Show More
@@ -1,270 +1,270 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-2011 The IPython Development Team |
|
14 | # Copyright (C) 2008-2011 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 | from __future__ import print_function |
|
24 | from __future__ import print_function | |
25 |
|
25 | |||
26 | import __builtin__ |
|
26 | import __builtin__ | |
27 |
|
27 | |||
28 | from IPython.config.configurable import Configurable |
|
28 | from IPython.config.configurable import Configurable | |
29 | from IPython.utils import io |
|
29 | from IPython.utils import io | |
30 | from IPython.utils.traitlets import Instance, List |
|
30 | from IPython.utils.traitlets import Instance, List | |
31 | from IPython.utils.warn import warn |
|
31 | from IPython.utils.warn import warn | |
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # Main displayhook class |
|
34 | # Main displayhook class | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
37 | # TODO: Move the various attributes (cache_size, [others now moved]). Some | |
38 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
38 | # of these are also attributes of InteractiveShell. They should be on ONE object | |
39 | # only and the other objects should ask that one object for their values. |
|
39 | # only and the other objects should ask that one object for their values. | |
40 |
|
40 | |||
41 | class DisplayHook(Configurable): |
|
41 | class DisplayHook(Configurable): | |
42 | """The custom IPython displayhook to replace sys.displayhook. |
|
42 | """The custom IPython displayhook to replace sys.displayhook. | |
43 |
|
43 | |||
44 | This class does many things, but the basic idea is that it is a callable |
|
44 | This class does many things, but the basic idea is that it is a callable | |
45 | that gets called anytime user code returns a value. |
|
45 | that gets called anytime user code returns a value. | |
46 | """ |
|
46 | """ | |
47 |
|
47 | |||
48 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
48 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
49 |
|
49 | |||
50 | def __init__(self, shell=None, cache_size=1000, config=None): |
|
50 | def __init__(self, shell=None, cache_size=1000, config=None): | |
51 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
51 | super(DisplayHook, self).__init__(shell=shell, config=config) | |
52 |
|
52 | |||
53 | cache_size_min = 3 |
|
53 | cache_size_min = 3 | |
54 | if cache_size <= 0: |
|
54 | if cache_size <= 0: | |
55 | self.do_full_cache = 0 |
|
55 | self.do_full_cache = 0 | |
56 | cache_size = 0 |
|
56 | cache_size = 0 | |
57 | elif cache_size < cache_size_min: |
|
57 | elif cache_size < cache_size_min: | |
58 | self.do_full_cache = 0 |
|
58 | self.do_full_cache = 0 | |
59 | cache_size = 0 |
|
59 | cache_size = 0 | |
60 | warn('caching was disabled (min value for cache size is %s).' % |
|
60 | warn('caching was disabled (min value for cache size is %s).' % | |
61 | cache_size_min,level=3) |
|
61 | cache_size_min,level=3) | |
62 | else: |
|
62 | else: | |
63 | self.do_full_cache = 1 |
|
63 | self.do_full_cache = 1 | |
64 |
|
64 | |||
65 | self.cache_size = cache_size |
|
65 | self.cache_size = cache_size | |
66 |
|
66 | |||
67 | # we need a reference to the user-level namespace |
|
67 | # we need a reference to the user-level namespace | |
68 | self.shell = shell |
|
68 | self.shell = shell | |
69 |
|
69 | |||
70 | self._,self.__,self.___ = '','','' |
|
70 | self._,self.__,self.___ = '','','' | |
71 |
|
71 | |||
72 | # these are deliberately global: |
|
72 | # these are deliberately global: | |
73 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
73 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
74 | self.shell.user_ns.update(to_user_ns) |
|
74 | self.shell.user_ns.update(to_user_ns) | |
75 |
|
75 | |||
76 | @property |
|
76 | @property | |
77 | def prompt_count(self): |
|
77 | def prompt_count(self): | |
78 | return self.shell.execution_count |
|
78 | return self.shell.execution_count | |
79 |
|
79 | |||
80 | #------------------------------------------------------------------------- |
|
80 | #------------------------------------------------------------------------- | |
81 | # Methods used in __call__. Override these methods to modify the behavior |
|
81 | # Methods used in __call__. Override these methods to modify the behavior | |
82 | # of the displayhook. |
|
82 | # of the displayhook. | |
83 | #------------------------------------------------------------------------- |
|
83 | #------------------------------------------------------------------------- | |
84 |
|
84 | |||
85 | def check_for_underscore(self): |
|
85 | def check_for_underscore(self): | |
86 | """Check if the user has set the '_' variable by hand.""" |
|
86 | """Check if the user has set the '_' variable by hand.""" | |
87 | # If something injected a '_' variable in __builtin__, delete |
|
87 | # If something injected a '_' variable in __builtin__, delete | |
88 | # ipython's automatic one so we don't clobber that. gettext() in |
|
88 | # ipython's automatic one so we don't clobber that. gettext() in | |
89 | # particular uses _, so we need to stay away from it. |
|
89 | # particular uses _, so we need to stay away from it. | |
90 | if '_' in __builtin__.__dict__: |
|
90 | if '_' in __builtin__.__dict__: | |
91 | try: |
|
91 | try: | |
92 | del self.shell.user_ns['_'] |
|
92 | del self.shell.user_ns['_'] | |
93 | except KeyError: |
|
93 | except KeyError: | |
94 | pass |
|
94 | pass | |
95 |
|
95 | |||
96 | def quiet(self): |
|
96 | def quiet(self): | |
97 | """Should we silence the display hook because of ';'?""" |
|
97 | """Should we silence the display hook because of ';'?""" | |
98 | # do not print output if input ends in ';' |
|
98 | # do not print output if input ends in ';' | |
99 | try: |
|
99 | try: | |
100 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
100 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] | |
101 | if cell.rstrip().endswith(';'): |
|
101 | if cell.rstrip().endswith(';'): | |
102 | return True |
|
102 | return True | |
103 | except IndexError: |
|
103 | except IndexError: | |
104 | # some uses of ipshellembed may fail here |
|
104 | # some uses of ipshellembed may fail here | |
105 | pass |
|
105 | pass | |
106 | return False |
|
106 | return False | |
107 |
|
107 | |||
108 | def start_displayhook(self): |
|
108 | def start_displayhook(self): | |
109 | """Start the displayhook, initializing resources.""" |
|
109 | """Start the displayhook, initializing resources.""" | |
110 | pass |
|
110 | pass | |
111 |
|
111 | |||
112 | def write_output_prompt(self): |
|
112 | def write_output_prompt(self): | |
113 | """Write the output prompt. |
|
113 | """Write the output prompt. | |
114 |
|
114 | |||
115 | The default implementation simply writes the prompt to |
|
115 | The default implementation simply writes the prompt to | |
116 | ``io.stdout``. |
|
116 | ``io.stdout``. | |
117 | """ |
|
117 | """ | |
118 | # Use write, not print which adds an extra space. |
|
118 | # Use write, not print which adds an extra space. | |
119 | io.stdout.write(self.shell.separate_out) |
|
119 | io.stdout.write(self.shell.separate_out) | |
120 | outprompt = self.shell.prompt_manager.render('out') |
|
120 | outprompt = self.shell.prompt_manager.render('out') | |
121 | if self.do_full_cache: |
|
121 | if self.do_full_cache: | |
122 | io.stdout.write(outprompt) |
|
122 | io.stdout.write(outprompt) | |
123 |
|
123 | |||
124 | def compute_format_data(self, result): |
|
124 | def compute_format_data(self, result): | |
125 | """Compute format data of the object to be displayed. |
|
125 | """Compute format data of the object to be displayed. | |
126 |
|
126 | |||
127 | The format data is a generalization of the :func:`repr` of an object. |
|
127 | The format data is a generalization of the :func:`repr` of an object. | |
128 | In the default implementation the format data is a :class:`dict` of |
|
128 | In the default implementation the format data is a :class:`dict` of | |
129 | key value pair where the keys are valid MIME types and the values |
|
129 | key value pair where the keys are valid MIME types and the values | |
130 | are JSON'able data structure containing the raw data for that MIME |
|
130 | are JSON'able data structure containing the raw data for that MIME | |
131 | type. It is up to frontends to determine pick a MIME to to use and |
|
131 | type. It is up to frontends to determine pick a MIME to to use and | |
132 | display that data in an appropriate manner. |
|
132 | display that data in an appropriate manner. | |
133 |
|
133 | |||
134 | This method only computes the format data for the object and should |
|
134 | This method only computes the format data for the object and should | |
135 | NOT actually print or write that to a stream. |
|
135 | NOT actually print or write that to a stream. | |
136 |
|
136 | |||
137 | Parameters |
|
137 | Parameters | |
138 | ---------- |
|
138 | ---------- | |
139 | result : object |
|
139 | result : object | |
140 | The Python object passed to the display hook, whose format will be |
|
140 | The Python object passed to the display hook, whose format will be | |
141 | computed. |
|
141 | computed. | |
142 |
|
142 | |||
143 | Returns |
|
143 | Returns | |
144 | ------- |
|
144 | ------- | |
145 | format_data : dict |
|
145 | format_data : dict | |
146 | A :class:`dict` whose keys are valid MIME types and values are |
|
146 | A :class:`dict` whose keys are valid MIME types and values are | |
147 | JSON'able raw data for that MIME type. It is recommended that |
|
147 | JSON'able raw data for that MIME type. It is recommended that | |
148 | all return values of this should always include the "text/plain" |
|
148 | all return values of this should always include the "text/plain" | |
149 | MIME type representation of the object. |
|
149 | MIME type representation of the object. | |
150 | """ |
|
150 | """ | |
151 | return self.shell.display_formatter.format(result) |
|
151 | return self.shell.display_formatter.format(result) | |
152 |
|
152 | |||
153 | def write_format_data(self, format_dict): |
|
153 | def write_format_data(self, format_dict): | |
154 | """Write the format data dict to the frontend. |
|
154 | """Write the format data dict to the frontend. | |
155 |
|
155 | |||
156 | This default version of this method simply writes the plain text |
|
156 | This default version of this method simply writes the plain text | |
157 | representation of the object to ``io.stdout``. Subclasses should |
|
157 | representation of the object to ``io.stdout``. Subclasses should | |
158 | override this method to send the entire `format_dict` to the |
|
158 | override this method to send the entire `format_dict` to the | |
159 | frontends. |
|
159 | frontends. | |
160 |
|
160 | |||
161 | Parameters |
|
161 | Parameters | |
162 | ---------- |
|
162 | ---------- | |
163 | format_dict : dict |
|
163 | format_dict : dict | |
164 | The format dict for the object passed to `sys.displayhook`. |
|
164 | The format dict for the object passed to `sys.displayhook`. | |
165 | """ |
|
165 | """ | |
166 | # We want to print because we want to always make sure we have a |
|
166 | # We want to print because we want to always make sure we have a | |
167 | # newline, even if all the prompt separators are ''. This is the |
|
167 | # newline, even if all the prompt separators are ''. This is the | |
168 | # standard IPython behavior. |
|
168 | # standard IPython behavior. | |
169 | result_repr = format_dict['text/plain'] |
|
169 | result_repr = format_dict['text/plain'] | |
170 | if '\n' in result_repr: |
|
170 | if '\n' in result_repr: | |
171 | # So that multi-line strings line up with the left column of |
|
171 | # So that multi-line strings line up with the left column of | |
172 | # the screen, instead of having the output prompt mess up |
|
172 | # the screen, instead of having the output prompt mess up | |
173 | # their first line. |
|
173 | # their first line. | |
174 | # We use the prompt template instead of the expanded prompt |
|
174 | # We use the prompt template instead of the expanded prompt | |
175 | # because the expansion may add ANSI escapes that will interfere |
|
175 | # because the expansion may add ANSI escapes that will interfere | |
176 | # with our ability to determine whether or not we should add |
|
176 | # with our ability to determine whether or not we should add | |
177 | # a newline. |
|
177 | # a newline. | |
178 | prompt_template = self.shell.prompt_manager.out_template |
|
178 | prompt_template = self.shell.prompt_manager.out_template | |
179 | if prompt_template and not prompt_template.endswith('\n'): |
|
179 | if prompt_template and not prompt_template.endswith('\n'): | |
180 | # But avoid extraneous empty lines. |
|
180 | # But avoid extraneous empty lines. | |
181 | result_repr = '\n' + result_repr |
|
181 | result_repr = '\n' + result_repr | |
182 |
|
182 | |||
183 | print(result_repr, file=io.stdout) |
|
183 | print(result_repr, file=io.stdout) | |
184 |
|
184 | |||
185 | def update_user_ns(self, result): |
|
185 | def update_user_ns(self, result): | |
186 | """Update user_ns with various things like _, __, _1, etc.""" |
|
186 | """Update user_ns with various things like _, __, _1, etc.""" | |
187 |
|
187 | |||
188 | # Avoid recursive reference when displaying _oh/Out |
|
188 | # Avoid recursive reference when displaying _oh/Out | |
189 | if result is not self.shell.user_ns['_oh']: |
|
189 | if result is not self.shell.user_ns['_oh']: | |
190 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
190 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
191 | warn('Output cache limit (currently '+ |
|
191 | warn('Output cache limit (currently '+ | |
192 | repr(self.cache_size)+' entries) hit.\n' |
|
192 | repr(self.cache_size)+' entries) hit.\n' | |
193 | 'Flushing cache and resetting history counter...\n' |
|
193 | 'Flushing cache and resetting history counter...\n' | |
194 | 'The only history variables available will be _,__,___ and _1\n' |
|
194 | 'The only history variables available will be _,__,___ and _1\n' | |
195 | 'with the current result.') |
|
195 | 'with the current result.') | |
196 |
|
196 | |||
197 | self.flush() |
|
197 | self.flush() | |
198 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
198 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
199 | # we cause buggy behavior for things like gettext). |
|
199 | # we cause buggy behavior for things like gettext). | |
200 |
|
200 | |||
201 | if '_' not in __builtin__.__dict__: |
|
201 | if '_' not in __builtin__.__dict__: | |
202 | self.___ = self.__ |
|
202 | self.___ = self.__ | |
203 | self.__ = self._ |
|
203 | self.__ = self._ | |
204 | self._ = result |
|
204 | self._ = result | |
205 | self.shell.push({'_':self._, |
|
205 | self.shell.push({'_':self._, | |
206 | '__':self.__, |
|
206 | '__':self.__, | |
207 | '___':self.___}, interactive=False) |
|
207 | '___':self.___}, interactive=False) | |
208 |
|
208 | |||
209 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
209 | # hackish access to top-level namespace to create _1,_2... dynamically | |
210 | to_main = {} |
|
210 | to_main = {} | |
211 | if self.do_full_cache: |
|
211 | if self.do_full_cache: | |
212 | new_result = '_'+repr(self.prompt_count) |
|
212 | new_result = '_'+repr(self.prompt_count) | |
213 | to_main[new_result] = result |
|
213 | to_main[new_result] = result | |
214 | self.shell.push(to_main, interactive=False) |
|
214 | self.shell.push(to_main, interactive=False) | |
215 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
215 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
216 |
|
216 | |||
217 | def log_output(self, format_dict): |
|
217 | def log_output(self, format_dict): | |
218 | """Log the output.""" |
|
218 | """Log the output.""" | |
219 | if self.shell.logger.log_output: |
|
219 | if self.shell.logger.log_output: | |
220 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
220 | self.shell.logger.log_write(format_dict['text/plain'], 'output') | |
221 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
221 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ | |
222 | format_dict['text/plain'] |
|
222 | format_dict['text/plain'] | |
223 |
|
223 | |||
224 | def finish_displayhook(self): |
|
224 | def finish_displayhook(self): | |
225 | """Finish up all displayhook activities.""" |
|
225 | """Finish up all displayhook activities.""" | |
226 | io.stdout.write(self.shell.separate_out2) |
|
226 | io.stdout.write(self.shell.separate_out2) | |
227 | io.stdout.flush() |
|
227 | io.stdout.flush() | |
228 |
|
228 | |||
229 | def __call__(self, result=None): |
|
229 | def __call__(self, result=None): | |
230 | """Printing with history cache management. |
|
230 | """Printing with history cache management. | |
231 |
|
231 | |||
232 | This is invoked everytime the interpreter needs to print, and is |
|
232 | This is invoked everytime the interpreter needs to print, and is | |
233 | activated by setting the variable sys.displayhook to it. |
|
233 | activated by setting the variable sys.displayhook to it. | |
234 | """ |
|
234 | """ | |
235 | self.check_for_underscore() |
|
235 | self.check_for_underscore() | |
236 | if result is not None and not self.quiet(): |
|
236 | if result is not None and not self.quiet(): | |
237 | self.start_displayhook() |
|
237 | self.start_displayhook() | |
238 | self.write_output_prompt() |
|
238 | self.write_output_prompt() | |
239 | format_dict = self.compute_format_data(result) |
|
239 | format_dict = self.compute_format_data(result) | |
240 | self.write_format_data(format_dict) |
|
240 | self.write_format_data(format_dict) | |
241 | self.update_user_ns(result) |
|
241 | self.update_user_ns(result) | |
242 | self.log_output(format_dict) |
|
242 | self.log_output(format_dict) | |
243 | self.finish_displayhook() |
|
243 | self.finish_displayhook() | |
244 |
|
244 | |||
245 | def flush(self): |
|
245 | def flush(self): | |
246 | if not self.do_full_cache: |
|
246 | if not self.do_full_cache: | |
247 |
raise ValueError |
|
247 | raise ValueError("You shouldn't have reached the cache flush " | |
248 | "if full caching is not enabled!" |
|
248 | "if full caching is not enabled!") | |
249 | # delete auto-generated vars from global namespace |
|
249 | # delete auto-generated vars from global namespace | |
250 |
|
250 | |||
251 | for n in range(1,self.prompt_count + 1): |
|
251 | for n in range(1,self.prompt_count + 1): | |
252 | key = '_'+repr(n) |
|
252 | key = '_'+repr(n) | |
253 | try: |
|
253 | try: | |
254 | del self.shell.user_ns[key] |
|
254 | del self.shell.user_ns[key] | |
255 | except: pass |
|
255 | except: pass | |
256 | # In some embedded circumstances, the user_ns doesn't have the |
|
256 | # In some embedded circumstances, the user_ns doesn't have the | |
257 | # '_oh' key set up. |
|
257 | # '_oh' key set up. | |
258 | oh = self.shell.user_ns.get('_oh', None) |
|
258 | oh = self.shell.user_ns.get('_oh', None) | |
259 | if oh is not None: |
|
259 | if oh is not None: | |
260 | oh.clear() |
|
260 | oh.clear() | |
261 |
|
261 | |||
262 | # Release our own references to objects: |
|
262 | # Release our own references to objects: | |
263 | self._, self.__, self.___ = '', '', '' |
|
263 | self._, self.__, self.___ = '', '', '' | |
264 |
|
264 | |||
265 | if '_' not in __builtin__.__dict__: |
|
265 | if '_' not in __builtin__.__dict__: | |
266 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
266 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
267 | import gc |
|
267 | import gc | |
268 | # TODO: Is this really needed? |
|
268 | # TODO: Is this really needed? | |
269 | gc.collect() |
|
269 | gc.collect() | |
270 |
|
270 |
@@ -1,3010 +1,3010 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 | from __future__ import print_function |
|
19 | from __future__ import print_function | |
20 |
|
20 | |||
21 | import __builtin__ as builtin_mod |
|
21 | import __builtin__ as builtin_mod | |
22 | import __future__ |
|
22 | import __future__ | |
23 | import abc |
|
23 | import abc | |
24 | import ast |
|
24 | import ast | |
25 | import atexit |
|
25 | import atexit | |
26 | import os |
|
26 | import os | |
27 | import re |
|
27 | import re | |
28 | import runpy |
|
28 | import runpy | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import types |
|
31 | import types | |
32 |
|
32 | |||
33 | # We need to use nested to support python 2.6, once we move to >=2.7, we can |
|
33 | # We need to use nested to support python 2.6, once we move to >=2.7, we can | |
34 | # use the with keyword's new builtin support for nested managers |
|
34 | # use the with keyword's new builtin support for nested managers | |
35 | try: |
|
35 | try: | |
36 | from contextlib import nested |
|
36 | from contextlib import nested | |
37 | except: |
|
37 | except: | |
38 | from IPython.utils.nested_context import nested |
|
38 | from IPython.utils.nested_context import nested | |
39 |
|
39 | |||
40 | from IPython.config.configurable import SingletonConfigurable |
|
40 | from IPython.config.configurable import SingletonConfigurable | |
41 | from IPython.core import debugger, oinspect |
|
41 | from IPython.core import debugger, oinspect | |
42 | from IPython.core import history as ipcorehist |
|
42 | from IPython.core import history as ipcorehist | |
43 | from IPython.core import magic |
|
43 | from IPython.core import magic | |
44 | from IPython.core import page |
|
44 | from IPython.core import page | |
45 | from IPython.core import prefilter |
|
45 | from IPython.core import prefilter | |
46 | from IPython.core import shadowns |
|
46 | from IPython.core import shadowns | |
47 | from IPython.core import ultratb |
|
47 | from IPython.core import ultratb | |
48 | from IPython.core.alias import AliasManager, AliasError |
|
48 | from IPython.core.alias import AliasManager, AliasError | |
49 | from IPython.core.autocall import ExitAutocall |
|
49 | from IPython.core.autocall import ExitAutocall | |
50 | from IPython.core.builtin_trap import BuiltinTrap |
|
50 | from IPython.core.builtin_trap import BuiltinTrap | |
51 | from IPython.core.compilerop import CachingCompiler |
|
51 | from IPython.core.compilerop import CachingCompiler | |
52 | from IPython.core.display_trap import DisplayTrap |
|
52 | from IPython.core.display_trap import DisplayTrap | |
53 | from IPython.core.displayhook import DisplayHook |
|
53 | from IPython.core.displayhook import DisplayHook | |
54 | from IPython.core.displaypub import DisplayPublisher |
|
54 | from IPython.core.displaypub import DisplayPublisher | |
55 | from IPython.core.error import UsageError |
|
55 | from IPython.core.error import UsageError | |
56 | from IPython.core.extensions import ExtensionManager |
|
56 | from IPython.core.extensions import ExtensionManager | |
57 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
57 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
58 | from IPython.core.formatters import DisplayFormatter |
|
58 | from IPython.core.formatters import DisplayFormatter | |
59 | from IPython.core.history import HistoryManager |
|
59 | from IPython.core.history import HistoryManager | |
60 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
60 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 | |
61 | from IPython.core.logger import Logger |
|
61 | from IPython.core.logger import Logger | |
62 | from IPython.core.macro import Macro |
|
62 | from IPython.core.macro import Macro | |
63 | from IPython.core.payload import PayloadManager |
|
63 | from IPython.core.payload import PayloadManager | |
64 | from IPython.core.plugin import PluginManager |
|
64 | from IPython.core.plugin import PluginManager | |
65 | from IPython.core.prefilter import PrefilterManager |
|
65 | from IPython.core.prefilter import PrefilterManager | |
66 | from IPython.core.profiledir import ProfileDir |
|
66 | from IPython.core.profiledir import ProfileDir | |
67 | from IPython.core.pylabtools import pylab_activate |
|
67 | from IPython.core.pylabtools import pylab_activate | |
68 | from IPython.core.prompts import PromptManager |
|
68 | from IPython.core.prompts import PromptManager | |
69 | from IPython.utils import PyColorize |
|
69 | from IPython.utils import PyColorize | |
70 | from IPython.utils import io |
|
70 | from IPython.utils import io | |
71 | from IPython.utils import py3compat |
|
71 | from IPython.utils import py3compat | |
72 | from IPython.utils import openpy |
|
72 | from IPython.utils import openpy | |
73 | from IPython.utils.doctestreload import doctest_reload |
|
73 | from IPython.utils.doctestreload import doctest_reload | |
74 | from IPython.utils.io import ask_yes_no |
|
74 | from IPython.utils.io import ask_yes_no | |
75 | from IPython.utils.ipstruct import Struct |
|
75 | from IPython.utils.ipstruct import Struct | |
76 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename |
|
76 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename | |
77 | from IPython.utils.pickleshare import PickleShareDB |
|
77 | from IPython.utils.pickleshare import PickleShareDB | |
78 | from IPython.utils.process import system, getoutput |
|
78 | from IPython.utils.process import system, getoutput | |
79 | from IPython.utils.strdispatch import StrDispatch |
|
79 | from IPython.utils.strdispatch import StrDispatch | |
80 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
80 | from IPython.utils.syspathcontext import prepended_to_syspath | |
81 | from IPython.utils.text import (format_screen, LSString, SList, |
|
81 | from IPython.utils.text import (format_screen, LSString, SList, | |
82 | DollarFormatter) |
|
82 | DollarFormatter) | |
83 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
83 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, | |
84 | List, Unicode, Instance, Type) |
|
84 | List, Unicode, Instance, Type) | |
85 | from IPython.utils.warn import warn, error |
|
85 | from IPython.utils.warn import warn, error | |
86 | import IPython.core.hooks |
|
86 | import IPython.core.hooks | |
87 |
|
87 | |||
88 | # FIXME: do this in a function to avoid circular dependencies |
|
88 | # FIXME: do this in a function to avoid circular dependencies | |
89 | # A better solution is to remove IPython.parallel.error, |
|
89 | # A better solution is to remove IPython.parallel.error, | |
90 | # and place those classes in IPython.core.error. |
|
90 | # and place those classes in IPython.core.error. | |
91 |
|
91 | |||
92 | class RemoteError(Exception): |
|
92 | class RemoteError(Exception): | |
93 | pass |
|
93 | pass | |
94 |
|
94 | |||
95 | def _import_remote_error(): |
|
95 | def _import_remote_error(): | |
96 | global RemoteError |
|
96 | global RemoteError | |
97 | try: |
|
97 | try: | |
98 | from IPython.parallel.error import RemoteError |
|
98 | from IPython.parallel.error import RemoteError | |
99 | except: |
|
99 | except: | |
100 | pass |
|
100 | pass | |
101 |
|
101 | |||
102 | _import_remote_error() |
|
102 | _import_remote_error() | |
103 |
|
103 | |||
104 | #----------------------------------------------------------------------------- |
|
104 | #----------------------------------------------------------------------------- | |
105 | # Globals |
|
105 | # Globals | |
106 | #----------------------------------------------------------------------------- |
|
106 | #----------------------------------------------------------------------------- | |
107 |
|
107 | |||
108 | # compiled regexps for autoindent management |
|
108 | # compiled regexps for autoindent management | |
109 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
109 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
110 |
|
110 | |||
111 | #----------------------------------------------------------------------------- |
|
111 | #----------------------------------------------------------------------------- | |
112 | # Utilities |
|
112 | # Utilities | |
113 | #----------------------------------------------------------------------------- |
|
113 | #----------------------------------------------------------------------------- | |
114 |
|
114 | |||
115 | def softspace(file, newvalue): |
|
115 | def softspace(file, newvalue): | |
116 | """Copied from code.py, to remove the dependency""" |
|
116 | """Copied from code.py, to remove the dependency""" | |
117 |
|
117 | |||
118 | oldvalue = 0 |
|
118 | oldvalue = 0 | |
119 | try: |
|
119 | try: | |
120 | oldvalue = file.softspace |
|
120 | oldvalue = file.softspace | |
121 | except AttributeError: |
|
121 | except AttributeError: | |
122 | pass |
|
122 | pass | |
123 | try: |
|
123 | try: | |
124 | file.softspace = newvalue |
|
124 | file.softspace = newvalue | |
125 | except (AttributeError, TypeError): |
|
125 | except (AttributeError, TypeError): | |
126 | # "attribute-less object" or "read-only attributes" |
|
126 | # "attribute-less object" or "read-only attributes" | |
127 | pass |
|
127 | pass | |
128 | return oldvalue |
|
128 | return oldvalue | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | def no_op(*a, **kw): pass |
|
131 | def no_op(*a, **kw): pass | |
132 |
|
132 | |||
133 | class NoOpContext(object): |
|
133 | class NoOpContext(object): | |
134 | def __enter__(self): pass |
|
134 | def __enter__(self): pass | |
135 | def __exit__(self, type, value, traceback): pass |
|
135 | def __exit__(self, type, value, traceback): pass | |
136 | no_op_context = NoOpContext() |
|
136 | no_op_context = NoOpContext() | |
137 |
|
137 | |||
138 | class SpaceInInput(Exception): pass |
|
138 | class SpaceInInput(Exception): pass | |
139 |
|
139 | |||
140 | class Bunch: pass |
|
140 | class Bunch: pass | |
141 |
|
141 | |||
142 |
|
142 | |||
143 | def get_default_colors(): |
|
143 | def get_default_colors(): | |
144 | if sys.platform=='darwin': |
|
144 | if sys.platform=='darwin': | |
145 | return "LightBG" |
|
145 | return "LightBG" | |
146 | elif os.name=='nt': |
|
146 | elif os.name=='nt': | |
147 | return 'Linux' |
|
147 | return 'Linux' | |
148 | else: |
|
148 | else: | |
149 | return 'Linux' |
|
149 | return 'Linux' | |
150 |
|
150 | |||
151 |
|
151 | |||
152 | class SeparateUnicode(Unicode): |
|
152 | class SeparateUnicode(Unicode): | |
153 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
153 | """A Unicode subclass to validate separate_in, separate_out, etc. | |
154 |
|
154 | |||
155 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
155 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. | |
156 | """ |
|
156 | """ | |
157 |
|
157 | |||
158 | def validate(self, obj, value): |
|
158 | def validate(self, obj, value): | |
159 | if value == '0': value = '' |
|
159 | if value == '0': value = '' | |
160 | value = value.replace('\\n','\n') |
|
160 | value = value.replace('\\n','\n') | |
161 | return super(SeparateUnicode, self).validate(obj, value) |
|
161 | return super(SeparateUnicode, self).validate(obj, value) | |
162 |
|
162 | |||
163 |
|
163 | |||
164 | class ReadlineNoRecord(object): |
|
164 | class ReadlineNoRecord(object): | |
165 | """Context manager to execute some code, then reload readline history |
|
165 | """Context manager to execute some code, then reload readline history | |
166 | so that interactive input to the code doesn't appear when pressing up.""" |
|
166 | so that interactive input to the code doesn't appear when pressing up.""" | |
167 | def __init__(self, shell): |
|
167 | def __init__(self, shell): | |
168 | self.shell = shell |
|
168 | self.shell = shell | |
169 | self._nested_level = 0 |
|
169 | self._nested_level = 0 | |
170 |
|
170 | |||
171 | def __enter__(self): |
|
171 | def __enter__(self): | |
172 | if self._nested_level == 0: |
|
172 | if self._nested_level == 0: | |
173 | try: |
|
173 | try: | |
174 | self.orig_length = self.current_length() |
|
174 | self.orig_length = self.current_length() | |
175 | self.readline_tail = self.get_readline_tail() |
|
175 | self.readline_tail = self.get_readline_tail() | |
176 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
176 | except (AttributeError, IndexError): # Can fail with pyreadline | |
177 | self.orig_length, self.readline_tail = 999999, [] |
|
177 | self.orig_length, self.readline_tail = 999999, [] | |
178 | self._nested_level += 1 |
|
178 | self._nested_level += 1 | |
179 |
|
179 | |||
180 | def __exit__(self, type, value, traceback): |
|
180 | def __exit__(self, type, value, traceback): | |
181 | self._nested_level -= 1 |
|
181 | self._nested_level -= 1 | |
182 | if self._nested_level == 0: |
|
182 | if self._nested_level == 0: | |
183 | # Try clipping the end if it's got longer |
|
183 | # Try clipping the end if it's got longer | |
184 | try: |
|
184 | try: | |
185 | e = self.current_length() - self.orig_length |
|
185 | e = self.current_length() - self.orig_length | |
186 | if e > 0: |
|
186 | if e > 0: | |
187 | for _ in range(e): |
|
187 | for _ in range(e): | |
188 | self.shell.readline.remove_history_item(self.orig_length) |
|
188 | self.shell.readline.remove_history_item(self.orig_length) | |
189 |
|
189 | |||
190 | # If it still doesn't match, just reload readline history. |
|
190 | # If it still doesn't match, just reload readline history. | |
191 | if self.current_length() != self.orig_length \ |
|
191 | if self.current_length() != self.orig_length \ | |
192 | or self.get_readline_tail() != self.readline_tail: |
|
192 | or self.get_readline_tail() != self.readline_tail: | |
193 | self.shell.refill_readline_hist() |
|
193 | self.shell.refill_readline_hist() | |
194 | except (AttributeError, IndexError): |
|
194 | except (AttributeError, IndexError): | |
195 | pass |
|
195 | pass | |
196 | # Returning False will cause exceptions to propagate |
|
196 | # Returning False will cause exceptions to propagate | |
197 | return False |
|
197 | return False | |
198 |
|
198 | |||
199 | def current_length(self): |
|
199 | def current_length(self): | |
200 | return self.shell.readline.get_current_history_length() |
|
200 | return self.shell.readline.get_current_history_length() | |
201 |
|
201 | |||
202 | def get_readline_tail(self, n=10): |
|
202 | def get_readline_tail(self, n=10): | |
203 | """Get the last n items in readline history.""" |
|
203 | """Get the last n items in readline history.""" | |
204 | end = self.shell.readline.get_current_history_length() + 1 |
|
204 | end = self.shell.readline.get_current_history_length() + 1 | |
205 | start = max(end-n, 1) |
|
205 | start = max(end-n, 1) | |
206 | ghi = self.shell.readline.get_history_item |
|
206 | ghi = self.shell.readline.get_history_item | |
207 | return [ghi(x) for x in range(start, end)] |
|
207 | return [ghi(x) for x in range(start, end)] | |
208 |
|
208 | |||
209 | #----------------------------------------------------------------------------- |
|
209 | #----------------------------------------------------------------------------- | |
210 | # Main IPython class |
|
210 | # Main IPython class | |
211 | #----------------------------------------------------------------------------- |
|
211 | #----------------------------------------------------------------------------- | |
212 |
|
212 | |||
213 | class InteractiveShell(SingletonConfigurable): |
|
213 | class InteractiveShell(SingletonConfigurable): | |
214 | """An enhanced, interactive shell for Python.""" |
|
214 | """An enhanced, interactive shell for Python.""" | |
215 |
|
215 | |||
216 | _instance = None |
|
216 | _instance = None | |
217 |
|
217 | |||
218 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
218 | autocall = Enum((0,1,2), default_value=0, config=True, help= | |
219 | """ |
|
219 | """ | |
220 | Make IPython automatically call any callable object even if you didn't |
|
220 | Make IPython automatically call any callable object even if you didn't | |
221 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
221 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
222 | automatically. The value can be '0' to disable the feature, '1' for |
|
222 | automatically. The value can be '0' to disable the feature, '1' for | |
223 | 'smart' autocall, where it is not applied if there are no more |
|
223 | 'smart' autocall, where it is not applied if there are no more | |
224 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
224 | arguments on the line, and '2' for 'full' autocall, where all callable | |
225 | objects are automatically called (even if no arguments are present). |
|
225 | objects are automatically called (even if no arguments are present). | |
226 | """ |
|
226 | """ | |
227 | ) |
|
227 | ) | |
228 | # TODO: remove all autoindent logic and put into frontends. |
|
228 | # TODO: remove all autoindent logic and put into frontends. | |
229 | # We can't do this yet because even runlines uses the autoindent. |
|
229 | # We can't do this yet because even runlines uses the autoindent. | |
230 | autoindent = CBool(True, config=True, help= |
|
230 | autoindent = CBool(True, config=True, help= | |
231 | """ |
|
231 | """ | |
232 | Autoindent IPython code entered interactively. |
|
232 | Autoindent IPython code entered interactively. | |
233 | """ |
|
233 | """ | |
234 | ) |
|
234 | ) | |
235 | automagic = CBool(True, config=True, help= |
|
235 | automagic = CBool(True, config=True, help= | |
236 | """ |
|
236 | """ | |
237 | Enable magic commands to be called without the leading %. |
|
237 | Enable magic commands to be called without the leading %. | |
238 | """ |
|
238 | """ | |
239 | ) |
|
239 | ) | |
240 | cache_size = Integer(1000, config=True, help= |
|
240 | cache_size = Integer(1000, config=True, help= | |
241 | """ |
|
241 | """ | |
242 | Set the size of the output cache. The default is 1000, you can |
|
242 | Set the size of the output cache. The default is 1000, you can | |
243 | change it permanently in your config file. Setting it to 0 completely |
|
243 | change it permanently in your config file. Setting it to 0 completely | |
244 | disables the caching system, and the minimum value accepted is 20 (if |
|
244 | disables the caching system, and the minimum value accepted is 20 (if | |
245 | you provide a value less than 20, it is reset to 0 and a warning is |
|
245 | you provide a value less than 20, it is reset to 0 and a warning is | |
246 | issued). This limit is defined because otherwise you'll spend more |
|
246 | issued). This limit is defined because otherwise you'll spend more | |
247 | time re-flushing a too small cache than working |
|
247 | time re-flushing a too small cache than working | |
248 | """ |
|
248 | """ | |
249 | ) |
|
249 | ) | |
250 | color_info = CBool(True, config=True, help= |
|
250 | color_info = CBool(True, config=True, help= | |
251 | """ |
|
251 | """ | |
252 | Use colors for displaying information about objects. Because this |
|
252 | Use colors for displaying information about objects. Because this | |
253 | information is passed through a pager (like 'less'), and some pagers |
|
253 | information is passed through a pager (like 'less'), and some pagers | |
254 | get confused with color codes, this capability can be turned off. |
|
254 | get confused with color codes, this capability can be turned off. | |
255 | """ |
|
255 | """ | |
256 | ) |
|
256 | ) | |
257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
258 | default_value=get_default_colors(), config=True, |
|
258 | default_value=get_default_colors(), config=True, | |
259 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
259 | help="Set the color scheme (NoColor, Linux, or LightBG)." | |
260 | ) |
|
260 | ) | |
261 | colors_force = CBool(False, help= |
|
261 | colors_force = CBool(False, help= | |
262 | """ |
|
262 | """ | |
263 | Force use of ANSI color codes, regardless of OS and readline |
|
263 | Force use of ANSI color codes, regardless of OS and readline | |
264 | availability. |
|
264 | availability. | |
265 | """ |
|
265 | """ | |
266 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
266 | # FIXME: This is essentially a hack to allow ZMQShell to show colors | |
267 | # without readline on Win32. When the ZMQ formatting system is |
|
267 | # without readline on Win32. When the ZMQ formatting system is | |
268 | # refactored, this should be removed. |
|
268 | # refactored, this should be removed. | |
269 | ) |
|
269 | ) | |
270 | debug = CBool(False, config=True) |
|
270 | debug = CBool(False, config=True) | |
271 | deep_reload = CBool(False, config=True, help= |
|
271 | deep_reload = CBool(False, config=True, help= | |
272 | """ |
|
272 | """ | |
273 | Enable deep (recursive) reloading by default. IPython can use the |
|
273 | Enable deep (recursive) reloading by default. IPython can use the | |
274 | deep_reload module which reloads changes in modules recursively (it |
|
274 | deep_reload module which reloads changes in modules recursively (it | |
275 | replaces the reload() function, so you don't need to change anything to |
|
275 | replaces the reload() function, so you don't need to change anything to | |
276 | use it). deep_reload() forces a full reload of modules whose code may |
|
276 | use it). deep_reload() forces a full reload of modules whose code may | |
277 | have changed, which the default reload() function does not. When |
|
277 | have changed, which the default reload() function does not. When | |
278 | deep_reload is off, IPython will use the normal reload(), but |
|
278 | deep_reload is off, IPython will use the normal reload(), but | |
279 | deep_reload will still be available as dreload(). |
|
279 | deep_reload will still be available as dreload(). | |
280 | """ |
|
280 | """ | |
281 | ) |
|
281 | ) | |
282 | disable_failing_post_execute = CBool(False, config=True, |
|
282 | disable_failing_post_execute = CBool(False, config=True, | |
283 | help="Don't call post-execute functions that have failed in the past." |
|
283 | help="Don't call post-execute functions that have failed in the past." | |
284 | ) |
|
284 | ) | |
285 | display_formatter = Instance(DisplayFormatter) |
|
285 | display_formatter = Instance(DisplayFormatter) | |
286 | displayhook_class = Type(DisplayHook) |
|
286 | displayhook_class = Type(DisplayHook) | |
287 | display_pub_class = Type(DisplayPublisher) |
|
287 | display_pub_class = Type(DisplayPublisher) | |
288 |
|
288 | |||
289 | exit_now = CBool(False) |
|
289 | exit_now = CBool(False) | |
290 | exiter = Instance(ExitAutocall) |
|
290 | exiter = Instance(ExitAutocall) | |
291 | def _exiter_default(self): |
|
291 | def _exiter_default(self): | |
292 | return ExitAutocall(self) |
|
292 | return ExitAutocall(self) | |
293 | # Monotonically increasing execution counter |
|
293 | # Monotonically increasing execution counter | |
294 | execution_count = Integer(1) |
|
294 | execution_count = Integer(1) | |
295 | filename = Unicode("<ipython console>") |
|
295 | filename = Unicode("<ipython console>") | |
296 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
296 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
297 |
|
297 | |||
298 | # Input splitter, to split entire cells of input into either individual |
|
298 | # Input splitter, to split entire cells of input into either individual | |
299 | # interactive statements or whole blocks. |
|
299 | # interactive statements or whole blocks. | |
300 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
300 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
301 | (), {}) |
|
301 | (), {}) | |
302 | logstart = CBool(False, config=True, help= |
|
302 | logstart = CBool(False, config=True, help= | |
303 | """ |
|
303 | """ | |
304 | Start logging to the default log file. |
|
304 | Start logging to the default log file. | |
305 | """ |
|
305 | """ | |
306 | ) |
|
306 | ) | |
307 | logfile = Unicode('', config=True, help= |
|
307 | logfile = Unicode('', config=True, help= | |
308 | """ |
|
308 | """ | |
309 | The name of the logfile to use. |
|
309 | The name of the logfile to use. | |
310 | """ |
|
310 | """ | |
311 | ) |
|
311 | ) | |
312 | logappend = Unicode('', config=True, help= |
|
312 | logappend = Unicode('', config=True, help= | |
313 | """ |
|
313 | """ | |
314 | Start logging to the given file in append mode. |
|
314 | Start logging to the given file in append mode. | |
315 | """ |
|
315 | """ | |
316 | ) |
|
316 | ) | |
317 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
317 | object_info_string_level = Enum((0,1,2), default_value=0, | |
318 | config=True) |
|
318 | config=True) | |
319 | pdb = CBool(False, config=True, help= |
|
319 | pdb = CBool(False, config=True, help= | |
320 | """ |
|
320 | """ | |
321 | Automatically call the pdb debugger after every exception. |
|
321 | Automatically call the pdb debugger after every exception. | |
322 | """ |
|
322 | """ | |
323 | ) |
|
323 | ) | |
324 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
324 | multiline_history = CBool(sys.platform != 'win32', config=True, | |
325 | help="Save multi-line entries as one entry in readline history" |
|
325 | help="Save multi-line entries as one entry in readline history" | |
326 | ) |
|
326 | ) | |
327 |
|
327 | |||
328 | # deprecated prompt traits: |
|
328 | # deprecated prompt traits: | |
329 |
|
329 | |||
330 | prompt_in1 = Unicode('In [\\#]: ', config=True, |
|
330 | prompt_in1 = Unicode('In [\\#]: ', config=True, | |
331 | help="Deprecated, use PromptManager.in_template") |
|
331 | help="Deprecated, use PromptManager.in_template") | |
332 | prompt_in2 = Unicode(' .\\D.: ', config=True, |
|
332 | prompt_in2 = Unicode(' .\\D.: ', config=True, | |
333 | help="Deprecated, use PromptManager.in2_template") |
|
333 | help="Deprecated, use PromptManager.in2_template") | |
334 | prompt_out = Unicode('Out[\\#]: ', config=True, |
|
334 | prompt_out = Unicode('Out[\\#]: ', config=True, | |
335 | help="Deprecated, use PromptManager.out_template") |
|
335 | help="Deprecated, use PromptManager.out_template") | |
336 | prompts_pad_left = CBool(True, config=True, |
|
336 | prompts_pad_left = CBool(True, config=True, | |
337 | help="Deprecated, use PromptManager.justify") |
|
337 | help="Deprecated, use PromptManager.justify") | |
338 |
|
338 | |||
339 | def _prompt_trait_changed(self, name, old, new): |
|
339 | def _prompt_trait_changed(self, name, old, new): | |
340 | table = { |
|
340 | table = { | |
341 | 'prompt_in1' : 'in_template', |
|
341 | 'prompt_in1' : 'in_template', | |
342 | 'prompt_in2' : 'in2_template', |
|
342 | 'prompt_in2' : 'in2_template', | |
343 | 'prompt_out' : 'out_template', |
|
343 | 'prompt_out' : 'out_template', | |
344 | 'prompts_pad_left' : 'justify', |
|
344 | 'prompts_pad_left' : 'justify', | |
345 | } |
|
345 | } | |
346 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format( |
|
346 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format( | |
347 | name=name, newname=table[name]) |
|
347 | name=name, newname=table[name]) | |
348 | ) |
|
348 | ) | |
349 | # protect against weird cases where self.config may not exist: |
|
349 | # protect against weird cases where self.config may not exist: | |
350 | if self.config is not None: |
|
350 | if self.config is not None: | |
351 | # propagate to corresponding PromptManager trait |
|
351 | # propagate to corresponding PromptManager trait | |
352 | setattr(self.config.PromptManager, table[name], new) |
|
352 | setattr(self.config.PromptManager, table[name], new) | |
353 |
|
353 | |||
354 | _prompt_in1_changed = _prompt_trait_changed |
|
354 | _prompt_in1_changed = _prompt_trait_changed | |
355 | _prompt_in2_changed = _prompt_trait_changed |
|
355 | _prompt_in2_changed = _prompt_trait_changed | |
356 | _prompt_out_changed = _prompt_trait_changed |
|
356 | _prompt_out_changed = _prompt_trait_changed | |
357 | _prompt_pad_left_changed = _prompt_trait_changed |
|
357 | _prompt_pad_left_changed = _prompt_trait_changed | |
358 |
|
358 | |||
359 | show_rewritten_input = CBool(True, config=True, |
|
359 | show_rewritten_input = CBool(True, config=True, | |
360 | help="Show rewritten input, e.g. for autocall." |
|
360 | help="Show rewritten input, e.g. for autocall." | |
361 | ) |
|
361 | ) | |
362 |
|
362 | |||
363 | quiet = CBool(False, config=True) |
|
363 | quiet = CBool(False, config=True) | |
364 |
|
364 | |||
365 | history_length = Integer(10000, config=True) |
|
365 | history_length = Integer(10000, config=True) | |
366 |
|
366 | |||
367 | # The readline stuff will eventually be moved to the terminal subclass |
|
367 | # The readline stuff will eventually be moved to the terminal subclass | |
368 | # but for now, we can't do that as readline is welded in everywhere. |
|
368 | # but for now, we can't do that as readline is welded in everywhere. | |
369 | readline_use = CBool(True, config=True) |
|
369 | readline_use = CBool(True, config=True) | |
370 | readline_remove_delims = Unicode('-/~', config=True) |
|
370 | readline_remove_delims = Unicode('-/~', config=True) | |
371 | # don't use \M- bindings by default, because they |
|
371 | # don't use \M- bindings by default, because they | |
372 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
372 | # conflict with 8-bit encodings. See gh-58,gh-88 | |
373 | readline_parse_and_bind = List([ |
|
373 | readline_parse_and_bind = List([ | |
374 | 'tab: complete', |
|
374 | 'tab: complete', | |
375 | '"\C-l": clear-screen', |
|
375 | '"\C-l": clear-screen', | |
376 | 'set show-all-if-ambiguous on', |
|
376 | 'set show-all-if-ambiguous on', | |
377 | '"\C-o": tab-insert', |
|
377 | '"\C-o": tab-insert', | |
378 | '"\C-r": reverse-search-history', |
|
378 | '"\C-r": reverse-search-history', | |
379 | '"\C-s": forward-search-history', |
|
379 | '"\C-s": forward-search-history', | |
380 | '"\C-p": history-search-backward', |
|
380 | '"\C-p": history-search-backward', | |
381 | '"\C-n": history-search-forward', |
|
381 | '"\C-n": history-search-forward', | |
382 | '"\e[A": history-search-backward', |
|
382 | '"\e[A": history-search-backward', | |
383 | '"\e[B": history-search-forward', |
|
383 | '"\e[B": history-search-forward', | |
384 | '"\C-k": kill-line', |
|
384 | '"\C-k": kill-line', | |
385 | '"\C-u": unix-line-discard', |
|
385 | '"\C-u": unix-line-discard', | |
386 | ], allow_none=False, config=True) |
|
386 | ], allow_none=False, config=True) | |
387 |
|
387 | |||
388 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
388 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], | |
389 | default_value='last_expr', config=True, |
|
389 | default_value='last_expr', config=True, | |
390 | help=""" |
|
390 | help=""" | |
391 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
391 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
392 | run interactively (displaying output from expressions).""") |
|
392 | run interactively (displaying output from expressions).""") | |
393 |
|
393 | |||
394 | # TODO: this part of prompt management should be moved to the frontends. |
|
394 | # TODO: this part of prompt management should be moved to the frontends. | |
395 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
395 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
396 | separate_in = SeparateUnicode('\n', config=True) |
|
396 | separate_in = SeparateUnicode('\n', config=True) | |
397 | separate_out = SeparateUnicode('', config=True) |
|
397 | separate_out = SeparateUnicode('', config=True) | |
398 | separate_out2 = SeparateUnicode('', config=True) |
|
398 | separate_out2 = SeparateUnicode('', config=True) | |
399 | wildcards_case_sensitive = CBool(True, config=True) |
|
399 | wildcards_case_sensitive = CBool(True, config=True) | |
400 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
400 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
401 | default_value='Context', config=True) |
|
401 | default_value='Context', config=True) | |
402 |
|
402 | |||
403 | # Subcomponents of InteractiveShell |
|
403 | # Subcomponents of InteractiveShell | |
404 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
404 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
405 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
405 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
406 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
406 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
407 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
407 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
408 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
408 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
409 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
409 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
410 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
410 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
411 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
411 | history_manager = Instance('IPython.core.history.HistoryManager') | |
412 | magics_manager = Instance('IPython.core.magic.MagicsManager') |
|
412 | magics_manager = Instance('IPython.core.magic.MagicsManager') | |
413 |
|
413 | |||
414 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
414 | profile_dir = Instance('IPython.core.application.ProfileDir') | |
415 | @property |
|
415 | @property | |
416 | def profile(self): |
|
416 | def profile(self): | |
417 | if self.profile_dir is not None: |
|
417 | if self.profile_dir is not None: | |
418 | name = os.path.basename(self.profile_dir.location) |
|
418 | name = os.path.basename(self.profile_dir.location) | |
419 | return name.replace('profile_','') |
|
419 | return name.replace('profile_','') | |
420 |
|
420 | |||
421 |
|
421 | |||
422 | # Private interface |
|
422 | # Private interface | |
423 | _post_execute = Instance(dict) |
|
423 | _post_execute = Instance(dict) | |
424 |
|
424 | |||
425 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
425 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, | |
426 | user_module=None, user_ns=None, |
|
426 | user_module=None, user_ns=None, | |
427 | custom_exceptions=((), None)): |
|
427 | custom_exceptions=((), None)): | |
428 |
|
428 | |||
429 | # This is where traits with a config_key argument are updated |
|
429 | # This is where traits with a config_key argument are updated | |
430 | # from the values on config. |
|
430 | # from the values on config. | |
431 | super(InteractiveShell, self).__init__(config=config) |
|
431 | super(InteractiveShell, self).__init__(config=config) | |
432 | self.configurables = [self] |
|
432 | self.configurables = [self] | |
433 |
|
433 | |||
434 | # These are relatively independent and stateless |
|
434 | # These are relatively independent and stateless | |
435 | self.init_ipython_dir(ipython_dir) |
|
435 | self.init_ipython_dir(ipython_dir) | |
436 | self.init_profile_dir(profile_dir) |
|
436 | self.init_profile_dir(profile_dir) | |
437 | self.init_instance_attrs() |
|
437 | self.init_instance_attrs() | |
438 | self.init_environment() |
|
438 | self.init_environment() | |
439 |
|
439 | |||
440 | # Check if we're in a virtualenv, and set up sys.path. |
|
440 | # Check if we're in a virtualenv, and set up sys.path. | |
441 | self.init_virtualenv() |
|
441 | self.init_virtualenv() | |
442 |
|
442 | |||
443 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
443 | # Create namespaces (user_ns, user_global_ns, etc.) | |
444 | self.init_create_namespaces(user_module, user_ns) |
|
444 | self.init_create_namespaces(user_module, user_ns) | |
445 | # This has to be done after init_create_namespaces because it uses |
|
445 | # This has to be done after init_create_namespaces because it uses | |
446 | # something in self.user_ns, but before init_sys_modules, which |
|
446 | # something in self.user_ns, but before init_sys_modules, which | |
447 | # is the first thing to modify sys. |
|
447 | # is the first thing to modify sys. | |
448 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
448 | # TODO: When we override sys.stdout and sys.stderr before this class | |
449 | # is created, we are saving the overridden ones here. Not sure if this |
|
449 | # is created, we are saving the overridden ones here. Not sure if this | |
450 | # is what we want to do. |
|
450 | # is what we want to do. | |
451 | self.save_sys_module_state() |
|
451 | self.save_sys_module_state() | |
452 | self.init_sys_modules() |
|
452 | self.init_sys_modules() | |
453 |
|
453 | |||
454 | # While we're trying to have each part of the code directly access what |
|
454 | # While we're trying to have each part of the code directly access what | |
455 | # it needs without keeping redundant references to objects, we have too |
|
455 | # it needs without keeping redundant references to objects, we have too | |
456 | # much legacy code that expects ip.db to exist. |
|
456 | # much legacy code that expects ip.db to exist. | |
457 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
457 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
458 |
|
458 | |||
459 | self.init_history() |
|
459 | self.init_history() | |
460 | self.init_encoding() |
|
460 | self.init_encoding() | |
461 | self.init_prefilter() |
|
461 | self.init_prefilter() | |
462 |
|
462 | |||
463 | self.init_syntax_highlighting() |
|
463 | self.init_syntax_highlighting() | |
464 | self.init_hooks() |
|
464 | self.init_hooks() | |
465 | self.init_pushd_popd_magic() |
|
465 | self.init_pushd_popd_magic() | |
466 | # self.init_traceback_handlers use to be here, but we moved it below |
|
466 | # self.init_traceback_handlers use to be here, but we moved it below | |
467 | # because it and init_io have to come after init_readline. |
|
467 | # because it and init_io have to come after init_readline. | |
468 | self.init_user_ns() |
|
468 | self.init_user_ns() | |
469 | self.init_logger() |
|
469 | self.init_logger() | |
470 | self.init_alias() |
|
470 | self.init_alias() | |
471 | self.init_builtins() |
|
471 | self.init_builtins() | |
472 |
|
472 | |||
473 | # pre_config_initialization |
|
473 | # pre_config_initialization | |
474 |
|
474 | |||
475 | # The next section should contain everything that was in ipmaker. |
|
475 | # The next section should contain everything that was in ipmaker. | |
476 | self.init_logstart() |
|
476 | self.init_logstart() | |
477 |
|
477 | |||
478 | # The following was in post_config_initialization |
|
478 | # The following was in post_config_initialization | |
479 | self.init_inspector() |
|
479 | self.init_inspector() | |
480 | # init_readline() must come before init_io(), because init_io uses |
|
480 | # init_readline() must come before init_io(), because init_io uses | |
481 | # readline related things. |
|
481 | # readline related things. | |
482 | self.init_readline() |
|
482 | self.init_readline() | |
483 | # We save this here in case user code replaces raw_input, but it needs |
|
483 | # We save this here in case user code replaces raw_input, but it needs | |
484 | # to be after init_readline(), because PyPy's readline works by replacing |
|
484 | # to be after init_readline(), because PyPy's readline works by replacing | |
485 | # raw_input. |
|
485 | # raw_input. | |
486 | if py3compat.PY3: |
|
486 | if py3compat.PY3: | |
487 | self.raw_input_original = input |
|
487 | self.raw_input_original = input | |
488 | else: |
|
488 | else: | |
489 | self.raw_input_original = raw_input |
|
489 | self.raw_input_original = raw_input | |
490 | # init_completer must come after init_readline, because it needs to |
|
490 | # init_completer must come after init_readline, because it needs to | |
491 | # know whether readline is present or not system-wide to configure the |
|
491 | # know whether readline is present or not system-wide to configure the | |
492 | # completers, since the completion machinery can now operate |
|
492 | # completers, since the completion machinery can now operate | |
493 | # independently of readline (e.g. over the network) |
|
493 | # independently of readline (e.g. over the network) | |
494 | self.init_completer() |
|
494 | self.init_completer() | |
495 | # TODO: init_io() needs to happen before init_traceback handlers |
|
495 | # TODO: init_io() needs to happen before init_traceback handlers | |
496 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
496 | # because the traceback handlers hardcode the stdout/stderr streams. | |
497 | # This logic in in debugger.Pdb and should eventually be changed. |
|
497 | # This logic in in debugger.Pdb and should eventually be changed. | |
498 | self.init_io() |
|
498 | self.init_io() | |
499 | self.init_traceback_handlers(custom_exceptions) |
|
499 | self.init_traceback_handlers(custom_exceptions) | |
500 | self.init_prompts() |
|
500 | self.init_prompts() | |
501 | self.init_display_formatter() |
|
501 | self.init_display_formatter() | |
502 | self.init_display_pub() |
|
502 | self.init_display_pub() | |
503 | self.init_displayhook() |
|
503 | self.init_displayhook() | |
504 | self.init_reload_doctest() |
|
504 | self.init_reload_doctest() | |
505 | self.init_magics() |
|
505 | self.init_magics() | |
506 | self.init_pdb() |
|
506 | self.init_pdb() | |
507 | self.init_extension_manager() |
|
507 | self.init_extension_manager() | |
508 | self.init_plugin_manager() |
|
508 | self.init_plugin_manager() | |
509 | self.init_payload() |
|
509 | self.init_payload() | |
510 | self.hooks.late_startup_hook() |
|
510 | self.hooks.late_startup_hook() | |
511 | atexit.register(self.atexit_operations) |
|
511 | atexit.register(self.atexit_operations) | |
512 |
|
512 | |||
513 | def get_ipython(self): |
|
513 | def get_ipython(self): | |
514 | """Return the currently running IPython instance.""" |
|
514 | """Return the currently running IPython instance.""" | |
515 | return self |
|
515 | return self | |
516 |
|
516 | |||
517 | #------------------------------------------------------------------------- |
|
517 | #------------------------------------------------------------------------- | |
518 | # Trait changed handlers |
|
518 | # Trait changed handlers | |
519 | #------------------------------------------------------------------------- |
|
519 | #------------------------------------------------------------------------- | |
520 |
|
520 | |||
521 | def _ipython_dir_changed(self, name, new): |
|
521 | def _ipython_dir_changed(self, name, new): | |
522 | if not os.path.isdir(new): |
|
522 | if not os.path.isdir(new): | |
523 | os.makedirs(new, mode = 0777) |
|
523 | os.makedirs(new, mode = 0777) | |
524 |
|
524 | |||
525 | def set_autoindent(self,value=None): |
|
525 | def set_autoindent(self,value=None): | |
526 | """Set the autoindent flag, checking for readline support. |
|
526 | """Set the autoindent flag, checking for readline support. | |
527 |
|
527 | |||
528 | If called with no arguments, it acts as a toggle.""" |
|
528 | If called with no arguments, it acts as a toggle.""" | |
529 |
|
529 | |||
530 | if value != 0 and not self.has_readline: |
|
530 | if value != 0 and not self.has_readline: | |
531 | if os.name == 'posix': |
|
531 | if os.name == 'posix': | |
532 | warn("The auto-indent feature requires the readline library") |
|
532 | warn("The auto-indent feature requires the readline library") | |
533 | self.autoindent = 0 |
|
533 | self.autoindent = 0 | |
534 | return |
|
534 | return | |
535 | if value is None: |
|
535 | if value is None: | |
536 | self.autoindent = not self.autoindent |
|
536 | self.autoindent = not self.autoindent | |
537 | else: |
|
537 | else: | |
538 | self.autoindent = value |
|
538 | self.autoindent = value | |
539 |
|
539 | |||
540 | #------------------------------------------------------------------------- |
|
540 | #------------------------------------------------------------------------- | |
541 | # init_* methods called by __init__ |
|
541 | # init_* methods called by __init__ | |
542 | #------------------------------------------------------------------------- |
|
542 | #------------------------------------------------------------------------- | |
543 |
|
543 | |||
544 | def init_ipython_dir(self, ipython_dir): |
|
544 | def init_ipython_dir(self, ipython_dir): | |
545 | if ipython_dir is not None: |
|
545 | if ipython_dir is not None: | |
546 | self.ipython_dir = ipython_dir |
|
546 | self.ipython_dir = ipython_dir | |
547 | return |
|
547 | return | |
548 |
|
548 | |||
549 | self.ipython_dir = get_ipython_dir() |
|
549 | self.ipython_dir = get_ipython_dir() | |
550 |
|
550 | |||
551 | def init_profile_dir(self, profile_dir): |
|
551 | def init_profile_dir(self, profile_dir): | |
552 | if profile_dir is not None: |
|
552 | if profile_dir is not None: | |
553 | self.profile_dir = profile_dir |
|
553 | self.profile_dir = profile_dir | |
554 | return |
|
554 | return | |
555 | self.profile_dir =\ |
|
555 | self.profile_dir =\ | |
556 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
556 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
557 |
|
557 | |||
558 | def init_instance_attrs(self): |
|
558 | def init_instance_attrs(self): | |
559 | self.more = False |
|
559 | self.more = False | |
560 |
|
560 | |||
561 | # command compiler |
|
561 | # command compiler | |
562 | self.compile = CachingCompiler() |
|
562 | self.compile = CachingCompiler() | |
563 |
|
563 | |||
564 | # Make an empty namespace, which extension writers can rely on both |
|
564 | # Make an empty namespace, which extension writers can rely on both | |
565 | # existing and NEVER being used by ipython itself. This gives them a |
|
565 | # existing and NEVER being used by ipython itself. This gives them a | |
566 | # convenient location for storing additional information and state |
|
566 | # convenient location for storing additional information and state | |
567 | # their extensions may require, without fear of collisions with other |
|
567 | # their extensions may require, without fear of collisions with other | |
568 | # ipython names that may develop later. |
|
568 | # ipython names that may develop later. | |
569 | self.meta = Struct() |
|
569 | self.meta = Struct() | |
570 |
|
570 | |||
571 | # Temporary files used for various purposes. Deleted at exit. |
|
571 | # Temporary files used for various purposes. Deleted at exit. | |
572 | self.tempfiles = [] |
|
572 | self.tempfiles = [] | |
573 |
|
573 | |||
574 | # Keep track of readline usage (later set by init_readline) |
|
574 | # Keep track of readline usage (later set by init_readline) | |
575 | self.has_readline = False |
|
575 | self.has_readline = False | |
576 |
|
576 | |||
577 | # keep track of where we started running (mainly for crash post-mortem) |
|
577 | # keep track of where we started running (mainly for crash post-mortem) | |
578 | # This is not being used anywhere currently. |
|
578 | # This is not being used anywhere currently. | |
579 | self.starting_dir = os.getcwdu() |
|
579 | self.starting_dir = os.getcwdu() | |
580 |
|
580 | |||
581 | # Indentation management |
|
581 | # Indentation management | |
582 | self.indent_current_nsp = 0 |
|
582 | self.indent_current_nsp = 0 | |
583 |
|
583 | |||
584 | # Dict to track post-execution functions that have been registered |
|
584 | # Dict to track post-execution functions that have been registered | |
585 | self._post_execute = {} |
|
585 | self._post_execute = {} | |
586 |
|
586 | |||
587 | def init_environment(self): |
|
587 | def init_environment(self): | |
588 | """Any changes we need to make to the user's environment.""" |
|
588 | """Any changes we need to make to the user's environment.""" | |
589 | pass |
|
589 | pass | |
590 |
|
590 | |||
591 | def init_encoding(self): |
|
591 | def init_encoding(self): | |
592 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
592 | # Get system encoding at startup time. Certain terminals (like Emacs | |
593 | # under Win32 have it set to None, and we need to have a known valid |
|
593 | # under Win32 have it set to None, and we need to have a known valid | |
594 | # encoding to use in the raw_input() method |
|
594 | # encoding to use in the raw_input() method | |
595 | try: |
|
595 | try: | |
596 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
596 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
597 | except AttributeError: |
|
597 | except AttributeError: | |
598 | self.stdin_encoding = 'ascii' |
|
598 | self.stdin_encoding = 'ascii' | |
599 |
|
599 | |||
600 | def init_syntax_highlighting(self): |
|
600 | def init_syntax_highlighting(self): | |
601 | # Python source parser/formatter for syntax highlighting |
|
601 | # Python source parser/formatter for syntax highlighting | |
602 | pyformat = PyColorize.Parser().format |
|
602 | pyformat = PyColorize.Parser().format | |
603 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
603 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
604 |
|
604 | |||
605 | def init_pushd_popd_magic(self): |
|
605 | def init_pushd_popd_magic(self): | |
606 | # for pushd/popd management |
|
606 | # for pushd/popd management | |
607 | self.home_dir = get_home_dir() |
|
607 | self.home_dir = get_home_dir() | |
608 |
|
608 | |||
609 | self.dir_stack = [] |
|
609 | self.dir_stack = [] | |
610 |
|
610 | |||
611 | def init_logger(self): |
|
611 | def init_logger(self): | |
612 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
612 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
613 | logmode='rotate') |
|
613 | logmode='rotate') | |
614 |
|
614 | |||
615 | def init_logstart(self): |
|
615 | def init_logstart(self): | |
616 | """Initialize logging in case it was requested at the command line. |
|
616 | """Initialize logging in case it was requested at the command line. | |
617 | """ |
|
617 | """ | |
618 | if self.logappend: |
|
618 | if self.logappend: | |
619 | self.magic('logstart %s append' % self.logappend) |
|
619 | self.magic('logstart %s append' % self.logappend) | |
620 | elif self.logfile: |
|
620 | elif self.logfile: | |
621 | self.magic('logstart %' % self.logfile) |
|
621 | self.magic('logstart %' % self.logfile) | |
622 | elif self.logstart: |
|
622 | elif self.logstart: | |
623 | self.magic('logstart') |
|
623 | self.magic('logstart') | |
624 |
|
624 | |||
625 | def init_builtins(self): |
|
625 | def init_builtins(self): | |
626 | # A single, static flag that we set to True. Its presence indicates |
|
626 | # A single, static flag that we set to True. Its presence indicates | |
627 | # that an IPython shell has been created, and we make no attempts at |
|
627 | # that an IPython shell has been created, and we make no attempts at | |
628 | # removing on exit or representing the existence of more than one |
|
628 | # removing on exit or representing the existence of more than one | |
629 | # IPython at a time. |
|
629 | # IPython at a time. | |
630 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
630 | builtin_mod.__dict__['__IPYTHON__'] = True | |
631 |
|
631 | |||
632 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
632 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to | |
633 | # manage on enter/exit, but with all our shells it's virtually |
|
633 | # manage on enter/exit, but with all our shells it's virtually | |
634 | # impossible to get all the cases right. We're leaving the name in for |
|
634 | # impossible to get all the cases right. We're leaving the name in for | |
635 | # those who adapted their codes to check for this flag, but will |
|
635 | # those who adapted their codes to check for this flag, but will | |
636 | # eventually remove it after a few more releases. |
|
636 | # eventually remove it after a few more releases. | |
637 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
637 | builtin_mod.__dict__['__IPYTHON__active'] = \ | |
638 | 'Deprecated, check for __IPYTHON__' |
|
638 | 'Deprecated, check for __IPYTHON__' | |
639 |
|
639 | |||
640 | self.builtin_trap = BuiltinTrap(shell=self) |
|
640 | self.builtin_trap = BuiltinTrap(shell=self) | |
641 |
|
641 | |||
642 | def init_inspector(self): |
|
642 | def init_inspector(self): | |
643 | # Object inspector |
|
643 | # Object inspector | |
644 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
644 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
645 | PyColorize.ANSICodeColors, |
|
645 | PyColorize.ANSICodeColors, | |
646 | 'NoColor', |
|
646 | 'NoColor', | |
647 | self.object_info_string_level) |
|
647 | self.object_info_string_level) | |
648 |
|
648 | |||
649 | def init_io(self): |
|
649 | def init_io(self): | |
650 | # This will just use sys.stdout and sys.stderr. If you want to |
|
650 | # This will just use sys.stdout and sys.stderr. If you want to | |
651 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
651 | # override sys.stdout and sys.stderr themselves, you need to do that | |
652 | # *before* instantiating this class, because io holds onto |
|
652 | # *before* instantiating this class, because io holds onto | |
653 | # references to the underlying streams. |
|
653 | # references to the underlying streams. | |
654 | if sys.platform == 'win32' and self.has_readline: |
|
654 | if sys.platform == 'win32' and self.has_readline: | |
655 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
655 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
656 | else: |
|
656 | else: | |
657 | io.stdout = io.IOStream(sys.stdout) |
|
657 | io.stdout = io.IOStream(sys.stdout) | |
658 | io.stderr = io.IOStream(sys.stderr) |
|
658 | io.stderr = io.IOStream(sys.stderr) | |
659 |
|
659 | |||
660 | def init_prompts(self): |
|
660 | def init_prompts(self): | |
661 | self.prompt_manager = PromptManager(shell=self, config=self.config) |
|
661 | self.prompt_manager = PromptManager(shell=self, config=self.config) | |
662 | self.configurables.append(self.prompt_manager) |
|
662 | self.configurables.append(self.prompt_manager) | |
663 | # Set system prompts, so that scripts can decide if they are running |
|
663 | # Set system prompts, so that scripts can decide if they are running | |
664 | # interactively. |
|
664 | # interactively. | |
665 | sys.ps1 = 'In : ' |
|
665 | sys.ps1 = 'In : ' | |
666 | sys.ps2 = '...: ' |
|
666 | sys.ps2 = '...: ' | |
667 | sys.ps3 = 'Out: ' |
|
667 | sys.ps3 = 'Out: ' | |
668 |
|
668 | |||
669 | def init_display_formatter(self): |
|
669 | def init_display_formatter(self): | |
670 | self.display_formatter = DisplayFormatter(config=self.config) |
|
670 | self.display_formatter = DisplayFormatter(config=self.config) | |
671 | self.configurables.append(self.display_formatter) |
|
671 | self.configurables.append(self.display_formatter) | |
672 |
|
672 | |||
673 | def init_display_pub(self): |
|
673 | def init_display_pub(self): | |
674 | self.display_pub = self.display_pub_class(config=self.config) |
|
674 | self.display_pub = self.display_pub_class(config=self.config) | |
675 | self.configurables.append(self.display_pub) |
|
675 | self.configurables.append(self.display_pub) | |
676 |
|
676 | |||
677 | def init_displayhook(self): |
|
677 | def init_displayhook(self): | |
678 | # Initialize displayhook, set in/out prompts and printing system |
|
678 | # Initialize displayhook, set in/out prompts and printing system | |
679 | self.displayhook = self.displayhook_class( |
|
679 | self.displayhook = self.displayhook_class( | |
680 | config=self.config, |
|
680 | config=self.config, | |
681 | shell=self, |
|
681 | shell=self, | |
682 | cache_size=self.cache_size, |
|
682 | cache_size=self.cache_size, | |
683 | ) |
|
683 | ) | |
684 | self.configurables.append(self.displayhook) |
|
684 | self.configurables.append(self.displayhook) | |
685 | # This is a context manager that installs/revmoes the displayhook at |
|
685 | # This is a context manager that installs/revmoes the displayhook at | |
686 | # the appropriate time. |
|
686 | # the appropriate time. | |
687 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
687 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
688 |
|
688 | |||
689 | def init_reload_doctest(self): |
|
689 | def init_reload_doctest(self): | |
690 | # Do a proper resetting of doctest, including the necessary displayhook |
|
690 | # Do a proper resetting of doctest, including the necessary displayhook | |
691 | # monkeypatching |
|
691 | # monkeypatching | |
692 | try: |
|
692 | try: | |
693 | doctest_reload() |
|
693 | doctest_reload() | |
694 | except ImportError: |
|
694 | except ImportError: | |
695 | warn("doctest module does not exist.") |
|
695 | warn("doctest module does not exist.") | |
696 |
|
696 | |||
697 | def init_virtualenv(self): |
|
697 | def init_virtualenv(self): | |
698 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
698 | """Add a virtualenv to sys.path so the user can import modules from it. | |
699 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
699 | This isn't perfect: it doesn't use the Python interpreter with which the | |
700 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
700 | virtualenv was built, and it ignores the --no-site-packages option. A | |
701 | warning will appear suggesting the user installs IPython in the |
|
701 | warning will appear suggesting the user installs IPython in the | |
702 | virtualenv, but for many cases, it probably works well enough. |
|
702 | virtualenv, but for many cases, it probably works well enough. | |
703 |
|
703 | |||
704 | Adapted from code snippets online. |
|
704 | Adapted from code snippets online. | |
705 |
|
705 | |||
706 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
706 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
707 | """ |
|
707 | """ | |
708 | if 'VIRTUAL_ENV' not in os.environ: |
|
708 | if 'VIRTUAL_ENV' not in os.environ: | |
709 | # Not in a virtualenv |
|
709 | # Not in a virtualenv | |
710 | return |
|
710 | return | |
711 |
|
711 | |||
712 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): |
|
712 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): | |
713 | # Running properly in the virtualenv, don't need to do anything |
|
713 | # Running properly in the virtualenv, don't need to do anything | |
714 | return |
|
714 | return | |
715 |
|
715 | |||
716 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
716 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
717 | "install IPython inside the virtualenv.\n") |
|
717 | "install IPython inside the virtualenv.\n") | |
718 | if sys.platform == "win32": |
|
718 | if sys.platform == "win32": | |
719 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
719 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
720 | else: |
|
720 | else: | |
721 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
721 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
722 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
722 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
723 |
|
723 | |||
724 | import site |
|
724 | import site | |
725 | sys.path.insert(0, virtual_env) |
|
725 | sys.path.insert(0, virtual_env) | |
726 | site.addsitedir(virtual_env) |
|
726 | site.addsitedir(virtual_env) | |
727 |
|
727 | |||
728 | #------------------------------------------------------------------------- |
|
728 | #------------------------------------------------------------------------- | |
729 | # Things related to injections into the sys module |
|
729 | # Things related to injections into the sys module | |
730 | #------------------------------------------------------------------------- |
|
730 | #------------------------------------------------------------------------- | |
731 |
|
731 | |||
732 | def save_sys_module_state(self): |
|
732 | def save_sys_module_state(self): | |
733 | """Save the state of hooks in the sys module. |
|
733 | """Save the state of hooks in the sys module. | |
734 |
|
734 | |||
735 | This has to be called after self.user_module is created. |
|
735 | This has to be called after self.user_module is created. | |
736 | """ |
|
736 | """ | |
737 | self._orig_sys_module_state = {} |
|
737 | self._orig_sys_module_state = {} | |
738 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
738 | self._orig_sys_module_state['stdin'] = sys.stdin | |
739 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
739 | self._orig_sys_module_state['stdout'] = sys.stdout | |
740 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
740 | self._orig_sys_module_state['stderr'] = sys.stderr | |
741 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
741 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
742 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
742 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
743 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
743 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
744 |
|
744 | |||
745 | def restore_sys_module_state(self): |
|
745 | def restore_sys_module_state(self): | |
746 | """Restore the state of the sys module.""" |
|
746 | """Restore the state of the sys module.""" | |
747 | try: |
|
747 | try: | |
748 | for k, v in self._orig_sys_module_state.iteritems(): |
|
748 | for k, v in self._orig_sys_module_state.iteritems(): | |
749 | setattr(sys, k, v) |
|
749 | setattr(sys, k, v) | |
750 | except AttributeError: |
|
750 | except AttributeError: | |
751 | pass |
|
751 | pass | |
752 | # Reset what what done in self.init_sys_modules |
|
752 | # Reset what what done in self.init_sys_modules | |
753 | if self._orig_sys_modules_main_mod is not None: |
|
753 | if self._orig_sys_modules_main_mod is not None: | |
754 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
754 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
755 |
|
755 | |||
756 | #------------------------------------------------------------------------- |
|
756 | #------------------------------------------------------------------------- | |
757 | # Things related to hooks |
|
757 | # Things related to hooks | |
758 | #------------------------------------------------------------------------- |
|
758 | #------------------------------------------------------------------------- | |
759 |
|
759 | |||
760 | def init_hooks(self): |
|
760 | def init_hooks(self): | |
761 | # hooks holds pointers used for user-side customizations |
|
761 | # hooks holds pointers used for user-side customizations | |
762 | self.hooks = Struct() |
|
762 | self.hooks = Struct() | |
763 |
|
763 | |||
764 | self.strdispatchers = {} |
|
764 | self.strdispatchers = {} | |
765 |
|
765 | |||
766 | # Set all default hooks, defined in the IPython.hooks module. |
|
766 | # Set all default hooks, defined in the IPython.hooks module. | |
767 | hooks = IPython.core.hooks |
|
767 | hooks = IPython.core.hooks | |
768 | for hook_name in hooks.__all__: |
|
768 | for hook_name in hooks.__all__: | |
769 | # default hooks have priority 100, i.e. low; user hooks should have |
|
769 | # default hooks have priority 100, i.e. low; user hooks should have | |
770 | # 0-100 priority |
|
770 | # 0-100 priority | |
771 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
771 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
772 |
|
772 | |||
773 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
773 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
774 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
774 | """set_hook(name,hook) -> sets an internal IPython hook. | |
775 |
|
775 | |||
776 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
776 | IPython exposes some of its internal API as user-modifiable hooks. By | |
777 | adding your function to one of these hooks, you can modify IPython's |
|
777 | adding your function to one of these hooks, you can modify IPython's | |
778 | behavior to call at runtime your own routines.""" |
|
778 | behavior to call at runtime your own routines.""" | |
779 |
|
779 | |||
780 | # At some point in the future, this should validate the hook before it |
|
780 | # At some point in the future, this should validate the hook before it | |
781 | # accepts it. Probably at least check that the hook takes the number |
|
781 | # accepts it. Probably at least check that the hook takes the number | |
782 | # of args it's supposed to. |
|
782 | # of args it's supposed to. | |
783 |
|
783 | |||
784 | f = types.MethodType(hook,self) |
|
784 | f = types.MethodType(hook,self) | |
785 |
|
785 | |||
786 | # check if the hook is for strdispatcher first |
|
786 | # check if the hook is for strdispatcher first | |
787 | if str_key is not None: |
|
787 | if str_key is not None: | |
788 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
788 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
789 | sdp.add_s(str_key, f, priority ) |
|
789 | sdp.add_s(str_key, f, priority ) | |
790 | self.strdispatchers[name] = sdp |
|
790 | self.strdispatchers[name] = sdp | |
791 | return |
|
791 | return | |
792 | if re_key is not None: |
|
792 | if re_key is not None: | |
793 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
793 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
794 | sdp.add_re(re.compile(re_key), f, priority ) |
|
794 | sdp.add_re(re.compile(re_key), f, priority ) | |
795 | self.strdispatchers[name] = sdp |
|
795 | self.strdispatchers[name] = sdp | |
796 | return |
|
796 | return | |
797 |
|
797 | |||
798 | dp = getattr(self.hooks, name, None) |
|
798 | dp = getattr(self.hooks, name, None) | |
799 | if name not in IPython.core.hooks.__all__: |
|
799 | if name not in IPython.core.hooks.__all__: | |
800 | print("Warning! Hook '%s' is not one of %s" % \ |
|
800 | print("Warning! Hook '%s' is not one of %s" % \ | |
801 | (name, IPython.core.hooks.__all__ )) |
|
801 | (name, IPython.core.hooks.__all__ )) | |
802 | if not dp: |
|
802 | if not dp: | |
803 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
803 | dp = IPython.core.hooks.CommandChainDispatcher() | |
804 |
|
804 | |||
805 | try: |
|
805 | try: | |
806 | dp.add(f,priority) |
|
806 | dp.add(f,priority) | |
807 | except AttributeError: |
|
807 | except AttributeError: | |
808 | # it was not commandchain, plain old func - replace |
|
808 | # it was not commandchain, plain old func - replace | |
809 | dp = f |
|
809 | dp = f | |
810 |
|
810 | |||
811 | setattr(self.hooks,name, dp) |
|
811 | setattr(self.hooks,name, dp) | |
812 |
|
812 | |||
813 | def register_post_execute(self, func): |
|
813 | def register_post_execute(self, func): | |
814 | """Register a function for calling after code execution. |
|
814 | """Register a function for calling after code execution. | |
815 | """ |
|
815 | """ | |
816 | if not callable(func): |
|
816 | if not callable(func): | |
817 | raise ValueError('argument %s must be callable' % func) |
|
817 | raise ValueError('argument %s must be callable' % func) | |
818 | self._post_execute[func] = True |
|
818 | self._post_execute[func] = True | |
819 |
|
819 | |||
820 | #------------------------------------------------------------------------- |
|
820 | #------------------------------------------------------------------------- | |
821 | # Things related to the "main" module |
|
821 | # Things related to the "main" module | |
822 | #------------------------------------------------------------------------- |
|
822 | #------------------------------------------------------------------------- | |
823 |
|
823 | |||
824 | def new_main_mod(self,ns=None): |
|
824 | def new_main_mod(self,ns=None): | |
825 | """Return a new 'main' module object for user code execution. |
|
825 | """Return a new 'main' module object for user code execution. | |
826 | """ |
|
826 | """ | |
827 | main_mod = self._user_main_module |
|
827 | main_mod = self._user_main_module | |
828 | init_fakemod_dict(main_mod,ns) |
|
828 | init_fakemod_dict(main_mod,ns) | |
829 | return main_mod |
|
829 | return main_mod | |
830 |
|
830 | |||
831 | def cache_main_mod(self,ns,fname): |
|
831 | def cache_main_mod(self,ns,fname): | |
832 | """Cache a main module's namespace. |
|
832 | """Cache a main module's namespace. | |
833 |
|
833 | |||
834 | When scripts are executed via %run, we must keep a reference to the |
|
834 | When scripts are executed via %run, we must keep a reference to the | |
835 | namespace of their __main__ module (a FakeModule instance) around so |
|
835 | namespace of their __main__ module (a FakeModule instance) around so | |
836 | that Python doesn't clear it, rendering objects defined therein |
|
836 | that Python doesn't clear it, rendering objects defined therein | |
837 | useless. |
|
837 | useless. | |
838 |
|
838 | |||
839 | This method keeps said reference in a private dict, keyed by the |
|
839 | This method keeps said reference in a private dict, keyed by the | |
840 | absolute path of the module object (which corresponds to the script |
|
840 | absolute path of the module object (which corresponds to the script | |
841 | path). This way, for multiple executions of the same script we only |
|
841 | path). This way, for multiple executions of the same script we only | |
842 | keep one copy of the namespace (the last one), thus preventing memory |
|
842 | keep one copy of the namespace (the last one), thus preventing memory | |
843 | leaks from old references while allowing the objects from the last |
|
843 | leaks from old references while allowing the objects from the last | |
844 | execution to be accessible. |
|
844 | execution to be accessible. | |
845 |
|
845 | |||
846 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
846 | Note: we can not allow the actual FakeModule instances to be deleted, | |
847 | because of how Python tears down modules (it hard-sets all their |
|
847 | because of how Python tears down modules (it hard-sets all their | |
848 | references to None without regard for reference counts). This method |
|
848 | references to None without regard for reference counts). This method | |
849 | must therefore make a *copy* of the given namespace, to allow the |
|
849 | must therefore make a *copy* of the given namespace, to allow the | |
850 | original module's __dict__ to be cleared and reused. |
|
850 | original module's __dict__ to be cleared and reused. | |
851 |
|
851 | |||
852 |
|
852 | |||
853 | Parameters |
|
853 | Parameters | |
854 | ---------- |
|
854 | ---------- | |
855 | ns : a namespace (a dict, typically) |
|
855 | ns : a namespace (a dict, typically) | |
856 |
|
856 | |||
857 | fname : str |
|
857 | fname : str | |
858 | Filename associated with the namespace. |
|
858 | Filename associated with the namespace. | |
859 |
|
859 | |||
860 | Examples |
|
860 | Examples | |
861 | -------- |
|
861 | -------- | |
862 |
|
862 | |||
863 | In [10]: import IPython |
|
863 | In [10]: import IPython | |
864 |
|
864 | |||
865 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
865 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
866 |
|
866 | |||
867 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
867 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
868 | Out[12]: True |
|
868 | Out[12]: True | |
869 | """ |
|
869 | """ | |
870 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
870 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
871 |
|
871 | |||
872 | def clear_main_mod_cache(self): |
|
872 | def clear_main_mod_cache(self): | |
873 | """Clear the cache of main modules. |
|
873 | """Clear the cache of main modules. | |
874 |
|
874 | |||
875 | Mainly for use by utilities like %reset. |
|
875 | Mainly for use by utilities like %reset. | |
876 |
|
876 | |||
877 | Examples |
|
877 | Examples | |
878 | -------- |
|
878 | -------- | |
879 |
|
879 | |||
880 | In [15]: import IPython |
|
880 | In [15]: import IPython | |
881 |
|
881 | |||
882 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
882 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
883 |
|
883 | |||
884 | In [17]: len(_ip._main_ns_cache) > 0 |
|
884 | In [17]: len(_ip._main_ns_cache) > 0 | |
885 | Out[17]: True |
|
885 | Out[17]: True | |
886 |
|
886 | |||
887 | In [18]: _ip.clear_main_mod_cache() |
|
887 | In [18]: _ip.clear_main_mod_cache() | |
888 |
|
888 | |||
889 | In [19]: len(_ip._main_ns_cache) == 0 |
|
889 | In [19]: len(_ip._main_ns_cache) == 0 | |
890 | Out[19]: True |
|
890 | Out[19]: True | |
891 | """ |
|
891 | """ | |
892 | self._main_ns_cache.clear() |
|
892 | self._main_ns_cache.clear() | |
893 |
|
893 | |||
894 | #------------------------------------------------------------------------- |
|
894 | #------------------------------------------------------------------------- | |
895 | # Things related to debugging |
|
895 | # Things related to debugging | |
896 | #------------------------------------------------------------------------- |
|
896 | #------------------------------------------------------------------------- | |
897 |
|
897 | |||
898 | def init_pdb(self): |
|
898 | def init_pdb(self): | |
899 | # Set calling of pdb on exceptions |
|
899 | # Set calling of pdb on exceptions | |
900 | # self.call_pdb is a property |
|
900 | # self.call_pdb is a property | |
901 | self.call_pdb = self.pdb |
|
901 | self.call_pdb = self.pdb | |
902 |
|
902 | |||
903 | def _get_call_pdb(self): |
|
903 | def _get_call_pdb(self): | |
904 | return self._call_pdb |
|
904 | return self._call_pdb | |
905 |
|
905 | |||
906 | def _set_call_pdb(self,val): |
|
906 | def _set_call_pdb(self,val): | |
907 |
|
907 | |||
908 | if val not in (0,1,False,True): |
|
908 | if val not in (0,1,False,True): | |
909 |
raise ValueError |
|
909 | raise ValueError('new call_pdb value must be boolean') | |
910 |
|
910 | |||
911 | # store value in instance |
|
911 | # store value in instance | |
912 | self._call_pdb = val |
|
912 | self._call_pdb = val | |
913 |
|
913 | |||
914 | # notify the actual exception handlers |
|
914 | # notify the actual exception handlers | |
915 | self.InteractiveTB.call_pdb = val |
|
915 | self.InteractiveTB.call_pdb = val | |
916 |
|
916 | |||
917 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
917 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
918 | 'Control auto-activation of pdb at exceptions') |
|
918 | 'Control auto-activation of pdb at exceptions') | |
919 |
|
919 | |||
920 | def debugger(self,force=False): |
|
920 | def debugger(self,force=False): | |
921 | """Call the pydb/pdb debugger. |
|
921 | """Call the pydb/pdb debugger. | |
922 |
|
922 | |||
923 | Keywords: |
|
923 | Keywords: | |
924 |
|
924 | |||
925 | - force(False): by default, this routine checks the instance call_pdb |
|
925 | - force(False): by default, this routine checks the instance call_pdb | |
926 | flag and does not actually invoke the debugger if the flag is false. |
|
926 | flag and does not actually invoke the debugger if the flag is false. | |
927 | The 'force' option forces the debugger to activate even if the flag |
|
927 | The 'force' option forces the debugger to activate even if the flag | |
928 | is false. |
|
928 | is false. | |
929 | """ |
|
929 | """ | |
930 |
|
930 | |||
931 | if not (force or self.call_pdb): |
|
931 | if not (force or self.call_pdb): | |
932 | return |
|
932 | return | |
933 |
|
933 | |||
934 | if not hasattr(sys,'last_traceback'): |
|
934 | if not hasattr(sys,'last_traceback'): | |
935 | error('No traceback has been produced, nothing to debug.') |
|
935 | error('No traceback has been produced, nothing to debug.') | |
936 | return |
|
936 | return | |
937 |
|
937 | |||
938 | # use pydb if available |
|
938 | # use pydb if available | |
939 | if debugger.has_pydb: |
|
939 | if debugger.has_pydb: | |
940 | from pydb import pm |
|
940 | from pydb import pm | |
941 | else: |
|
941 | else: | |
942 | # fallback to our internal debugger |
|
942 | # fallback to our internal debugger | |
943 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
943 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
944 |
|
944 | |||
945 | with self.readline_no_record: |
|
945 | with self.readline_no_record: | |
946 | pm() |
|
946 | pm() | |
947 |
|
947 | |||
948 | #------------------------------------------------------------------------- |
|
948 | #------------------------------------------------------------------------- | |
949 | # Things related to IPython's various namespaces |
|
949 | # Things related to IPython's various namespaces | |
950 | #------------------------------------------------------------------------- |
|
950 | #------------------------------------------------------------------------- | |
951 | default_user_namespaces = True |
|
951 | default_user_namespaces = True | |
952 |
|
952 | |||
953 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
953 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
954 | # Create the namespace where the user will operate. user_ns is |
|
954 | # Create the namespace where the user will operate. user_ns is | |
955 | # normally the only one used, and it is passed to the exec calls as |
|
955 | # normally the only one used, and it is passed to the exec calls as | |
956 | # the locals argument. But we do carry a user_global_ns namespace |
|
956 | # the locals argument. But we do carry a user_global_ns namespace | |
957 | # given as the exec 'globals' argument, This is useful in embedding |
|
957 | # given as the exec 'globals' argument, This is useful in embedding | |
958 | # situations where the ipython shell opens in a context where the |
|
958 | # situations where the ipython shell opens in a context where the | |
959 | # distinction between locals and globals is meaningful. For |
|
959 | # distinction between locals and globals is meaningful. For | |
960 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
960 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
961 |
|
961 | |||
962 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
962 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
963 | # level as a dict instead of a module. This is a manual fix, but I |
|
963 | # level as a dict instead of a module. This is a manual fix, but I | |
964 | # should really track down where the problem is coming from. Alex |
|
964 | # should really track down where the problem is coming from. Alex | |
965 | # Schmolck reported this problem first. |
|
965 | # Schmolck reported this problem first. | |
966 |
|
966 | |||
967 | # A useful post by Alex Martelli on this topic: |
|
967 | # A useful post by Alex Martelli on this topic: | |
968 | # Re: inconsistent value from __builtins__ |
|
968 | # Re: inconsistent value from __builtins__ | |
969 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
969 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
970 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
970 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
971 | # Gruppen: comp.lang.python |
|
971 | # Gruppen: comp.lang.python | |
972 |
|
972 | |||
973 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
973 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
974 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
974 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
975 | # > <type 'dict'> |
|
975 | # > <type 'dict'> | |
976 | # > >>> print type(__builtins__) |
|
976 | # > >>> print type(__builtins__) | |
977 | # > <type 'module'> |
|
977 | # > <type 'module'> | |
978 | # > Is this difference in return value intentional? |
|
978 | # > Is this difference in return value intentional? | |
979 |
|
979 | |||
980 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
980 | # Well, it's documented that '__builtins__' can be either a dictionary | |
981 | # or a module, and it's been that way for a long time. Whether it's |
|
981 | # or a module, and it's been that way for a long time. Whether it's | |
982 | # intentional (or sensible), I don't know. In any case, the idea is |
|
982 | # intentional (or sensible), I don't know. In any case, the idea is | |
983 | # that if you need to access the built-in namespace directly, you |
|
983 | # that if you need to access the built-in namespace directly, you | |
984 | # should start with "import __builtin__" (note, no 's') which will |
|
984 | # should start with "import __builtin__" (note, no 's') which will | |
985 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
985 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
986 |
|
986 | |||
987 | # These routines return a properly built module and dict as needed by |
|
987 | # These routines return a properly built module and dict as needed by | |
988 | # the rest of the code, and can also be used by extension writers to |
|
988 | # the rest of the code, and can also be used by extension writers to | |
989 | # generate properly initialized namespaces. |
|
989 | # generate properly initialized namespaces. | |
990 | if (user_ns is not None) or (user_module is not None): |
|
990 | if (user_ns is not None) or (user_module is not None): | |
991 | self.default_user_namespaces = False |
|
991 | self.default_user_namespaces = False | |
992 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
992 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
993 |
|
993 | |||
994 | # A record of hidden variables we have added to the user namespace, so |
|
994 | # A record of hidden variables we have added to the user namespace, so | |
995 | # we can list later only variables defined in actual interactive use. |
|
995 | # we can list later only variables defined in actual interactive use. | |
996 | self.user_ns_hidden = set() |
|
996 | self.user_ns_hidden = set() | |
997 |
|
997 | |||
998 | # Now that FakeModule produces a real module, we've run into a nasty |
|
998 | # Now that FakeModule produces a real module, we've run into a nasty | |
999 | # problem: after script execution (via %run), the module where the user |
|
999 | # problem: after script execution (via %run), the module where the user | |
1000 | # code ran is deleted. Now that this object is a true module (needed |
|
1000 | # code ran is deleted. Now that this object is a true module (needed | |
1001 | # so docetst and other tools work correctly), the Python module |
|
1001 | # so docetst and other tools work correctly), the Python module | |
1002 | # teardown mechanism runs over it, and sets to None every variable |
|
1002 | # teardown mechanism runs over it, and sets to None every variable | |
1003 | # present in that module. Top-level references to objects from the |
|
1003 | # present in that module. Top-level references to objects from the | |
1004 | # script survive, because the user_ns is updated with them. However, |
|
1004 | # script survive, because the user_ns is updated with them. However, | |
1005 | # calling functions defined in the script that use other things from |
|
1005 | # calling functions defined in the script that use other things from | |
1006 | # the script will fail, because the function's closure had references |
|
1006 | # the script will fail, because the function's closure had references | |
1007 | # to the original objects, which are now all None. So we must protect |
|
1007 | # to the original objects, which are now all None. So we must protect | |
1008 | # these modules from deletion by keeping a cache. |
|
1008 | # these modules from deletion by keeping a cache. | |
1009 | # |
|
1009 | # | |
1010 | # To avoid keeping stale modules around (we only need the one from the |
|
1010 | # To avoid keeping stale modules around (we only need the one from the | |
1011 | # last run), we use a dict keyed with the full path to the script, so |
|
1011 | # last run), we use a dict keyed with the full path to the script, so | |
1012 | # only the last version of the module is held in the cache. Note, |
|
1012 | # only the last version of the module is held in the cache. Note, | |
1013 | # however, that we must cache the module *namespace contents* (their |
|
1013 | # however, that we must cache the module *namespace contents* (their | |
1014 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1014 | # __dict__). Because if we try to cache the actual modules, old ones | |
1015 | # (uncached) could be destroyed while still holding references (such as |
|
1015 | # (uncached) could be destroyed while still holding references (such as | |
1016 | # those held by GUI objects that tend to be long-lived)> |
|
1016 | # those held by GUI objects that tend to be long-lived)> | |
1017 | # |
|
1017 | # | |
1018 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1018 | # The %reset command will flush this cache. See the cache_main_mod() | |
1019 | # and clear_main_mod_cache() methods for details on use. |
|
1019 | # and clear_main_mod_cache() methods for details on use. | |
1020 |
|
1020 | |||
1021 | # This is the cache used for 'main' namespaces |
|
1021 | # This is the cache used for 'main' namespaces | |
1022 | self._main_ns_cache = {} |
|
1022 | self._main_ns_cache = {} | |
1023 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
1023 | # And this is the single instance of FakeModule whose __dict__ we keep | |
1024 | # copying and clearing for reuse on each %run |
|
1024 | # copying and clearing for reuse on each %run | |
1025 | self._user_main_module = FakeModule() |
|
1025 | self._user_main_module = FakeModule() | |
1026 |
|
1026 | |||
1027 | # A table holding all the namespaces IPython deals with, so that |
|
1027 | # A table holding all the namespaces IPython deals with, so that | |
1028 | # introspection facilities can search easily. |
|
1028 | # introspection facilities can search easily. | |
1029 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1029 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1030 | 'user_local':self.user_ns, |
|
1030 | 'user_local':self.user_ns, | |
1031 | 'builtin':builtin_mod.__dict__ |
|
1031 | 'builtin':builtin_mod.__dict__ | |
1032 | } |
|
1032 | } | |
1033 |
|
1033 | |||
1034 | @property |
|
1034 | @property | |
1035 | def user_global_ns(self): |
|
1035 | def user_global_ns(self): | |
1036 | return self.user_module.__dict__ |
|
1036 | return self.user_module.__dict__ | |
1037 |
|
1037 | |||
1038 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1038 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1039 | """Prepare the module and namespace in which user code will be run. |
|
1039 | """Prepare the module and namespace in which user code will be run. | |
1040 |
|
1040 | |||
1041 | When IPython is started normally, both parameters are None: a new module |
|
1041 | When IPython is started normally, both parameters are None: a new module | |
1042 | is created automatically, and its __dict__ used as the namespace. |
|
1042 | is created automatically, and its __dict__ used as the namespace. | |
1043 |
|
1043 | |||
1044 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1044 | If only user_module is provided, its __dict__ is used as the namespace. | |
1045 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1045 | If only user_ns is provided, a dummy module is created, and user_ns | |
1046 | becomes the global namespace. If both are provided (as they may be |
|
1046 | becomes the global namespace. If both are provided (as they may be | |
1047 | when embedding), user_ns is the local namespace, and user_module |
|
1047 | when embedding), user_ns is the local namespace, and user_module | |
1048 | provides the global namespace. |
|
1048 | provides the global namespace. | |
1049 |
|
1049 | |||
1050 | Parameters |
|
1050 | Parameters | |
1051 | ---------- |
|
1051 | ---------- | |
1052 | user_module : module, optional |
|
1052 | user_module : module, optional | |
1053 | The current user module in which IPython is being run. If None, |
|
1053 | The current user module in which IPython is being run. If None, | |
1054 | a clean module will be created. |
|
1054 | a clean module will be created. | |
1055 | user_ns : dict, optional |
|
1055 | user_ns : dict, optional | |
1056 | A namespace in which to run interactive commands. |
|
1056 | A namespace in which to run interactive commands. | |
1057 |
|
1057 | |||
1058 | Returns |
|
1058 | Returns | |
1059 | ------- |
|
1059 | ------- | |
1060 | A tuple of user_module and user_ns, each properly initialised. |
|
1060 | A tuple of user_module and user_ns, each properly initialised. | |
1061 | """ |
|
1061 | """ | |
1062 | if user_module is None and user_ns is not None: |
|
1062 | if user_module is None and user_ns is not None: | |
1063 | user_ns.setdefault("__name__", "__main__") |
|
1063 | user_ns.setdefault("__name__", "__main__") | |
1064 | class DummyMod(object): |
|
1064 | class DummyMod(object): | |
1065 | "A dummy module used for IPython's interactive namespace." |
|
1065 | "A dummy module used for IPython's interactive namespace." | |
1066 | pass |
|
1066 | pass | |
1067 | user_module = DummyMod() |
|
1067 | user_module = DummyMod() | |
1068 | user_module.__dict__ = user_ns |
|
1068 | user_module.__dict__ = user_ns | |
1069 |
|
1069 | |||
1070 | if user_module is None: |
|
1070 | if user_module is None: | |
1071 | user_module = types.ModuleType("__main__", |
|
1071 | user_module = types.ModuleType("__main__", | |
1072 | doc="Automatically created module for IPython interactive environment") |
|
1072 | doc="Automatically created module for IPython interactive environment") | |
1073 |
|
1073 | |||
1074 | # We must ensure that __builtin__ (without the final 's') is always |
|
1074 | # We must ensure that __builtin__ (without the final 's') is always | |
1075 | # available and pointing to the __builtin__ *module*. For more details: |
|
1075 | # available and pointing to the __builtin__ *module*. For more details: | |
1076 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1076 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1077 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1077 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1078 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1078 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1079 |
|
1079 | |||
1080 | if user_ns is None: |
|
1080 | if user_ns is None: | |
1081 | user_ns = user_module.__dict__ |
|
1081 | user_ns = user_module.__dict__ | |
1082 |
|
1082 | |||
1083 | return user_module, user_ns |
|
1083 | return user_module, user_ns | |
1084 |
|
1084 | |||
1085 | def init_sys_modules(self): |
|
1085 | def init_sys_modules(self): | |
1086 | # We need to insert into sys.modules something that looks like a |
|
1086 | # We need to insert into sys.modules something that looks like a | |
1087 | # module but which accesses the IPython namespace, for shelve and |
|
1087 | # module but which accesses the IPython namespace, for shelve and | |
1088 | # pickle to work interactively. Normally they rely on getting |
|
1088 | # pickle to work interactively. Normally they rely on getting | |
1089 | # everything out of __main__, but for embedding purposes each IPython |
|
1089 | # everything out of __main__, but for embedding purposes each IPython | |
1090 | # instance has its own private namespace, so we can't go shoving |
|
1090 | # instance has its own private namespace, so we can't go shoving | |
1091 | # everything into __main__. |
|
1091 | # everything into __main__. | |
1092 |
|
1092 | |||
1093 | # note, however, that we should only do this for non-embedded |
|
1093 | # note, however, that we should only do this for non-embedded | |
1094 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1094 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1095 | # namespace. Embedded instances, on the other hand, should not do |
|
1095 | # namespace. Embedded instances, on the other hand, should not do | |
1096 | # this because they need to manage the user local/global namespaces |
|
1096 | # this because they need to manage the user local/global namespaces | |
1097 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1097 | # only, but they live within a 'normal' __main__ (meaning, they | |
1098 | # shouldn't overtake the execution environment of the script they're |
|
1098 | # shouldn't overtake the execution environment of the script they're | |
1099 | # embedded in). |
|
1099 | # embedded in). | |
1100 |
|
1100 | |||
1101 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1101 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1102 | main_name = self.user_module.__name__ |
|
1102 | main_name = self.user_module.__name__ | |
1103 | sys.modules[main_name] = self.user_module |
|
1103 | sys.modules[main_name] = self.user_module | |
1104 |
|
1104 | |||
1105 | def init_user_ns(self): |
|
1105 | def init_user_ns(self): | |
1106 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1106 | """Initialize all user-visible namespaces to their minimum defaults. | |
1107 |
|
1107 | |||
1108 | Certain history lists are also initialized here, as they effectively |
|
1108 | Certain history lists are also initialized here, as they effectively | |
1109 | act as user namespaces. |
|
1109 | act as user namespaces. | |
1110 |
|
1110 | |||
1111 | Notes |
|
1111 | Notes | |
1112 | ----- |
|
1112 | ----- | |
1113 | All data structures here are only filled in, they are NOT reset by this |
|
1113 | All data structures here are only filled in, they are NOT reset by this | |
1114 | method. If they were not empty before, data will simply be added to |
|
1114 | method. If they were not empty before, data will simply be added to | |
1115 | therm. |
|
1115 | therm. | |
1116 | """ |
|
1116 | """ | |
1117 | # This function works in two parts: first we put a few things in |
|
1117 | # This function works in two parts: first we put a few things in | |
1118 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1118 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1119 | # initial variables aren't shown by %who. After the sync, we add the |
|
1119 | # initial variables aren't shown by %who. After the sync, we add the | |
1120 | # rest of what we *do* want the user to see with %who even on a new |
|
1120 | # rest of what we *do* want the user to see with %who even on a new | |
1121 | # session (probably nothing, so theye really only see their own stuff) |
|
1121 | # session (probably nothing, so theye really only see their own stuff) | |
1122 |
|
1122 | |||
1123 | # The user dict must *always* have a __builtin__ reference to the |
|
1123 | # The user dict must *always* have a __builtin__ reference to the | |
1124 | # Python standard __builtin__ namespace, which must be imported. |
|
1124 | # Python standard __builtin__ namespace, which must be imported. | |
1125 | # This is so that certain operations in prompt evaluation can be |
|
1125 | # This is so that certain operations in prompt evaluation can be | |
1126 | # reliably executed with builtins. Note that we can NOT use |
|
1126 | # reliably executed with builtins. Note that we can NOT use | |
1127 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1127 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1128 | # module, and can even mutate at runtime, depending on the context |
|
1128 | # module, and can even mutate at runtime, depending on the context | |
1129 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1129 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1130 | # always a module object, though it must be explicitly imported. |
|
1130 | # always a module object, though it must be explicitly imported. | |
1131 |
|
1131 | |||
1132 | # For more details: |
|
1132 | # For more details: | |
1133 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1133 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1134 | ns = dict() |
|
1134 | ns = dict() | |
1135 |
|
1135 | |||
1136 | # Put 'help' in the user namespace |
|
1136 | # Put 'help' in the user namespace | |
1137 | try: |
|
1137 | try: | |
1138 | from site import _Helper |
|
1138 | from site import _Helper | |
1139 | ns['help'] = _Helper() |
|
1139 | ns['help'] = _Helper() | |
1140 | except ImportError: |
|
1140 | except ImportError: | |
1141 | warn('help() not available - check site.py') |
|
1141 | warn('help() not available - check site.py') | |
1142 |
|
1142 | |||
1143 | # make global variables for user access to the histories |
|
1143 | # make global variables for user access to the histories | |
1144 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1144 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1145 | ns['_oh'] = self.history_manager.output_hist |
|
1145 | ns['_oh'] = self.history_manager.output_hist | |
1146 | ns['_dh'] = self.history_manager.dir_hist |
|
1146 | ns['_dh'] = self.history_manager.dir_hist | |
1147 |
|
1147 | |||
1148 | ns['_sh'] = shadowns |
|
1148 | ns['_sh'] = shadowns | |
1149 |
|
1149 | |||
1150 | # user aliases to input and output histories. These shouldn't show up |
|
1150 | # user aliases to input and output histories. These shouldn't show up | |
1151 | # in %who, as they can have very large reprs. |
|
1151 | # in %who, as they can have very large reprs. | |
1152 | ns['In'] = self.history_manager.input_hist_parsed |
|
1152 | ns['In'] = self.history_manager.input_hist_parsed | |
1153 | ns['Out'] = self.history_manager.output_hist |
|
1153 | ns['Out'] = self.history_manager.output_hist | |
1154 |
|
1154 | |||
1155 | # Store myself as the public api!!! |
|
1155 | # Store myself as the public api!!! | |
1156 | ns['get_ipython'] = self.get_ipython |
|
1156 | ns['get_ipython'] = self.get_ipython | |
1157 |
|
1157 | |||
1158 | ns['exit'] = self.exiter |
|
1158 | ns['exit'] = self.exiter | |
1159 | ns['quit'] = self.exiter |
|
1159 | ns['quit'] = self.exiter | |
1160 |
|
1160 | |||
1161 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1161 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1162 | # by %who |
|
1162 | # by %who | |
1163 | self.user_ns_hidden.update(ns) |
|
1163 | self.user_ns_hidden.update(ns) | |
1164 |
|
1164 | |||
1165 | # Anything put into ns now would show up in %who. Think twice before |
|
1165 | # Anything put into ns now would show up in %who. Think twice before | |
1166 | # putting anything here, as we really want %who to show the user their |
|
1166 | # putting anything here, as we really want %who to show the user their | |
1167 | # stuff, not our variables. |
|
1167 | # stuff, not our variables. | |
1168 |
|
1168 | |||
1169 | # Finally, update the real user's namespace |
|
1169 | # Finally, update the real user's namespace | |
1170 | self.user_ns.update(ns) |
|
1170 | self.user_ns.update(ns) | |
1171 |
|
1171 | |||
1172 | @property |
|
1172 | @property | |
1173 | def all_ns_refs(self): |
|
1173 | def all_ns_refs(self): | |
1174 | """Get a list of references to all the namespace dictionaries in which |
|
1174 | """Get a list of references to all the namespace dictionaries in which | |
1175 | IPython might store a user-created object. |
|
1175 | IPython might store a user-created object. | |
1176 |
|
1176 | |||
1177 | Note that this does not include the displayhook, which also caches |
|
1177 | Note that this does not include the displayhook, which also caches | |
1178 | objects from the output.""" |
|
1178 | objects from the output.""" | |
1179 | return [self.user_ns, self.user_global_ns, |
|
1179 | return [self.user_ns, self.user_global_ns, | |
1180 | self._user_main_module.__dict__] + self._main_ns_cache.values() |
|
1180 | self._user_main_module.__dict__] + self._main_ns_cache.values() | |
1181 |
|
1181 | |||
1182 | def reset(self, new_session=True): |
|
1182 | def reset(self, new_session=True): | |
1183 | """Clear all internal namespaces, and attempt to release references to |
|
1183 | """Clear all internal namespaces, and attempt to release references to | |
1184 | user objects. |
|
1184 | user objects. | |
1185 |
|
1185 | |||
1186 | If new_session is True, a new history session will be opened. |
|
1186 | If new_session is True, a new history session will be opened. | |
1187 | """ |
|
1187 | """ | |
1188 | # Clear histories |
|
1188 | # Clear histories | |
1189 | self.history_manager.reset(new_session) |
|
1189 | self.history_manager.reset(new_session) | |
1190 | # Reset counter used to index all histories |
|
1190 | # Reset counter used to index all histories | |
1191 | if new_session: |
|
1191 | if new_session: | |
1192 | self.execution_count = 1 |
|
1192 | self.execution_count = 1 | |
1193 |
|
1193 | |||
1194 | # Flush cached output items |
|
1194 | # Flush cached output items | |
1195 | if self.displayhook.do_full_cache: |
|
1195 | if self.displayhook.do_full_cache: | |
1196 | self.displayhook.flush() |
|
1196 | self.displayhook.flush() | |
1197 |
|
1197 | |||
1198 | # The main execution namespaces must be cleared very carefully, |
|
1198 | # The main execution namespaces must be cleared very carefully, | |
1199 | # skipping the deletion of the builtin-related keys, because doing so |
|
1199 | # skipping the deletion of the builtin-related keys, because doing so | |
1200 | # would cause errors in many object's __del__ methods. |
|
1200 | # would cause errors in many object's __del__ methods. | |
1201 | if self.user_ns is not self.user_global_ns: |
|
1201 | if self.user_ns is not self.user_global_ns: | |
1202 | self.user_ns.clear() |
|
1202 | self.user_ns.clear() | |
1203 | ns = self.user_global_ns |
|
1203 | ns = self.user_global_ns | |
1204 | drop_keys = set(ns.keys()) |
|
1204 | drop_keys = set(ns.keys()) | |
1205 | drop_keys.discard('__builtin__') |
|
1205 | drop_keys.discard('__builtin__') | |
1206 | drop_keys.discard('__builtins__') |
|
1206 | drop_keys.discard('__builtins__') | |
1207 | drop_keys.discard('__name__') |
|
1207 | drop_keys.discard('__name__') | |
1208 | for k in drop_keys: |
|
1208 | for k in drop_keys: | |
1209 | del ns[k] |
|
1209 | del ns[k] | |
1210 |
|
1210 | |||
1211 | self.user_ns_hidden.clear() |
|
1211 | self.user_ns_hidden.clear() | |
1212 |
|
1212 | |||
1213 | # Restore the user namespaces to minimal usability |
|
1213 | # Restore the user namespaces to minimal usability | |
1214 | self.init_user_ns() |
|
1214 | self.init_user_ns() | |
1215 |
|
1215 | |||
1216 | # Restore the default and user aliases |
|
1216 | # Restore the default and user aliases | |
1217 | self.alias_manager.clear_aliases() |
|
1217 | self.alias_manager.clear_aliases() | |
1218 | self.alias_manager.init_aliases() |
|
1218 | self.alias_manager.init_aliases() | |
1219 |
|
1219 | |||
1220 | # Flush the private list of module references kept for script |
|
1220 | # Flush the private list of module references kept for script | |
1221 | # execution protection |
|
1221 | # execution protection | |
1222 | self.clear_main_mod_cache() |
|
1222 | self.clear_main_mod_cache() | |
1223 |
|
1223 | |||
1224 | # Clear out the namespace from the last %run |
|
1224 | # Clear out the namespace from the last %run | |
1225 | self.new_main_mod() |
|
1225 | self.new_main_mod() | |
1226 |
|
1226 | |||
1227 | def del_var(self, varname, by_name=False): |
|
1227 | def del_var(self, varname, by_name=False): | |
1228 | """Delete a variable from the various namespaces, so that, as |
|
1228 | """Delete a variable from the various namespaces, so that, as | |
1229 | far as possible, we're not keeping any hidden references to it. |
|
1229 | far as possible, we're not keeping any hidden references to it. | |
1230 |
|
1230 | |||
1231 | Parameters |
|
1231 | Parameters | |
1232 | ---------- |
|
1232 | ---------- | |
1233 | varname : str |
|
1233 | varname : str | |
1234 | The name of the variable to delete. |
|
1234 | The name of the variable to delete. | |
1235 | by_name : bool |
|
1235 | by_name : bool | |
1236 | If True, delete variables with the given name in each |
|
1236 | If True, delete variables with the given name in each | |
1237 | namespace. If False (default), find the variable in the user |
|
1237 | namespace. If False (default), find the variable in the user | |
1238 | namespace, and delete references to it. |
|
1238 | namespace, and delete references to it. | |
1239 | """ |
|
1239 | """ | |
1240 | if varname in ('__builtin__', '__builtins__'): |
|
1240 | if varname in ('__builtin__', '__builtins__'): | |
1241 | raise ValueError("Refusing to delete %s" % varname) |
|
1241 | raise ValueError("Refusing to delete %s" % varname) | |
1242 |
|
1242 | |||
1243 | ns_refs = self.all_ns_refs |
|
1243 | ns_refs = self.all_ns_refs | |
1244 |
|
1244 | |||
1245 | if by_name: # Delete by name |
|
1245 | if by_name: # Delete by name | |
1246 | for ns in ns_refs: |
|
1246 | for ns in ns_refs: | |
1247 | try: |
|
1247 | try: | |
1248 | del ns[varname] |
|
1248 | del ns[varname] | |
1249 | except KeyError: |
|
1249 | except KeyError: | |
1250 | pass |
|
1250 | pass | |
1251 | else: # Delete by object |
|
1251 | else: # Delete by object | |
1252 | try: |
|
1252 | try: | |
1253 | obj = self.user_ns[varname] |
|
1253 | obj = self.user_ns[varname] | |
1254 | except KeyError: |
|
1254 | except KeyError: | |
1255 | raise NameError("name '%s' is not defined" % varname) |
|
1255 | raise NameError("name '%s' is not defined" % varname) | |
1256 | # Also check in output history |
|
1256 | # Also check in output history | |
1257 | ns_refs.append(self.history_manager.output_hist) |
|
1257 | ns_refs.append(self.history_manager.output_hist) | |
1258 | for ns in ns_refs: |
|
1258 | for ns in ns_refs: | |
1259 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1259 | to_delete = [n for n, o in ns.iteritems() if o is obj] | |
1260 | for name in to_delete: |
|
1260 | for name in to_delete: | |
1261 | del ns[name] |
|
1261 | del ns[name] | |
1262 |
|
1262 | |||
1263 | # displayhook keeps extra references, but not in a dictionary |
|
1263 | # displayhook keeps extra references, but not in a dictionary | |
1264 | for name in ('_', '__', '___'): |
|
1264 | for name in ('_', '__', '___'): | |
1265 | if getattr(self.displayhook, name) is obj: |
|
1265 | if getattr(self.displayhook, name) is obj: | |
1266 | setattr(self.displayhook, name, None) |
|
1266 | setattr(self.displayhook, name, None) | |
1267 |
|
1267 | |||
1268 | def reset_selective(self, regex=None): |
|
1268 | def reset_selective(self, regex=None): | |
1269 | """Clear selective variables from internal namespaces based on a |
|
1269 | """Clear selective variables from internal namespaces based on a | |
1270 | specified regular expression. |
|
1270 | specified regular expression. | |
1271 |
|
1271 | |||
1272 | Parameters |
|
1272 | Parameters | |
1273 | ---------- |
|
1273 | ---------- | |
1274 | regex : string or compiled pattern, optional |
|
1274 | regex : string or compiled pattern, optional | |
1275 | A regular expression pattern that will be used in searching |
|
1275 | A regular expression pattern that will be used in searching | |
1276 | variable names in the users namespaces. |
|
1276 | variable names in the users namespaces. | |
1277 | """ |
|
1277 | """ | |
1278 | if regex is not None: |
|
1278 | if regex is not None: | |
1279 | try: |
|
1279 | try: | |
1280 | m = re.compile(regex) |
|
1280 | m = re.compile(regex) | |
1281 | except TypeError: |
|
1281 | except TypeError: | |
1282 | raise TypeError('regex must be a string or compiled pattern') |
|
1282 | raise TypeError('regex must be a string or compiled pattern') | |
1283 | # Search for keys in each namespace that match the given regex |
|
1283 | # Search for keys in each namespace that match the given regex | |
1284 | # If a match is found, delete the key/value pair. |
|
1284 | # If a match is found, delete the key/value pair. | |
1285 | for ns in self.all_ns_refs: |
|
1285 | for ns in self.all_ns_refs: | |
1286 | for var in ns: |
|
1286 | for var in ns: | |
1287 | if m.search(var): |
|
1287 | if m.search(var): | |
1288 | del ns[var] |
|
1288 | del ns[var] | |
1289 |
|
1289 | |||
1290 | def push(self, variables, interactive=True): |
|
1290 | def push(self, variables, interactive=True): | |
1291 | """Inject a group of variables into the IPython user namespace. |
|
1291 | """Inject a group of variables into the IPython user namespace. | |
1292 |
|
1292 | |||
1293 | Parameters |
|
1293 | Parameters | |
1294 | ---------- |
|
1294 | ---------- | |
1295 | variables : dict, str or list/tuple of str |
|
1295 | variables : dict, str or list/tuple of str | |
1296 | The variables to inject into the user's namespace. If a dict, a |
|
1296 | The variables to inject into the user's namespace. If a dict, a | |
1297 | simple update is done. If a str, the string is assumed to have |
|
1297 | simple update is done. If a str, the string is assumed to have | |
1298 | variable names separated by spaces. A list/tuple of str can also |
|
1298 | variable names separated by spaces. A list/tuple of str can also | |
1299 | be used to give the variable names. If just the variable names are |
|
1299 | be used to give the variable names. If just the variable names are | |
1300 | give (list/tuple/str) then the variable values looked up in the |
|
1300 | give (list/tuple/str) then the variable values looked up in the | |
1301 | callers frame. |
|
1301 | callers frame. | |
1302 | interactive : bool |
|
1302 | interactive : bool | |
1303 | If True (default), the variables will be listed with the ``who`` |
|
1303 | If True (default), the variables will be listed with the ``who`` | |
1304 | magic. |
|
1304 | magic. | |
1305 | """ |
|
1305 | """ | |
1306 | vdict = None |
|
1306 | vdict = None | |
1307 |
|
1307 | |||
1308 | # We need a dict of name/value pairs to do namespace updates. |
|
1308 | # We need a dict of name/value pairs to do namespace updates. | |
1309 | if isinstance(variables, dict): |
|
1309 | if isinstance(variables, dict): | |
1310 | vdict = variables |
|
1310 | vdict = variables | |
1311 | elif isinstance(variables, (basestring, list, tuple)): |
|
1311 | elif isinstance(variables, (basestring, list, tuple)): | |
1312 | if isinstance(variables, basestring): |
|
1312 | if isinstance(variables, basestring): | |
1313 | vlist = variables.split() |
|
1313 | vlist = variables.split() | |
1314 | else: |
|
1314 | else: | |
1315 | vlist = variables |
|
1315 | vlist = variables | |
1316 | vdict = {} |
|
1316 | vdict = {} | |
1317 | cf = sys._getframe(1) |
|
1317 | cf = sys._getframe(1) | |
1318 | for name in vlist: |
|
1318 | for name in vlist: | |
1319 | try: |
|
1319 | try: | |
1320 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1320 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1321 | except: |
|
1321 | except: | |
1322 | print('Could not get variable %s from %s' % |
|
1322 | print('Could not get variable %s from %s' % | |
1323 | (name,cf.f_code.co_name)) |
|
1323 | (name,cf.f_code.co_name)) | |
1324 | else: |
|
1324 | else: | |
1325 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1325 | raise ValueError('variables must be a dict/str/list/tuple') | |
1326 |
|
1326 | |||
1327 | # Propagate variables to user namespace |
|
1327 | # Propagate variables to user namespace | |
1328 | self.user_ns.update(vdict) |
|
1328 | self.user_ns.update(vdict) | |
1329 |
|
1329 | |||
1330 | # And configure interactive visibility |
|
1330 | # And configure interactive visibility | |
1331 | user_ns_hidden = self.user_ns_hidden |
|
1331 | user_ns_hidden = self.user_ns_hidden | |
1332 | if interactive: |
|
1332 | if interactive: | |
1333 | user_ns_hidden.difference_update(vdict) |
|
1333 | user_ns_hidden.difference_update(vdict) | |
1334 | else: |
|
1334 | else: | |
1335 | user_ns_hidden.update(vdict) |
|
1335 | user_ns_hidden.update(vdict) | |
1336 |
|
1336 | |||
1337 | def drop_by_id(self, variables): |
|
1337 | def drop_by_id(self, variables): | |
1338 | """Remove a dict of variables from the user namespace, if they are the |
|
1338 | """Remove a dict of variables from the user namespace, if they are the | |
1339 | same as the values in the dictionary. |
|
1339 | same as the values in the dictionary. | |
1340 |
|
1340 | |||
1341 | This is intended for use by extensions: variables that they've added can |
|
1341 | This is intended for use by extensions: variables that they've added can | |
1342 | be taken back out if they are unloaded, without removing any that the |
|
1342 | be taken back out if they are unloaded, without removing any that the | |
1343 | user has overwritten. |
|
1343 | user has overwritten. | |
1344 |
|
1344 | |||
1345 | Parameters |
|
1345 | Parameters | |
1346 | ---------- |
|
1346 | ---------- | |
1347 | variables : dict |
|
1347 | variables : dict | |
1348 | A dictionary mapping object names (as strings) to the objects. |
|
1348 | A dictionary mapping object names (as strings) to the objects. | |
1349 | """ |
|
1349 | """ | |
1350 | for name, obj in variables.iteritems(): |
|
1350 | for name, obj in variables.iteritems(): | |
1351 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1351 | if name in self.user_ns and self.user_ns[name] is obj: | |
1352 | del self.user_ns[name] |
|
1352 | del self.user_ns[name] | |
1353 | self.user_ns_hidden.discard(name) |
|
1353 | self.user_ns_hidden.discard(name) | |
1354 |
|
1354 | |||
1355 | #------------------------------------------------------------------------- |
|
1355 | #------------------------------------------------------------------------- | |
1356 | # Things related to object introspection |
|
1356 | # Things related to object introspection | |
1357 | #------------------------------------------------------------------------- |
|
1357 | #------------------------------------------------------------------------- | |
1358 |
|
1358 | |||
1359 | def _ofind(self, oname, namespaces=None): |
|
1359 | def _ofind(self, oname, namespaces=None): | |
1360 | """Find an object in the available namespaces. |
|
1360 | """Find an object in the available namespaces. | |
1361 |
|
1361 | |||
1362 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1362 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1363 |
|
1363 | |||
1364 | Has special code to detect magic functions. |
|
1364 | Has special code to detect magic functions. | |
1365 | """ |
|
1365 | """ | |
1366 | oname = oname.strip() |
|
1366 | oname = oname.strip() | |
1367 | #print '1- oname: <%r>' % oname # dbg |
|
1367 | #print '1- oname: <%r>' % oname # dbg | |
1368 | if not oname.startswith(ESC_MAGIC) and \ |
|
1368 | if not oname.startswith(ESC_MAGIC) and \ | |
1369 | not oname.startswith(ESC_MAGIC2) and \ |
|
1369 | not oname.startswith(ESC_MAGIC2) and \ | |
1370 | not py3compat.isidentifier(oname, dotted=True): |
|
1370 | not py3compat.isidentifier(oname, dotted=True): | |
1371 | return dict(found=False) |
|
1371 | return dict(found=False) | |
1372 |
|
1372 | |||
1373 | alias_ns = None |
|
1373 | alias_ns = None | |
1374 | if namespaces is None: |
|
1374 | if namespaces is None: | |
1375 | # Namespaces to search in: |
|
1375 | # Namespaces to search in: | |
1376 | # Put them in a list. The order is important so that we |
|
1376 | # Put them in a list. The order is important so that we | |
1377 | # find things in the same order that Python finds them. |
|
1377 | # find things in the same order that Python finds them. | |
1378 | namespaces = [ ('Interactive', self.user_ns), |
|
1378 | namespaces = [ ('Interactive', self.user_ns), | |
1379 | ('Interactive (global)', self.user_global_ns), |
|
1379 | ('Interactive (global)', self.user_global_ns), | |
1380 | ('Python builtin', builtin_mod.__dict__), |
|
1380 | ('Python builtin', builtin_mod.__dict__), | |
1381 | ('Alias', self.alias_manager.alias_table), |
|
1381 | ('Alias', self.alias_manager.alias_table), | |
1382 | ] |
|
1382 | ] | |
1383 | alias_ns = self.alias_manager.alias_table |
|
1383 | alias_ns = self.alias_manager.alias_table | |
1384 |
|
1384 | |||
1385 | # initialize results to 'null' |
|
1385 | # initialize results to 'null' | |
1386 | found = False; obj = None; ospace = None; ds = None; |
|
1386 | found = False; obj = None; ospace = None; ds = None; | |
1387 | ismagic = False; isalias = False; parent = None |
|
1387 | ismagic = False; isalias = False; parent = None | |
1388 |
|
1388 | |||
1389 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1389 | # We need to special-case 'print', which as of python2.6 registers as a | |
1390 | # function but should only be treated as one if print_function was |
|
1390 | # function but should only be treated as one if print_function was | |
1391 | # loaded with a future import. In this case, just bail. |
|
1391 | # loaded with a future import. In this case, just bail. | |
1392 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1392 | if (oname == 'print' and not py3compat.PY3 and not \ | |
1393 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1393 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1394 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1394 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1395 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1395 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1396 |
|
1396 | |||
1397 | # Look for the given name by splitting it in parts. If the head is |
|
1397 | # Look for the given name by splitting it in parts. If the head is | |
1398 | # found, then we look for all the remaining parts as members, and only |
|
1398 | # found, then we look for all the remaining parts as members, and only | |
1399 | # declare success if we can find them all. |
|
1399 | # declare success if we can find them all. | |
1400 | oname_parts = oname.split('.') |
|
1400 | oname_parts = oname.split('.') | |
1401 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1401 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1402 | for nsname,ns in namespaces: |
|
1402 | for nsname,ns in namespaces: | |
1403 | try: |
|
1403 | try: | |
1404 | obj = ns[oname_head] |
|
1404 | obj = ns[oname_head] | |
1405 | except KeyError: |
|
1405 | except KeyError: | |
1406 | continue |
|
1406 | continue | |
1407 | else: |
|
1407 | else: | |
1408 | #print 'oname_rest:', oname_rest # dbg |
|
1408 | #print 'oname_rest:', oname_rest # dbg | |
1409 | for part in oname_rest: |
|
1409 | for part in oname_rest: | |
1410 | try: |
|
1410 | try: | |
1411 | parent = obj |
|
1411 | parent = obj | |
1412 | obj = getattr(obj,part) |
|
1412 | obj = getattr(obj,part) | |
1413 | except: |
|
1413 | except: | |
1414 | # Blanket except b/c some badly implemented objects |
|
1414 | # Blanket except b/c some badly implemented objects | |
1415 | # allow __getattr__ to raise exceptions other than |
|
1415 | # allow __getattr__ to raise exceptions other than | |
1416 | # AttributeError, which then crashes IPython. |
|
1416 | # AttributeError, which then crashes IPython. | |
1417 | break |
|
1417 | break | |
1418 | else: |
|
1418 | else: | |
1419 | # If we finish the for loop (no break), we got all members |
|
1419 | # If we finish the for loop (no break), we got all members | |
1420 | found = True |
|
1420 | found = True | |
1421 | ospace = nsname |
|
1421 | ospace = nsname | |
1422 | if ns == alias_ns: |
|
1422 | if ns == alias_ns: | |
1423 | isalias = True |
|
1423 | isalias = True | |
1424 | break # namespace loop |
|
1424 | break # namespace loop | |
1425 |
|
1425 | |||
1426 | # Try to see if it's magic |
|
1426 | # Try to see if it's magic | |
1427 | if not found: |
|
1427 | if not found: | |
1428 | obj = None |
|
1428 | obj = None | |
1429 | if oname.startswith(ESC_MAGIC2): |
|
1429 | if oname.startswith(ESC_MAGIC2): | |
1430 | oname = oname.lstrip(ESC_MAGIC2) |
|
1430 | oname = oname.lstrip(ESC_MAGIC2) | |
1431 | obj = self.find_cell_magic(oname) |
|
1431 | obj = self.find_cell_magic(oname) | |
1432 | elif oname.startswith(ESC_MAGIC): |
|
1432 | elif oname.startswith(ESC_MAGIC): | |
1433 | oname = oname.lstrip(ESC_MAGIC) |
|
1433 | oname = oname.lstrip(ESC_MAGIC) | |
1434 | obj = self.find_line_magic(oname) |
|
1434 | obj = self.find_line_magic(oname) | |
1435 | else: |
|
1435 | else: | |
1436 | # search without prefix, so run? will find %run? |
|
1436 | # search without prefix, so run? will find %run? | |
1437 | obj = self.find_line_magic(oname) |
|
1437 | obj = self.find_line_magic(oname) | |
1438 | if obj is None: |
|
1438 | if obj is None: | |
1439 | obj = self.find_cell_magic(oname) |
|
1439 | obj = self.find_cell_magic(oname) | |
1440 | if obj is not None: |
|
1440 | if obj is not None: | |
1441 | found = True |
|
1441 | found = True | |
1442 | ospace = 'IPython internal' |
|
1442 | ospace = 'IPython internal' | |
1443 | ismagic = True |
|
1443 | ismagic = True | |
1444 |
|
1444 | |||
1445 | # Last try: special-case some literals like '', [], {}, etc: |
|
1445 | # Last try: special-case some literals like '', [], {}, etc: | |
1446 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1446 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1447 | obj = eval(oname_head) |
|
1447 | obj = eval(oname_head) | |
1448 | found = True |
|
1448 | found = True | |
1449 | ospace = 'Interactive' |
|
1449 | ospace = 'Interactive' | |
1450 |
|
1450 | |||
1451 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1451 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1452 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1452 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1453 |
|
1453 | |||
1454 | def _ofind_property(self, oname, info): |
|
1454 | def _ofind_property(self, oname, info): | |
1455 | """Second part of object finding, to look for property details.""" |
|
1455 | """Second part of object finding, to look for property details.""" | |
1456 | if info.found: |
|
1456 | if info.found: | |
1457 | # Get the docstring of the class property if it exists. |
|
1457 | # Get the docstring of the class property if it exists. | |
1458 | path = oname.split('.') |
|
1458 | path = oname.split('.') | |
1459 | root = '.'.join(path[:-1]) |
|
1459 | root = '.'.join(path[:-1]) | |
1460 | if info.parent is not None: |
|
1460 | if info.parent is not None: | |
1461 | try: |
|
1461 | try: | |
1462 | target = getattr(info.parent, '__class__') |
|
1462 | target = getattr(info.parent, '__class__') | |
1463 | # The object belongs to a class instance. |
|
1463 | # The object belongs to a class instance. | |
1464 | try: |
|
1464 | try: | |
1465 | target = getattr(target, path[-1]) |
|
1465 | target = getattr(target, path[-1]) | |
1466 | # The class defines the object. |
|
1466 | # The class defines the object. | |
1467 | if isinstance(target, property): |
|
1467 | if isinstance(target, property): | |
1468 | oname = root + '.__class__.' + path[-1] |
|
1468 | oname = root + '.__class__.' + path[-1] | |
1469 | info = Struct(self._ofind(oname)) |
|
1469 | info = Struct(self._ofind(oname)) | |
1470 | except AttributeError: pass |
|
1470 | except AttributeError: pass | |
1471 | except AttributeError: pass |
|
1471 | except AttributeError: pass | |
1472 |
|
1472 | |||
1473 | # We return either the new info or the unmodified input if the object |
|
1473 | # We return either the new info or the unmodified input if the object | |
1474 | # hadn't been found |
|
1474 | # hadn't been found | |
1475 | return info |
|
1475 | return info | |
1476 |
|
1476 | |||
1477 | def _object_find(self, oname, namespaces=None): |
|
1477 | def _object_find(self, oname, namespaces=None): | |
1478 | """Find an object and return a struct with info about it.""" |
|
1478 | """Find an object and return a struct with info about it.""" | |
1479 | inf = Struct(self._ofind(oname, namespaces)) |
|
1479 | inf = Struct(self._ofind(oname, namespaces)) | |
1480 | return Struct(self._ofind_property(oname, inf)) |
|
1480 | return Struct(self._ofind_property(oname, inf)) | |
1481 |
|
1481 | |||
1482 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1482 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1483 | """Generic interface to the inspector system. |
|
1483 | """Generic interface to the inspector system. | |
1484 |
|
1484 | |||
1485 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1485 | This function is meant to be called by pdef, pdoc & friends.""" | |
1486 | info = self._object_find(oname) |
|
1486 | info = self._object_find(oname) | |
1487 | if info.found: |
|
1487 | if info.found: | |
1488 | pmethod = getattr(self.inspector, meth) |
|
1488 | pmethod = getattr(self.inspector, meth) | |
1489 | formatter = format_screen if info.ismagic else None |
|
1489 | formatter = format_screen if info.ismagic else None | |
1490 | if meth == 'pdoc': |
|
1490 | if meth == 'pdoc': | |
1491 | pmethod(info.obj, oname, formatter) |
|
1491 | pmethod(info.obj, oname, formatter) | |
1492 | elif meth == 'pinfo': |
|
1492 | elif meth == 'pinfo': | |
1493 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1493 | pmethod(info.obj, oname, formatter, info, **kw) | |
1494 | else: |
|
1494 | else: | |
1495 | pmethod(info.obj, oname) |
|
1495 | pmethod(info.obj, oname) | |
1496 | else: |
|
1496 | else: | |
1497 | print('Object `%s` not found.' % oname) |
|
1497 | print('Object `%s` not found.' % oname) | |
1498 | return 'not found' # so callers can take other action |
|
1498 | return 'not found' # so callers can take other action | |
1499 |
|
1499 | |||
1500 | def object_inspect(self, oname, detail_level=0): |
|
1500 | def object_inspect(self, oname, detail_level=0): | |
1501 | with self.builtin_trap: |
|
1501 | with self.builtin_trap: | |
1502 | info = self._object_find(oname) |
|
1502 | info = self._object_find(oname) | |
1503 | if info.found: |
|
1503 | if info.found: | |
1504 | return self.inspector.info(info.obj, oname, info=info, |
|
1504 | return self.inspector.info(info.obj, oname, info=info, | |
1505 | detail_level=detail_level |
|
1505 | detail_level=detail_level | |
1506 | ) |
|
1506 | ) | |
1507 | else: |
|
1507 | else: | |
1508 | return oinspect.object_info(name=oname, found=False) |
|
1508 | return oinspect.object_info(name=oname, found=False) | |
1509 |
|
1509 | |||
1510 | #------------------------------------------------------------------------- |
|
1510 | #------------------------------------------------------------------------- | |
1511 | # Things related to history management |
|
1511 | # Things related to history management | |
1512 | #------------------------------------------------------------------------- |
|
1512 | #------------------------------------------------------------------------- | |
1513 |
|
1513 | |||
1514 | def init_history(self): |
|
1514 | def init_history(self): | |
1515 | """Sets up the command history, and starts regular autosaves.""" |
|
1515 | """Sets up the command history, and starts regular autosaves.""" | |
1516 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1516 | self.history_manager = HistoryManager(shell=self, config=self.config) | |
1517 | self.configurables.append(self.history_manager) |
|
1517 | self.configurables.append(self.history_manager) | |
1518 |
|
1518 | |||
1519 | #------------------------------------------------------------------------- |
|
1519 | #------------------------------------------------------------------------- | |
1520 | # Things related to exception handling and tracebacks (not debugging) |
|
1520 | # Things related to exception handling and tracebacks (not debugging) | |
1521 | #------------------------------------------------------------------------- |
|
1521 | #------------------------------------------------------------------------- | |
1522 |
|
1522 | |||
1523 | def init_traceback_handlers(self, custom_exceptions): |
|
1523 | def init_traceback_handlers(self, custom_exceptions): | |
1524 | # Syntax error handler. |
|
1524 | # Syntax error handler. | |
1525 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1525 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1526 |
|
1526 | |||
1527 | # The interactive one is initialized with an offset, meaning we always |
|
1527 | # The interactive one is initialized with an offset, meaning we always | |
1528 | # want to remove the topmost item in the traceback, which is our own |
|
1528 | # want to remove the topmost item in the traceback, which is our own | |
1529 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1529 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1530 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1530 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1531 | color_scheme='NoColor', |
|
1531 | color_scheme='NoColor', | |
1532 | tb_offset = 1, |
|
1532 | tb_offset = 1, | |
1533 | check_cache=self.compile.check_cache) |
|
1533 | check_cache=self.compile.check_cache) | |
1534 |
|
1534 | |||
1535 | # The instance will store a pointer to the system-wide exception hook, |
|
1535 | # The instance will store a pointer to the system-wide exception hook, | |
1536 | # so that runtime code (such as magics) can access it. This is because |
|
1536 | # so that runtime code (such as magics) can access it. This is because | |
1537 | # during the read-eval loop, it may get temporarily overwritten. |
|
1537 | # during the read-eval loop, it may get temporarily overwritten. | |
1538 | self.sys_excepthook = sys.excepthook |
|
1538 | self.sys_excepthook = sys.excepthook | |
1539 |
|
1539 | |||
1540 | # and add any custom exception handlers the user may have specified |
|
1540 | # and add any custom exception handlers the user may have specified | |
1541 | self.set_custom_exc(*custom_exceptions) |
|
1541 | self.set_custom_exc(*custom_exceptions) | |
1542 |
|
1542 | |||
1543 | # Set the exception mode |
|
1543 | # Set the exception mode | |
1544 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1544 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1545 |
|
1545 | |||
1546 | def set_custom_exc(self, exc_tuple, handler): |
|
1546 | def set_custom_exc(self, exc_tuple, handler): | |
1547 | """set_custom_exc(exc_tuple,handler) |
|
1547 | """set_custom_exc(exc_tuple,handler) | |
1548 |
|
1548 | |||
1549 | Set a custom exception handler, which will be called if any of the |
|
1549 | Set a custom exception handler, which will be called if any of the | |
1550 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1550 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1551 | run_code() method). |
|
1551 | run_code() method). | |
1552 |
|
1552 | |||
1553 | Parameters |
|
1553 | Parameters | |
1554 | ---------- |
|
1554 | ---------- | |
1555 |
|
1555 | |||
1556 | exc_tuple : tuple of exception classes |
|
1556 | exc_tuple : tuple of exception classes | |
1557 | A *tuple* of exception classes, for which to call the defined |
|
1557 | A *tuple* of exception classes, for which to call the defined | |
1558 | handler. It is very important that you use a tuple, and NOT A |
|
1558 | handler. It is very important that you use a tuple, and NOT A | |
1559 | LIST here, because of the way Python's except statement works. If |
|
1559 | LIST here, because of the way Python's except statement works. If | |
1560 | you only want to trap a single exception, use a singleton tuple:: |
|
1560 | you only want to trap a single exception, use a singleton tuple:: | |
1561 |
|
1561 | |||
1562 | exc_tuple == (MyCustomException,) |
|
1562 | exc_tuple == (MyCustomException,) | |
1563 |
|
1563 | |||
1564 | handler : callable |
|
1564 | handler : callable | |
1565 | handler must have the following signature:: |
|
1565 | handler must have the following signature:: | |
1566 |
|
1566 | |||
1567 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1567 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1568 | ... |
|
1568 | ... | |
1569 | return structured_traceback |
|
1569 | return structured_traceback | |
1570 |
|
1570 | |||
1571 | Your handler must return a structured traceback (a list of strings), |
|
1571 | Your handler must return a structured traceback (a list of strings), | |
1572 | or None. |
|
1572 | or None. | |
1573 |
|
1573 | |||
1574 | This will be made into an instance method (via types.MethodType) |
|
1574 | This will be made into an instance method (via types.MethodType) | |
1575 | of IPython itself, and it will be called if any of the exceptions |
|
1575 | of IPython itself, and it will be called if any of the exceptions | |
1576 | listed in the exc_tuple are caught. If the handler is None, an |
|
1576 | listed in the exc_tuple are caught. If the handler is None, an | |
1577 | internal basic one is used, which just prints basic info. |
|
1577 | internal basic one is used, which just prints basic info. | |
1578 |
|
1578 | |||
1579 | To protect IPython from crashes, if your handler ever raises an |
|
1579 | To protect IPython from crashes, if your handler ever raises an | |
1580 | exception or returns an invalid result, it will be immediately |
|
1580 | exception or returns an invalid result, it will be immediately | |
1581 | disabled. |
|
1581 | disabled. | |
1582 |
|
1582 | |||
1583 | WARNING: by putting in your own exception handler into IPython's main |
|
1583 | WARNING: by putting in your own exception handler into IPython's main | |
1584 | execution loop, you run a very good chance of nasty crashes. This |
|
1584 | execution loop, you run a very good chance of nasty crashes. This | |
1585 | facility should only be used if you really know what you are doing.""" |
|
1585 | facility should only be used if you really know what you are doing.""" | |
1586 |
|
1586 | |||
1587 | assert type(exc_tuple)==type(()) , \ |
|
1587 | assert type(exc_tuple)==type(()) , \ | |
1588 | "The custom exceptions must be given AS A TUPLE." |
|
1588 | "The custom exceptions must be given AS A TUPLE." | |
1589 |
|
1589 | |||
1590 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1590 | def dummy_handler(self,etype,value,tb,tb_offset=None): | |
1591 | print('*** Simple custom exception handler ***') |
|
1591 | print('*** Simple custom exception handler ***') | |
1592 | print('Exception type :',etype) |
|
1592 | print('Exception type :',etype) | |
1593 | print('Exception value:',value) |
|
1593 | print('Exception value:',value) | |
1594 | print('Traceback :',tb) |
|
1594 | print('Traceback :',tb) | |
1595 | #print 'Source code :','\n'.join(self.buffer) |
|
1595 | #print 'Source code :','\n'.join(self.buffer) | |
1596 |
|
1596 | |||
1597 | def validate_stb(stb): |
|
1597 | def validate_stb(stb): | |
1598 | """validate structured traceback return type |
|
1598 | """validate structured traceback return type | |
1599 |
|
1599 | |||
1600 | return type of CustomTB *should* be a list of strings, but allow |
|
1600 | return type of CustomTB *should* be a list of strings, but allow | |
1601 | single strings or None, which are harmless. |
|
1601 | single strings or None, which are harmless. | |
1602 |
|
1602 | |||
1603 | This function will *always* return a list of strings, |
|
1603 | This function will *always* return a list of strings, | |
1604 | and will raise a TypeError if stb is inappropriate. |
|
1604 | and will raise a TypeError if stb is inappropriate. | |
1605 | """ |
|
1605 | """ | |
1606 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1606 | msg = "CustomTB must return list of strings, not %r" % stb | |
1607 | if stb is None: |
|
1607 | if stb is None: | |
1608 | return [] |
|
1608 | return [] | |
1609 | elif isinstance(stb, basestring): |
|
1609 | elif isinstance(stb, basestring): | |
1610 | return [stb] |
|
1610 | return [stb] | |
1611 | elif not isinstance(stb, list): |
|
1611 | elif not isinstance(stb, list): | |
1612 | raise TypeError(msg) |
|
1612 | raise TypeError(msg) | |
1613 | # it's a list |
|
1613 | # it's a list | |
1614 | for line in stb: |
|
1614 | for line in stb: | |
1615 | # check every element |
|
1615 | # check every element | |
1616 | if not isinstance(line, basestring): |
|
1616 | if not isinstance(line, basestring): | |
1617 | raise TypeError(msg) |
|
1617 | raise TypeError(msg) | |
1618 | return stb |
|
1618 | return stb | |
1619 |
|
1619 | |||
1620 | if handler is None: |
|
1620 | if handler is None: | |
1621 | wrapped = dummy_handler |
|
1621 | wrapped = dummy_handler | |
1622 | else: |
|
1622 | else: | |
1623 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1623 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1624 | """wrap CustomTB handler, to protect IPython from user code |
|
1624 | """wrap CustomTB handler, to protect IPython from user code | |
1625 |
|
1625 | |||
1626 | This makes it harder (but not impossible) for custom exception |
|
1626 | This makes it harder (but not impossible) for custom exception | |
1627 | handlers to crash IPython. |
|
1627 | handlers to crash IPython. | |
1628 | """ |
|
1628 | """ | |
1629 | try: |
|
1629 | try: | |
1630 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1630 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1631 | return validate_stb(stb) |
|
1631 | return validate_stb(stb) | |
1632 | except: |
|
1632 | except: | |
1633 | # clear custom handler immediately |
|
1633 | # clear custom handler immediately | |
1634 | self.set_custom_exc((), None) |
|
1634 | self.set_custom_exc((), None) | |
1635 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1635 | print("Custom TB Handler failed, unregistering", file=io.stderr) | |
1636 | # show the exception in handler first |
|
1636 | # show the exception in handler first | |
1637 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1637 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1638 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1638 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1639 | print("The original exception:", file=io.stdout) |
|
1639 | print("The original exception:", file=io.stdout) | |
1640 | stb = self.InteractiveTB.structured_traceback( |
|
1640 | stb = self.InteractiveTB.structured_traceback( | |
1641 | (etype,value,tb), tb_offset=tb_offset |
|
1641 | (etype,value,tb), tb_offset=tb_offset | |
1642 | ) |
|
1642 | ) | |
1643 | return stb |
|
1643 | return stb | |
1644 |
|
1644 | |||
1645 | self.CustomTB = types.MethodType(wrapped,self) |
|
1645 | self.CustomTB = types.MethodType(wrapped,self) | |
1646 | self.custom_exceptions = exc_tuple |
|
1646 | self.custom_exceptions = exc_tuple | |
1647 |
|
1647 | |||
1648 | def excepthook(self, etype, value, tb): |
|
1648 | def excepthook(self, etype, value, tb): | |
1649 | """One more defense for GUI apps that call sys.excepthook. |
|
1649 | """One more defense for GUI apps that call sys.excepthook. | |
1650 |
|
1650 | |||
1651 | GUI frameworks like wxPython trap exceptions and call |
|
1651 | GUI frameworks like wxPython trap exceptions and call | |
1652 | sys.excepthook themselves. I guess this is a feature that |
|
1652 | sys.excepthook themselves. I guess this is a feature that | |
1653 | enables them to keep running after exceptions that would |
|
1653 | enables them to keep running after exceptions that would | |
1654 | otherwise kill their mainloop. This is a bother for IPython |
|
1654 | otherwise kill their mainloop. This is a bother for IPython | |
1655 | which excepts to catch all of the program exceptions with a try: |
|
1655 | which excepts to catch all of the program exceptions with a try: | |
1656 | except: statement. |
|
1656 | except: statement. | |
1657 |
|
1657 | |||
1658 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1658 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1659 | any app directly invokes sys.excepthook, it will look to the user like |
|
1659 | any app directly invokes sys.excepthook, it will look to the user like | |
1660 | IPython crashed. In order to work around this, we can disable the |
|
1660 | IPython crashed. In order to work around this, we can disable the | |
1661 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1661 | CrashHandler and replace it with this excepthook instead, which prints a | |
1662 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1662 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1663 | call sys.excepthook will generate a regular-looking exception from |
|
1663 | call sys.excepthook will generate a regular-looking exception from | |
1664 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1664 | IPython, and the CrashHandler will only be triggered by real IPython | |
1665 | crashes. |
|
1665 | crashes. | |
1666 |
|
1666 | |||
1667 | This hook should be used sparingly, only in places which are not likely |
|
1667 | This hook should be used sparingly, only in places which are not likely | |
1668 | to be true IPython errors. |
|
1668 | to be true IPython errors. | |
1669 | """ |
|
1669 | """ | |
1670 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1670 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1671 |
|
1671 | |||
1672 | def _get_exc_info(self, exc_tuple=None): |
|
1672 | def _get_exc_info(self, exc_tuple=None): | |
1673 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1673 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1674 |
|
1674 | |||
1675 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1675 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1676 | from whichever source. |
|
1676 | from whichever source. | |
1677 |
|
1677 | |||
1678 | raises ValueError if none of these contain any information |
|
1678 | raises ValueError if none of these contain any information | |
1679 | """ |
|
1679 | """ | |
1680 | if exc_tuple is None: |
|
1680 | if exc_tuple is None: | |
1681 | etype, value, tb = sys.exc_info() |
|
1681 | etype, value, tb = sys.exc_info() | |
1682 | else: |
|
1682 | else: | |
1683 | etype, value, tb = exc_tuple |
|
1683 | etype, value, tb = exc_tuple | |
1684 |
|
1684 | |||
1685 | if etype is None: |
|
1685 | if etype is None: | |
1686 | if hasattr(sys, 'last_type'): |
|
1686 | if hasattr(sys, 'last_type'): | |
1687 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1687 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1688 | sys.last_traceback |
|
1688 | sys.last_traceback | |
1689 |
|
1689 | |||
1690 | if etype is None: |
|
1690 | if etype is None: | |
1691 | raise ValueError("No exception to find") |
|
1691 | raise ValueError("No exception to find") | |
1692 |
|
1692 | |||
1693 | # Now store the exception info in sys.last_type etc. |
|
1693 | # Now store the exception info in sys.last_type etc. | |
1694 | # WARNING: these variables are somewhat deprecated and not |
|
1694 | # WARNING: these variables are somewhat deprecated and not | |
1695 | # necessarily safe to use in a threaded environment, but tools |
|
1695 | # necessarily safe to use in a threaded environment, but tools | |
1696 | # like pdb depend on their existence, so let's set them. If we |
|
1696 | # like pdb depend on their existence, so let's set them. If we | |
1697 | # find problems in the field, we'll need to revisit their use. |
|
1697 | # find problems in the field, we'll need to revisit their use. | |
1698 | sys.last_type = etype |
|
1698 | sys.last_type = etype | |
1699 | sys.last_value = value |
|
1699 | sys.last_value = value | |
1700 | sys.last_traceback = tb |
|
1700 | sys.last_traceback = tb | |
1701 |
|
1701 | |||
1702 | return etype, value, tb |
|
1702 | return etype, value, tb | |
1703 |
|
1703 | |||
1704 |
|
1704 | |||
1705 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1705 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1706 | exception_only=False): |
|
1706 | exception_only=False): | |
1707 | """Display the exception that just occurred. |
|
1707 | """Display the exception that just occurred. | |
1708 |
|
1708 | |||
1709 | If nothing is known about the exception, this is the method which |
|
1709 | If nothing is known about the exception, this is the method which | |
1710 | should be used throughout the code for presenting user tracebacks, |
|
1710 | should be used throughout the code for presenting user tracebacks, | |
1711 | rather than directly invoking the InteractiveTB object. |
|
1711 | rather than directly invoking the InteractiveTB object. | |
1712 |
|
1712 | |||
1713 | A specific showsyntaxerror() also exists, but this method can take |
|
1713 | A specific showsyntaxerror() also exists, but this method can take | |
1714 | care of calling it if needed, so unless you are explicitly catching a |
|
1714 | care of calling it if needed, so unless you are explicitly catching a | |
1715 | SyntaxError exception, don't try to analyze the stack manually and |
|
1715 | SyntaxError exception, don't try to analyze the stack manually and | |
1716 | simply call this method.""" |
|
1716 | simply call this method.""" | |
1717 |
|
1717 | |||
1718 | try: |
|
1718 | try: | |
1719 | try: |
|
1719 | try: | |
1720 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1720 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1721 | except ValueError: |
|
1721 | except ValueError: | |
1722 | self.write_err('No traceback available to show.\n') |
|
1722 | self.write_err('No traceback available to show.\n') | |
1723 | return |
|
1723 | return | |
1724 |
|
1724 | |||
1725 | if etype is SyntaxError: |
|
1725 | if etype is SyntaxError: | |
1726 | # Though this won't be called by syntax errors in the input |
|
1726 | # Though this won't be called by syntax errors in the input | |
1727 | # line, there may be SyntaxError cases with imported code. |
|
1727 | # line, there may be SyntaxError cases with imported code. | |
1728 | self.showsyntaxerror(filename) |
|
1728 | self.showsyntaxerror(filename) | |
1729 | elif etype is UsageError: |
|
1729 | elif etype is UsageError: | |
1730 | self.write_err("UsageError: %s" % value) |
|
1730 | self.write_err("UsageError: %s" % value) | |
1731 | elif issubclass(etype, RemoteError): |
|
1731 | elif issubclass(etype, RemoteError): | |
1732 | # IPython.parallel remote exceptions. |
|
1732 | # IPython.parallel remote exceptions. | |
1733 | # Draw the remote traceback, not the local one. |
|
1733 | # Draw the remote traceback, not the local one. | |
1734 | self._showtraceback(etype, value, value.render_traceback()) |
|
1734 | self._showtraceback(etype, value, value.render_traceback()) | |
1735 | else: |
|
1735 | else: | |
1736 | if exception_only: |
|
1736 | if exception_only: | |
1737 | stb = ['An exception has occurred, use %tb to see ' |
|
1737 | stb = ['An exception has occurred, use %tb to see ' | |
1738 | 'the full traceback.\n'] |
|
1738 | 'the full traceback.\n'] | |
1739 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1739 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1740 | value)) |
|
1740 | value)) | |
1741 | else: |
|
1741 | else: | |
1742 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1742 | stb = self.InteractiveTB.structured_traceback(etype, | |
1743 | value, tb, tb_offset=tb_offset) |
|
1743 | value, tb, tb_offset=tb_offset) | |
1744 |
|
1744 | |||
1745 | self._showtraceback(etype, value, stb) |
|
1745 | self._showtraceback(etype, value, stb) | |
1746 | if self.call_pdb: |
|
1746 | if self.call_pdb: | |
1747 | # drop into debugger |
|
1747 | # drop into debugger | |
1748 | self.debugger(force=True) |
|
1748 | self.debugger(force=True) | |
1749 | return |
|
1749 | return | |
1750 |
|
1750 | |||
1751 | # Actually show the traceback |
|
1751 | # Actually show the traceback | |
1752 | self._showtraceback(etype, value, stb) |
|
1752 | self._showtraceback(etype, value, stb) | |
1753 |
|
1753 | |||
1754 | except KeyboardInterrupt: |
|
1754 | except KeyboardInterrupt: | |
1755 | self.write_err("\nKeyboardInterrupt\n") |
|
1755 | self.write_err("\nKeyboardInterrupt\n") | |
1756 |
|
1756 | |||
1757 | def _showtraceback(self, etype, evalue, stb): |
|
1757 | def _showtraceback(self, etype, evalue, stb): | |
1758 | """Actually show a traceback. |
|
1758 | """Actually show a traceback. | |
1759 |
|
1759 | |||
1760 | Subclasses may override this method to put the traceback on a different |
|
1760 | Subclasses may override this method to put the traceback on a different | |
1761 | place, like a side channel. |
|
1761 | place, like a side channel. | |
1762 | """ |
|
1762 | """ | |
1763 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1763 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1764 |
|
1764 | |||
1765 | def showsyntaxerror(self, filename=None): |
|
1765 | def showsyntaxerror(self, filename=None): | |
1766 | """Display the syntax error that just occurred. |
|
1766 | """Display the syntax error that just occurred. | |
1767 |
|
1767 | |||
1768 | This doesn't display a stack trace because there isn't one. |
|
1768 | This doesn't display a stack trace because there isn't one. | |
1769 |
|
1769 | |||
1770 | If a filename is given, it is stuffed in the exception instead |
|
1770 | If a filename is given, it is stuffed in the exception instead | |
1771 | of what was there before (because Python's parser always uses |
|
1771 | of what was there before (because Python's parser always uses | |
1772 | "<string>" when reading from a string). |
|
1772 | "<string>" when reading from a string). | |
1773 | """ |
|
1773 | """ | |
1774 | etype, value, last_traceback = self._get_exc_info() |
|
1774 | etype, value, last_traceback = self._get_exc_info() | |
1775 |
|
1775 | |||
1776 | if filename and etype is SyntaxError: |
|
1776 | if filename and etype is SyntaxError: | |
1777 | try: |
|
1777 | try: | |
1778 | value.filename = filename |
|
1778 | value.filename = filename | |
1779 | except: |
|
1779 | except: | |
1780 | # Not the format we expect; leave it alone |
|
1780 | # Not the format we expect; leave it alone | |
1781 | pass |
|
1781 | pass | |
1782 |
|
1782 | |||
1783 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1783 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1784 | self._showtraceback(etype, value, stb) |
|
1784 | self._showtraceback(etype, value, stb) | |
1785 |
|
1785 | |||
1786 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1786 | # This is overridden in TerminalInteractiveShell to show a message about | |
1787 | # the %paste magic. |
|
1787 | # the %paste magic. | |
1788 | def showindentationerror(self): |
|
1788 | def showindentationerror(self): | |
1789 | """Called by run_cell when there's an IndentationError in code entered |
|
1789 | """Called by run_cell when there's an IndentationError in code entered | |
1790 | at the prompt. |
|
1790 | at the prompt. | |
1791 |
|
1791 | |||
1792 | This is overridden in TerminalInteractiveShell to show a message about |
|
1792 | This is overridden in TerminalInteractiveShell to show a message about | |
1793 | the %paste magic.""" |
|
1793 | the %paste magic.""" | |
1794 | self.showsyntaxerror() |
|
1794 | self.showsyntaxerror() | |
1795 |
|
1795 | |||
1796 | #------------------------------------------------------------------------- |
|
1796 | #------------------------------------------------------------------------- | |
1797 | # Things related to readline |
|
1797 | # Things related to readline | |
1798 | #------------------------------------------------------------------------- |
|
1798 | #------------------------------------------------------------------------- | |
1799 |
|
1799 | |||
1800 | def init_readline(self): |
|
1800 | def init_readline(self): | |
1801 | """Command history completion/saving/reloading.""" |
|
1801 | """Command history completion/saving/reloading.""" | |
1802 |
|
1802 | |||
1803 | if self.readline_use: |
|
1803 | if self.readline_use: | |
1804 | import IPython.utils.rlineimpl as readline |
|
1804 | import IPython.utils.rlineimpl as readline | |
1805 |
|
1805 | |||
1806 | self.rl_next_input = None |
|
1806 | self.rl_next_input = None | |
1807 | self.rl_do_indent = False |
|
1807 | self.rl_do_indent = False | |
1808 |
|
1808 | |||
1809 | if not self.readline_use or not readline.have_readline: |
|
1809 | if not self.readline_use or not readline.have_readline: | |
1810 | self.has_readline = False |
|
1810 | self.has_readline = False | |
1811 | self.readline = None |
|
1811 | self.readline = None | |
1812 | # Set a number of methods that depend on readline to be no-op |
|
1812 | # Set a number of methods that depend on readline to be no-op | |
1813 | self.readline_no_record = no_op_context |
|
1813 | self.readline_no_record = no_op_context | |
1814 | self.set_readline_completer = no_op |
|
1814 | self.set_readline_completer = no_op | |
1815 | self.set_custom_completer = no_op |
|
1815 | self.set_custom_completer = no_op | |
1816 | self.set_completer_frame = no_op |
|
1816 | self.set_completer_frame = no_op | |
1817 | if self.readline_use: |
|
1817 | if self.readline_use: | |
1818 | warn('Readline services not available or not loaded.') |
|
1818 | warn('Readline services not available or not loaded.') | |
1819 | else: |
|
1819 | else: | |
1820 | self.has_readline = True |
|
1820 | self.has_readline = True | |
1821 | self.readline = readline |
|
1821 | self.readline = readline | |
1822 | sys.modules['readline'] = readline |
|
1822 | sys.modules['readline'] = readline | |
1823 |
|
1823 | |||
1824 | # Platform-specific configuration |
|
1824 | # Platform-specific configuration | |
1825 | if os.name == 'nt': |
|
1825 | if os.name == 'nt': | |
1826 | # FIXME - check with Frederick to see if we can harmonize |
|
1826 | # FIXME - check with Frederick to see if we can harmonize | |
1827 | # naming conventions with pyreadline to avoid this |
|
1827 | # naming conventions with pyreadline to avoid this | |
1828 | # platform-dependent check |
|
1828 | # platform-dependent check | |
1829 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1829 | self.readline_startup_hook = readline.set_pre_input_hook | |
1830 | else: |
|
1830 | else: | |
1831 | self.readline_startup_hook = readline.set_startup_hook |
|
1831 | self.readline_startup_hook = readline.set_startup_hook | |
1832 |
|
1832 | |||
1833 | # Load user's initrc file (readline config) |
|
1833 | # Load user's initrc file (readline config) | |
1834 | # Or if libedit is used, load editrc. |
|
1834 | # Or if libedit is used, load editrc. | |
1835 | inputrc_name = os.environ.get('INPUTRC') |
|
1835 | inputrc_name = os.environ.get('INPUTRC') | |
1836 | if inputrc_name is None: |
|
1836 | if inputrc_name is None: | |
1837 | inputrc_name = '.inputrc' |
|
1837 | inputrc_name = '.inputrc' | |
1838 | if readline.uses_libedit: |
|
1838 | if readline.uses_libedit: | |
1839 | inputrc_name = '.editrc' |
|
1839 | inputrc_name = '.editrc' | |
1840 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1840 | inputrc_name = os.path.join(self.home_dir, inputrc_name) | |
1841 | if os.path.isfile(inputrc_name): |
|
1841 | if os.path.isfile(inputrc_name): | |
1842 | try: |
|
1842 | try: | |
1843 | readline.read_init_file(inputrc_name) |
|
1843 | readline.read_init_file(inputrc_name) | |
1844 | except: |
|
1844 | except: | |
1845 | warn('Problems reading readline initialization file <%s>' |
|
1845 | warn('Problems reading readline initialization file <%s>' | |
1846 | % inputrc_name) |
|
1846 | % inputrc_name) | |
1847 |
|
1847 | |||
1848 | # Configure readline according to user's prefs |
|
1848 | # Configure readline according to user's prefs | |
1849 | # This is only done if GNU readline is being used. If libedit |
|
1849 | # This is only done if GNU readline is being used. If libedit | |
1850 | # is being used (as on Leopard) the readline config is |
|
1850 | # is being used (as on Leopard) the readline config is | |
1851 | # not run as the syntax for libedit is different. |
|
1851 | # not run as the syntax for libedit is different. | |
1852 | if not readline.uses_libedit: |
|
1852 | if not readline.uses_libedit: | |
1853 | for rlcommand in self.readline_parse_and_bind: |
|
1853 | for rlcommand in self.readline_parse_and_bind: | |
1854 | #print "loading rl:",rlcommand # dbg |
|
1854 | #print "loading rl:",rlcommand # dbg | |
1855 | readline.parse_and_bind(rlcommand) |
|
1855 | readline.parse_and_bind(rlcommand) | |
1856 |
|
1856 | |||
1857 | # Remove some chars from the delimiters list. If we encounter |
|
1857 | # Remove some chars from the delimiters list. If we encounter | |
1858 | # unicode chars, discard them. |
|
1858 | # unicode chars, discard them. | |
1859 | delims = readline.get_completer_delims() |
|
1859 | delims = readline.get_completer_delims() | |
1860 | if not py3compat.PY3: |
|
1860 | if not py3compat.PY3: | |
1861 | delims = delims.encode("ascii", "ignore") |
|
1861 | delims = delims.encode("ascii", "ignore") | |
1862 | for d in self.readline_remove_delims: |
|
1862 | for d in self.readline_remove_delims: | |
1863 | delims = delims.replace(d, "") |
|
1863 | delims = delims.replace(d, "") | |
1864 | delims = delims.replace(ESC_MAGIC, '') |
|
1864 | delims = delims.replace(ESC_MAGIC, '') | |
1865 | readline.set_completer_delims(delims) |
|
1865 | readline.set_completer_delims(delims) | |
1866 | # otherwise we end up with a monster history after a while: |
|
1866 | # otherwise we end up with a monster history after a while: | |
1867 | readline.set_history_length(self.history_length) |
|
1867 | readline.set_history_length(self.history_length) | |
1868 |
|
1868 | |||
1869 | self.refill_readline_hist() |
|
1869 | self.refill_readline_hist() | |
1870 | self.readline_no_record = ReadlineNoRecord(self) |
|
1870 | self.readline_no_record = ReadlineNoRecord(self) | |
1871 |
|
1871 | |||
1872 | # Configure auto-indent for all platforms |
|
1872 | # Configure auto-indent for all platforms | |
1873 | self.set_autoindent(self.autoindent) |
|
1873 | self.set_autoindent(self.autoindent) | |
1874 |
|
1874 | |||
1875 | def refill_readline_hist(self): |
|
1875 | def refill_readline_hist(self): | |
1876 | # Load the last 1000 lines from history |
|
1876 | # Load the last 1000 lines from history | |
1877 | self.readline.clear_history() |
|
1877 | self.readline.clear_history() | |
1878 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1878 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1879 | last_cell = u"" |
|
1879 | last_cell = u"" | |
1880 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1880 | for _, _, cell in self.history_manager.get_tail(1000, | |
1881 | include_latest=True): |
|
1881 | include_latest=True): | |
1882 | # Ignore blank lines and consecutive duplicates |
|
1882 | # Ignore blank lines and consecutive duplicates | |
1883 | cell = cell.rstrip() |
|
1883 | cell = cell.rstrip() | |
1884 | if cell and (cell != last_cell): |
|
1884 | if cell and (cell != last_cell): | |
1885 | if self.multiline_history: |
|
1885 | if self.multiline_history: | |
1886 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1886 | self.readline.add_history(py3compat.unicode_to_str(cell, | |
1887 | stdin_encoding)) |
|
1887 | stdin_encoding)) | |
1888 | else: |
|
1888 | else: | |
1889 | for line in cell.splitlines(): |
|
1889 | for line in cell.splitlines(): | |
1890 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1890 | self.readline.add_history(py3compat.unicode_to_str(line, | |
1891 | stdin_encoding)) |
|
1891 | stdin_encoding)) | |
1892 | last_cell = cell |
|
1892 | last_cell = cell | |
1893 |
|
1893 | |||
1894 | def set_next_input(self, s): |
|
1894 | def set_next_input(self, s): | |
1895 | """ Sets the 'default' input string for the next command line. |
|
1895 | """ Sets the 'default' input string for the next command line. | |
1896 |
|
1896 | |||
1897 | Requires readline. |
|
1897 | Requires readline. | |
1898 |
|
1898 | |||
1899 | Example: |
|
1899 | Example: | |
1900 |
|
1900 | |||
1901 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1901 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1902 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1902 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1903 | """ |
|
1903 | """ | |
1904 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1904 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1905 |
|
1905 | |||
1906 | # Maybe move this to the terminal subclass? |
|
1906 | # Maybe move this to the terminal subclass? | |
1907 | def pre_readline(self): |
|
1907 | def pre_readline(self): | |
1908 | """readline hook to be used at the start of each line. |
|
1908 | """readline hook to be used at the start of each line. | |
1909 |
|
1909 | |||
1910 | Currently it handles auto-indent only.""" |
|
1910 | Currently it handles auto-indent only.""" | |
1911 |
|
1911 | |||
1912 | if self.rl_do_indent: |
|
1912 | if self.rl_do_indent: | |
1913 | self.readline.insert_text(self._indent_current_str()) |
|
1913 | self.readline.insert_text(self._indent_current_str()) | |
1914 | if self.rl_next_input is not None: |
|
1914 | if self.rl_next_input is not None: | |
1915 | self.readline.insert_text(self.rl_next_input) |
|
1915 | self.readline.insert_text(self.rl_next_input) | |
1916 | self.rl_next_input = None |
|
1916 | self.rl_next_input = None | |
1917 |
|
1917 | |||
1918 | def _indent_current_str(self): |
|
1918 | def _indent_current_str(self): | |
1919 | """return the current level of indentation as a string""" |
|
1919 | """return the current level of indentation as a string""" | |
1920 | return self.input_splitter.indent_spaces * ' ' |
|
1920 | return self.input_splitter.indent_spaces * ' ' | |
1921 |
|
1921 | |||
1922 | #------------------------------------------------------------------------- |
|
1922 | #------------------------------------------------------------------------- | |
1923 | # Things related to text completion |
|
1923 | # Things related to text completion | |
1924 | #------------------------------------------------------------------------- |
|
1924 | #------------------------------------------------------------------------- | |
1925 |
|
1925 | |||
1926 | def init_completer(self): |
|
1926 | def init_completer(self): | |
1927 | """Initialize the completion machinery. |
|
1927 | """Initialize the completion machinery. | |
1928 |
|
1928 | |||
1929 | This creates completion machinery that can be used by client code, |
|
1929 | This creates completion machinery that can be used by client code, | |
1930 | either interactively in-process (typically triggered by the readline |
|
1930 | either interactively in-process (typically triggered by the readline | |
1931 | library), programatically (such as in test suites) or out-of-prcess |
|
1931 | library), programatically (such as in test suites) or out-of-prcess | |
1932 | (typically over the network by remote frontends). |
|
1932 | (typically over the network by remote frontends). | |
1933 | """ |
|
1933 | """ | |
1934 | from IPython.core.completer import IPCompleter |
|
1934 | from IPython.core.completer import IPCompleter | |
1935 | from IPython.core.completerlib import (module_completer, |
|
1935 | from IPython.core.completerlib import (module_completer, | |
1936 | magic_run_completer, cd_completer, reset_completer) |
|
1936 | magic_run_completer, cd_completer, reset_completer) | |
1937 |
|
1937 | |||
1938 | self.Completer = IPCompleter(shell=self, |
|
1938 | self.Completer = IPCompleter(shell=self, | |
1939 | namespace=self.user_ns, |
|
1939 | namespace=self.user_ns, | |
1940 | global_namespace=self.user_global_ns, |
|
1940 | global_namespace=self.user_global_ns, | |
1941 | alias_table=self.alias_manager.alias_table, |
|
1941 | alias_table=self.alias_manager.alias_table, | |
1942 | use_readline=self.has_readline, |
|
1942 | use_readline=self.has_readline, | |
1943 | config=self.config, |
|
1943 | config=self.config, | |
1944 | ) |
|
1944 | ) | |
1945 | self.configurables.append(self.Completer) |
|
1945 | self.configurables.append(self.Completer) | |
1946 |
|
1946 | |||
1947 | # Add custom completers to the basic ones built into IPCompleter |
|
1947 | # Add custom completers to the basic ones built into IPCompleter | |
1948 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1948 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1949 | self.strdispatchers['complete_command'] = sdisp |
|
1949 | self.strdispatchers['complete_command'] = sdisp | |
1950 | self.Completer.custom_completers = sdisp |
|
1950 | self.Completer.custom_completers = sdisp | |
1951 |
|
1951 | |||
1952 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1952 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1953 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1953 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1954 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1954 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1955 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1955 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1956 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1956 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1957 |
|
1957 | |||
1958 | # Only configure readline if we truly are using readline. IPython can |
|
1958 | # Only configure readline if we truly are using readline. IPython can | |
1959 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1959 | # do tab-completion over the network, in GUIs, etc, where readline | |
1960 | # itself may be absent |
|
1960 | # itself may be absent | |
1961 | if self.has_readline: |
|
1961 | if self.has_readline: | |
1962 | self.set_readline_completer() |
|
1962 | self.set_readline_completer() | |
1963 |
|
1963 | |||
1964 | def complete(self, text, line=None, cursor_pos=None): |
|
1964 | def complete(self, text, line=None, cursor_pos=None): | |
1965 | """Return the completed text and a list of completions. |
|
1965 | """Return the completed text and a list of completions. | |
1966 |
|
1966 | |||
1967 | Parameters |
|
1967 | Parameters | |
1968 | ---------- |
|
1968 | ---------- | |
1969 |
|
1969 | |||
1970 | text : string |
|
1970 | text : string | |
1971 | A string of text to be completed on. It can be given as empty and |
|
1971 | A string of text to be completed on. It can be given as empty and | |
1972 | instead a line/position pair are given. In this case, the |
|
1972 | instead a line/position pair are given. In this case, the | |
1973 | completer itself will split the line like readline does. |
|
1973 | completer itself will split the line like readline does. | |
1974 |
|
1974 | |||
1975 | line : string, optional |
|
1975 | line : string, optional | |
1976 | The complete line that text is part of. |
|
1976 | The complete line that text is part of. | |
1977 |
|
1977 | |||
1978 | cursor_pos : int, optional |
|
1978 | cursor_pos : int, optional | |
1979 | The position of the cursor on the input line. |
|
1979 | The position of the cursor on the input line. | |
1980 |
|
1980 | |||
1981 | Returns |
|
1981 | Returns | |
1982 | ------- |
|
1982 | ------- | |
1983 | text : string |
|
1983 | text : string | |
1984 | The actual text that was completed. |
|
1984 | The actual text that was completed. | |
1985 |
|
1985 | |||
1986 | matches : list |
|
1986 | matches : list | |
1987 | A sorted list with all possible completions. |
|
1987 | A sorted list with all possible completions. | |
1988 |
|
1988 | |||
1989 | The optional arguments allow the completion to take more context into |
|
1989 | The optional arguments allow the completion to take more context into | |
1990 | account, and are part of the low-level completion API. |
|
1990 | account, and are part of the low-level completion API. | |
1991 |
|
1991 | |||
1992 | This is a wrapper around the completion mechanism, similar to what |
|
1992 | This is a wrapper around the completion mechanism, similar to what | |
1993 | readline does at the command line when the TAB key is hit. By |
|
1993 | readline does at the command line when the TAB key is hit. By | |
1994 | exposing it as a method, it can be used by other non-readline |
|
1994 | exposing it as a method, it can be used by other non-readline | |
1995 | environments (such as GUIs) for text completion. |
|
1995 | environments (such as GUIs) for text completion. | |
1996 |
|
1996 | |||
1997 | Simple usage example: |
|
1997 | Simple usage example: | |
1998 |
|
1998 | |||
1999 | In [1]: x = 'hello' |
|
1999 | In [1]: x = 'hello' | |
2000 |
|
2000 | |||
2001 | In [2]: _ip.complete('x.l') |
|
2001 | In [2]: _ip.complete('x.l') | |
2002 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2002 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
2003 | """ |
|
2003 | """ | |
2004 |
|
2004 | |||
2005 | # Inject names into __builtin__ so we can complete on the added names. |
|
2005 | # Inject names into __builtin__ so we can complete on the added names. | |
2006 | with self.builtin_trap: |
|
2006 | with self.builtin_trap: | |
2007 | return self.Completer.complete(text, line, cursor_pos) |
|
2007 | return self.Completer.complete(text, line, cursor_pos) | |
2008 |
|
2008 | |||
2009 | def set_custom_completer(self, completer, pos=0): |
|
2009 | def set_custom_completer(self, completer, pos=0): | |
2010 | """Adds a new custom completer function. |
|
2010 | """Adds a new custom completer function. | |
2011 |
|
2011 | |||
2012 | The position argument (defaults to 0) is the index in the completers |
|
2012 | The position argument (defaults to 0) is the index in the completers | |
2013 | list where you want the completer to be inserted.""" |
|
2013 | list where you want the completer to be inserted.""" | |
2014 |
|
2014 | |||
2015 | newcomp = types.MethodType(completer,self.Completer) |
|
2015 | newcomp = types.MethodType(completer,self.Completer) | |
2016 | self.Completer.matchers.insert(pos,newcomp) |
|
2016 | self.Completer.matchers.insert(pos,newcomp) | |
2017 |
|
2017 | |||
2018 | def set_readline_completer(self): |
|
2018 | def set_readline_completer(self): | |
2019 | """Reset readline's completer to be our own.""" |
|
2019 | """Reset readline's completer to be our own.""" | |
2020 | self.readline.set_completer(self.Completer.rlcomplete) |
|
2020 | self.readline.set_completer(self.Completer.rlcomplete) | |
2021 |
|
2021 | |||
2022 | def set_completer_frame(self, frame=None): |
|
2022 | def set_completer_frame(self, frame=None): | |
2023 | """Set the frame of the completer.""" |
|
2023 | """Set the frame of the completer.""" | |
2024 | if frame: |
|
2024 | if frame: | |
2025 | self.Completer.namespace = frame.f_locals |
|
2025 | self.Completer.namespace = frame.f_locals | |
2026 | self.Completer.global_namespace = frame.f_globals |
|
2026 | self.Completer.global_namespace = frame.f_globals | |
2027 | else: |
|
2027 | else: | |
2028 | self.Completer.namespace = self.user_ns |
|
2028 | self.Completer.namespace = self.user_ns | |
2029 | self.Completer.global_namespace = self.user_global_ns |
|
2029 | self.Completer.global_namespace = self.user_global_ns | |
2030 |
|
2030 | |||
2031 | #------------------------------------------------------------------------- |
|
2031 | #------------------------------------------------------------------------- | |
2032 | # Things related to magics |
|
2032 | # Things related to magics | |
2033 | #------------------------------------------------------------------------- |
|
2033 | #------------------------------------------------------------------------- | |
2034 |
|
2034 | |||
2035 | def init_magics(self): |
|
2035 | def init_magics(self): | |
2036 | from IPython.core import magics as m |
|
2036 | from IPython.core import magics as m | |
2037 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2037 | self.magics_manager = magic.MagicsManager(shell=self, | |
2038 | confg=self.config, |
|
2038 | confg=self.config, | |
2039 | user_magics=m.UserMagics(self)) |
|
2039 | user_magics=m.UserMagics(self)) | |
2040 | self.configurables.append(self.magics_manager) |
|
2040 | self.configurables.append(self.magics_manager) | |
2041 |
|
2041 | |||
2042 | # Expose as public API from the magics manager |
|
2042 | # Expose as public API from the magics manager | |
2043 | self.register_magics = self.magics_manager.register |
|
2043 | self.register_magics = self.magics_manager.register | |
2044 | self.register_magic_function = self.magics_manager.register_function |
|
2044 | self.register_magic_function = self.magics_manager.register_function | |
2045 | self.define_magic = self.magics_manager.define_magic |
|
2045 | self.define_magic = self.magics_manager.define_magic | |
2046 |
|
2046 | |||
2047 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2047 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
2048 | m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics, |
|
2048 | m.ConfigMagics, m.DeprecatedMagics, m.ExecutionMagics, | |
2049 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2049 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2050 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2050 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2051 | ) |
|
2051 | ) | |
2052 |
|
2052 | |||
2053 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2053 | # FIXME: Move the color initialization to the DisplayHook, which | |
2054 | # should be split into a prompt manager and displayhook. We probably |
|
2054 | # should be split into a prompt manager and displayhook. We probably | |
2055 | # even need a centralize colors management object. |
|
2055 | # even need a centralize colors management object. | |
2056 | self.magic('colors %s' % self.colors) |
|
2056 | self.magic('colors %s' % self.colors) | |
2057 |
|
2057 | |||
2058 | def run_line_magic(self, magic_name, line): |
|
2058 | def run_line_magic(self, magic_name, line): | |
2059 | """Execute the given line magic. |
|
2059 | """Execute the given line magic. | |
2060 |
|
2060 | |||
2061 | Parameters |
|
2061 | Parameters | |
2062 | ---------- |
|
2062 | ---------- | |
2063 | magic_name : str |
|
2063 | magic_name : str | |
2064 | Name of the desired magic function, without '%' prefix. |
|
2064 | Name of the desired magic function, without '%' prefix. | |
2065 |
|
2065 | |||
2066 | line : str |
|
2066 | line : str | |
2067 | The rest of the input line as a single string. |
|
2067 | The rest of the input line as a single string. | |
2068 | """ |
|
2068 | """ | |
2069 | fn = self.find_line_magic(magic_name) |
|
2069 | fn = self.find_line_magic(magic_name) | |
2070 | if fn is None: |
|
2070 | if fn is None: | |
2071 | cm = self.find_cell_magic(magic_name) |
|
2071 | cm = self.find_cell_magic(magic_name) | |
2072 | etpl = "Line magic function `%%%s` not found%s." |
|
2072 | etpl = "Line magic function `%%%s` not found%s." | |
2073 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2073 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2074 | 'did you mean that instead?)' % magic_name ) |
|
2074 | 'did you mean that instead?)' % magic_name ) | |
2075 | error(etpl % (magic_name, extra)) |
|
2075 | error(etpl % (magic_name, extra)) | |
2076 | else: |
|
2076 | else: | |
2077 | # Note: this is the distance in the stack to the user's frame. |
|
2077 | # Note: this is the distance in the stack to the user's frame. | |
2078 | # This will need to be updated if the internal calling logic gets |
|
2078 | # This will need to be updated if the internal calling logic gets | |
2079 | # refactored, or else we'll be expanding the wrong variables. |
|
2079 | # refactored, or else we'll be expanding the wrong variables. | |
2080 | stack_depth = 2 |
|
2080 | stack_depth = 2 | |
2081 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2081 | magic_arg_s = self.var_expand(line, stack_depth) | |
2082 | # Put magic args in a list so we can call with f(*a) syntax |
|
2082 | # Put magic args in a list so we can call with f(*a) syntax | |
2083 | args = [magic_arg_s] |
|
2083 | args = [magic_arg_s] | |
2084 | # Grab local namespace if we need it: |
|
2084 | # Grab local namespace if we need it: | |
2085 | if getattr(fn, "needs_local_scope", False): |
|
2085 | if getattr(fn, "needs_local_scope", False): | |
2086 | args.append(sys._getframe(stack_depth).f_locals) |
|
2086 | args.append(sys._getframe(stack_depth).f_locals) | |
2087 | with self.builtin_trap: |
|
2087 | with self.builtin_trap: | |
2088 | result = fn(*args) |
|
2088 | result = fn(*args) | |
2089 | return result |
|
2089 | return result | |
2090 |
|
2090 | |||
2091 | def run_cell_magic(self, magic_name, line, cell): |
|
2091 | def run_cell_magic(self, magic_name, line, cell): | |
2092 | """Execute the given cell magic. |
|
2092 | """Execute the given cell magic. | |
2093 |
|
2093 | |||
2094 | Parameters |
|
2094 | Parameters | |
2095 | ---------- |
|
2095 | ---------- | |
2096 | magic_name : str |
|
2096 | magic_name : str | |
2097 | Name of the desired magic function, without '%' prefix. |
|
2097 | Name of the desired magic function, without '%' prefix. | |
2098 |
|
2098 | |||
2099 | line : str |
|
2099 | line : str | |
2100 | The rest of the first input line as a single string. |
|
2100 | The rest of the first input line as a single string. | |
2101 |
|
2101 | |||
2102 | cell : str |
|
2102 | cell : str | |
2103 | The body of the cell as a (possibly multiline) string. |
|
2103 | The body of the cell as a (possibly multiline) string. | |
2104 | """ |
|
2104 | """ | |
2105 | fn = self.find_cell_magic(magic_name) |
|
2105 | fn = self.find_cell_magic(magic_name) | |
2106 | if fn is None: |
|
2106 | if fn is None: | |
2107 | lm = self.find_line_magic(magic_name) |
|
2107 | lm = self.find_line_magic(magic_name) | |
2108 | etpl = "Cell magic function `%%%%%s` not found%s." |
|
2108 | etpl = "Cell magic function `%%%%%s` not found%s." | |
2109 | extra = '' if lm is None else (' (But line magic `%%%s` exists, ' |
|
2109 | extra = '' if lm is None else (' (But line magic `%%%s` exists, ' | |
2110 | 'did you mean that instead?)' % magic_name ) |
|
2110 | 'did you mean that instead?)' % magic_name ) | |
2111 | error(etpl % (magic_name, extra)) |
|
2111 | error(etpl % (magic_name, extra)) | |
2112 | else: |
|
2112 | else: | |
2113 | # Note: this is the distance in the stack to the user's frame. |
|
2113 | # Note: this is the distance in the stack to the user's frame. | |
2114 | # This will need to be updated if the internal calling logic gets |
|
2114 | # This will need to be updated if the internal calling logic gets | |
2115 | # refactored, or else we'll be expanding the wrong variables. |
|
2115 | # refactored, or else we'll be expanding the wrong variables. | |
2116 | stack_depth = 2 |
|
2116 | stack_depth = 2 | |
2117 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2117 | magic_arg_s = self.var_expand(line, stack_depth) | |
2118 | with self.builtin_trap: |
|
2118 | with self.builtin_trap: | |
2119 | result = fn(line, cell) |
|
2119 | result = fn(line, cell) | |
2120 | return result |
|
2120 | return result | |
2121 |
|
2121 | |||
2122 | def find_line_magic(self, magic_name): |
|
2122 | def find_line_magic(self, magic_name): | |
2123 | """Find and return a line magic by name. |
|
2123 | """Find and return a line magic by name. | |
2124 |
|
2124 | |||
2125 | Returns None if the magic isn't found.""" |
|
2125 | Returns None if the magic isn't found.""" | |
2126 | return self.magics_manager.magics['line'].get(magic_name) |
|
2126 | return self.magics_manager.magics['line'].get(magic_name) | |
2127 |
|
2127 | |||
2128 | def find_cell_magic(self, magic_name): |
|
2128 | def find_cell_magic(self, magic_name): | |
2129 | """Find and return a cell magic by name. |
|
2129 | """Find and return a cell magic by name. | |
2130 |
|
2130 | |||
2131 | Returns None if the magic isn't found.""" |
|
2131 | Returns None if the magic isn't found.""" | |
2132 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2132 | return self.magics_manager.magics['cell'].get(magic_name) | |
2133 |
|
2133 | |||
2134 | def find_magic(self, magic_name, magic_kind='line'): |
|
2134 | def find_magic(self, magic_name, magic_kind='line'): | |
2135 | """Find and return a magic of the given type by name. |
|
2135 | """Find and return a magic of the given type by name. | |
2136 |
|
2136 | |||
2137 | Returns None if the magic isn't found.""" |
|
2137 | Returns None if the magic isn't found.""" | |
2138 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2138 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2139 |
|
2139 | |||
2140 | def magic(self, arg_s): |
|
2140 | def magic(self, arg_s): | |
2141 | """DEPRECATED. Use run_line_magic() instead. |
|
2141 | """DEPRECATED. Use run_line_magic() instead. | |
2142 |
|
2142 | |||
2143 | Call a magic function by name. |
|
2143 | Call a magic function by name. | |
2144 |
|
2144 | |||
2145 | Input: a string containing the name of the magic function to call and |
|
2145 | Input: a string containing the name of the magic function to call and | |
2146 | any additional arguments to be passed to the magic. |
|
2146 | any additional arguments to be passed to the magic. | |
2147 |
|
2147 | |||
2148 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2148 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2149 | prompt: |
|
2149 | prompt: | |
2150 |
|
2150 | |||
2151 | In[1]: %name -opt foo bar |
|
2151 | In[1]: %name -opt foo bar | |
2152 |
|
2152 | |||
2153 | To call a magic without arguments, simply use magic('name'). |
|
2153 | To call a magic without arguments, simply use magic('name'). | |
2154 |
|
2154 | |||
2155 | This provides a proper Python function to call IPython's magics in any |
|
2155 | This provides a proper Python function to call IPython's magics in any | |
2156 | valid Python code you can type at the interpreter, including loops and |
|
2156 | valid Python code you can type at the interpreter, including loops and | |
2157 | compound statements. |
|
2157 | compound statements. | |
2158 | """ |
|
2158 | """ | |
2159 | # TODO: should we issue a loud deprecation warning here? |
|
2159 | # TODO: should we issue a loud deprecation warning here? | |
2160 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2160 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2161 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2161 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2162 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2162 | return self.run_line_magic(magic_name, magic_arg_s) | |
2163 |
|
2163 | |||
2164 | #------------------------------------------------------------------------- |
|
2164 | #------------------------------------------------------------------------- | |
2165 | # Things related to macros |
|
2165 | # Things related to macros | |
2166 | #------------------------------------------------------------------------- |
|
2166 | #------------------------------------------------------------------------- | |
2167 |
|
2167 | |||
2168 | def define_macro(self, name, themacro): |
|
2168 | def define_macro(self, name, themacro): | |
2169 | """Define a new macro |
|
2169 | """Define a new macro | |
2170 |
|
2170 | |||
2171 | Parameters |
|
2171 | Parameters | |
2172 | ---------- |
|
2172 | ---------- | |
2173 | name : str |
|
2173 | name : str | |
2174 | The name of the macro. |
|
2174 | The name of the macro. | |
2175 | themacro : str or Macro |
|
2175 | themacro : str or Macro | |
2176 | The action to do upon invoking the macro. If a string, a new |
|
2176 | The action to do upon invoking the macro. If a string, a new | |
2177 | Macro object is created by passing the string to it. |
|
2177 | Macro object is created by passing the string to it. | |
2178 | """ |
|
2178 | """ | |
2179 |
|
2179 | |||
2180 | from IPython.core import macro |
|
2180 | from IPython.core import macro | |
2181 |
|
2181 | |||
2182 | if isinstance(themacro, basestring): |
|
2182 | if isinstance(themacro, basestring): | |
2183 | themacro = macro.Macro(themacro) |
|
2183 | themacro = macro.Macro(themacro) | |
2184 | if not isinstance(themacro, macro.Macro): |
|
2184 | if not isinstance(themacro, macro.Macro): | |
2185 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2185 | raise ValueError('A macro must be a string or a Macro instance.') | |
2186 | self.user_ns[name] = themacro |
|
2186 | self.user_ns[name] = themacro | |
2187 |
|
2187 | |||
2188 | #------------------------------------------------------------------------- |
|
2188 | #------------------------------------------------------------------------- | |
2189 | # Things related to the running of system commands |
|
2189 | # Things related to the running of system commands | |
2190 | #------------------------------------------------------------------------- |
|
2190 | #------------------------------------------------------------------------- | |
2191 |
|
2191 | |||
2192 | def system_piped(self, cmd): |
|
2192 | def system_piped(self, cmd): | |
2193 | """Call the given cmd in a subprocess, piping stdout/err |
|
2193 | """Call the given cmd in a subprocess, piping stdout/err | |
2194 |
|
2194 | |||
2195 | Parameters |
|
2195 | Parameters | |
2196 | ---------- |
|
2196 | ---------- | |
2197 | cmd : str |
|
2197 | cmd : str | |
2198 | Command to execute (can not end in '&', as background processes are |
|
2198 | Command to execute (can not end in '&', as background processes are | |
2199 | not supported. Should not be a command that expects input |
|
2199 | not supported. Should not be a command that expects input | |
2200 | other than simple text. |
|
2200 | other than simple text. | |
2201 | """ |
|
2201 | """ | |
2202 | if cmd.rstrip().endswith('&'): |
|
2202 | if cmd.rstrip().endswith('&'): | |
2203 | # this is *far* from a rigorous test |
|
2203 | # this is *far* from a rigorous test | |
2204 | # We do not support backgrounding processes because we either use |
|
2204 | # We do not support backgrounding processes because we either use | |
2205 | # pexpect or pipes to read from. Users can always just call |
|
2205 | # pexpect or pipes to read from. Users can always just call | |
2206 | # os.system() or use ip.system=ip.system_raw |
|
2206 | # os.system() or use ip.system=ip.system_raw | |
2207 | # if they really want a background process. |
|
2207 | # if they really want a background process. | |
2208 | raise OSError("Background processes not supported.") |
|
2208 | raise OSError("Background processes not supported.") | |
2209 |
|
2209 | |||
2210 | # we explicitly do NOT return the subprocess status code, because |
|
2210 | # we explicitly do NOT return the subprocess status code, because | |
2211 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2211 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2212 | # Instead, we store the exit_code in user_ns. |
|
2212 | # Instead, we store the exit_code in user_ns. | |
2213 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2213 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2214 |
|
2214 | |||
2215 | def system_raw(self, cmd): |
|
2215 | def system_raw(self, cmd): | |
2216 | """Call the given cmd in a subprocess using os.system |
|
2216 | """Call the given cmd in a subprocess using os.system | |
2217 |
|
2217 | |||
2218 | Parameters |
|
2218 | Parameters | |
2219 | ---------- |
|
2219 | ---------- | |
2220 | cmd : str |
|
2220 | cmd : str | |
2221 | Command to execute. |
|
2221 | Command to execute. | |
2222 | """ |
|
2222 | """ | |
2223 | cmd = self.var_expand(cmd, depth=1) |
|
2223 | cmd = self.var_expand(cmd, depth=1) | |
2224 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2224 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2225 | if sys.platform == 'win32': |
|
2225 | if sys.platform == 'win32': | |
2226 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2226 | from IPython.utils._process_win32 import AvoidUNCPath | |
2227 | with AvoidUNCPath() as path: |
|
2227 | with AvoidUNCPath() as path: | |
2228 | if path is not None: |
|
2228 | if path is not None: | |
2229 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2229 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2230 | cmd = py3compat.unicode_to_str(cmd) |
|
2230 | cmd = py3compat.unicode_to_str(cmd) | |
2231 | ec = os.system(cmd) |
|
2231 | ec = os.system(cmd) | |
2232 | else: |
|
2232 | else: | |
2233 | cmd = py3compat.unicode_to_str(cmd) |
|
2233 | cmd = py3compat.unicode_to_str(cmd) | |
2234 | ec = os.system(cmd) |
|
2234 | ec = os.system(cmd) | |
2235 |
|
2235 | |||
2236 | # We explicitly do NOT return the subprocess status code, because |
|
2236 | # We explicitly do NOT return the subprocess status code, because | |
2237 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2237 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2238 | # Instead, we store the exit_code in user_ns. |
|
2238 | # Instead, we store the exit_code in user_ns. | |
2239 | self.user_ns['_exit_code'] = ec |
|
2239 | self.user_ns['_exit_code'] = ec | |
2240 |
|
2240 | |||
2241 | # use piped system by default, because it is better behaved |
|
2241 | # use piped system by default, because it is better behaved | |
2242 | system = system_piped |
|
2242 | system = system_piped | |
2243 |
|
2243 | |||
2244 | def getoutput(self, cmd, split=True, depth=0): |
|
2244 | def getoutput(self, cmd, split=True, depth=0): | |
2245 | """Get output (possibly including stderr) from a subprocess. |
|
2245 | """Get output (possibly including stderr) from a subprocess. | |
2246 |
|
2246 | |||
2247 | Parameters |
|
2247 | Parameters | |
2248 | ---------- |
|
2248 | ---------- | |
2249 | cmd : str |
|
2249 | cmd : str | |
2250 | Command to execute (can not end in '&', as background processes are |
|
2250 | Command to execute (can not end in '&', as background processes are | |
2251 | not supported. |
|
2251 | not supported. | |
2252 | split : bool, optional |
|
2252 | split : bool, optional | |
2253 | If True, split the output into an IPython SList. Otherwise, an |
|
2253 | If True, split the output into an IPython SList. Otherwise, an | |
2254 | IPython LSString is returned. These are objects similar to normal |
|
2254 | IPython LSString is returned. These are objects similar to normal | |
2255 | lists and strings, with a few convenience attributes for easier |
|
2255 | lists and strings, with a few convenience attributes for easier | |
2256 | manipulation of line-based output. You can use '?' on them for |
|
2256 | manipulation of line-based output. You can use '?' on them for | |
2257 | details. |
|
2257 | details. | |
2258 | depth : int, optional |
|
2258 | depth : int, optional | |
2259 | How many frames above the caller are the local variables which should |
|
2259 | How many frames above the caller are the local variables which should | |
2260 | be expanded in the command string? The default (0) assumes that the |
|
2260 | be expanded in the command string? The default (0) assumes that the | |
2261 | expansion variables are in the stack frame calling this function. |
|
2261 | expansion variables are in the stack frame calling this function. | |
2262 | """ |
|
2262 | """ | |
2263 | if cmd.rstrip().endswith('&'): |
|
2263 | if cmd.rstrip().endswith('&'): | |
2264 | # this is *far* from a rigorous test |
|
2264 | # this is *far* from a rigorous test | |
2265 | raise OSError("Background processes not supported.") |
|
2265 | raise OSError("Background processes not supported.") | |
2266 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2266 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2267 | if split: |
|
2267 | if split: | |
2268 | out = SList(out.splitlines()) |
|
2268 | out = SList(out.splitlines()) | |
2269 | else: |
|
2269 | else: | |
2270 | out = LSString(out) |
|
2270 | out = LSString(out) | |
2271 | return out |
|
2271 | return out | |
2272 |
|
2272 | |||
2273 | #------------------------------------------------------------------------- |
|
2273 | #------------------------------------------------------------------------- | |
2274 | # Things related to aliases |
|
2274 | # Things related to aliases | |
2275 | #------------------------------------------------------------------------- |
|
2275 | #------------------------------------------------------------------------- | |
2276 |
|
2276 | |||
2277 | def init_alias(self): |
|
2277 | def init_alias(self): | |
2278 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
2278 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
2279 | self.configurables.append(self.alias_manager) |
|
2279 | self.configurables.append(self.alias_manager) | |
2280 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
2280 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
2281 |
|
2281 | |||
2282 | #------------------------------------------------------------------------- |
|
2282 | #------------------------------------------------------------------------- | |
2283 | # Things related to extensions and plugins |
|
2283 | # Things related to extensions and plugins | |
2284 | #------------------------------------------------------------------------- |
|
2284 | #------------------------------------------------------------------------- | |
2285 |
|
2285 | |||
2286 | def init_extension_manager(self): |
|
2286 | def init_extension_manager(self): | |
2287 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
2287 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
2288 | self.configurables.append(self.extension_manager) |
|
2288 | self.configurables.append(self.extension_manager) | |
2289 |
|
2289 | |||
2290 | def init_plugin_manager(self): |
|
2290 | def init_plugin_manager(self): | |
2291 | self.plugin_manager = PluginManager(config=self.config) |
|
2291 | self.plugin_manager = PluginManager(config=self.config) | |
2292 | self.configurables.append(self.plugin_manager) |
|
2292 | self.configurables.append(self.plugin_manager) | |
2293 |
|
2293 | |||
2294 |
|
2294 | |||
2295 | #------------------------------------------------------------------------- |
|
2295 | #------------------------------------------------------------------------- | |
2296 | # Things related to payloads |
|
2296 | # Things related to payloads | |
2297 | #------------------------------------------------------------------------- |
|
2297 | #------------------------------------------------------------------------- | |
2298 |
|
2298 | |||
2299 | def init_payload(self): |
|
2299 | def init_payload(self): | |
2300 | self.payload_manager = PayloadManager(config=self.config) |
|
2300 | self.payload_manager = PayloadManager(config=self.config) | |
2301 | self.configurables.append(self.payload_manager) |
|
2301 | self.configurables.append(self.payload_manager) | |
2302 |
|
2302 | |||
2303 | #------------------------------------------------------------------------- |
|
2303 | #------------------------------------------------------------------------- | |
2304 | # Things related to the prefilter |
|
2304 | # Things related to the prefilter | |
2305 | #------------------------------------------------------------------------- |
|
2305 | #------------------------------------------------------------------------- | |
2306 |
|
2306 | |||
2307 | def init_prefilter(self): |
|
2307 | def init_prefilter(self): | |
2308 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
2308 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
2309 | self.configurables.append(self.prefilter_manager) |
|
2309 | self.configurables.append(self.prefilter_manager) | |
2310 | # Ultimately this will be refactored in the new interpreter code, but |
|
2310 | # Ultimately this will be refactored in the new interpreter code, but | |
2311 | # for now, we should expose the main prefilter method (there's legacy |
|
2311 | # for now, we should expose the main prefilter method (there's legacy | |
2312 | # code out there that may rely on this). |
|
2312 | # code out there that may rely on this). | |
2313 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2313 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2314 |
|
2314 | |||
2315 | def auto_rewrite_input(self, cmd): |
|
2315 | def auto_rewrite_input(self, cmd): | |
2316 | """Print to the screen the rewritten form of the user's command. |
|
2316 | """Print to the screen the rewritten form of the user's command. | |
2317 |
|
2317 | |||
2318 | This shows visual feedback by rewriting input lines that cause |
|
2318 | This shows visual feedback by rewriting input lines that cause | |
2319 | automatic calling to kick in, like:: |
|
2319 | automatic calling to kick in, like:: | |
2320 |
|
2320 | |||
2321 | /f x |
|
2321 | /f x | |
2322 |
|
2322 | |||
2323 | into:: |
|
2323 | into:: | |
2324 |
|
2324 | |||
2325 | ------> f(x) |
|
2325 | ------> f(x) | |
2326 |
|
2326 | |||
2327 | after the user's input prompt. This helps the user understand that the |
|
2327 | after the user's input prompt. This helps the user understand that the | |
2328 | input line was transformed automatically by IPython. |
|
2328 | input line was transformed automatically by IPython. | |
2329 | """ |
|
2329 | """ | |
2330 | if not self.show_rewritten_input: |
|
2330 | if not self.show_rewritten_input: | |
2331 | return |
|
2331 | return | |
2332 |
|
2332 | |||
2333 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2333 | rw = self.prompt_manager.render('rewrite') + cmd | |
2334 |
|
2334 | |||
2335 | try: |
|
2335 | try: | |
2336 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2336 | # plain ascii works better w/ pyreadline, on some machines, so | |
2337 | # we use it and only print uncolored rewrite if we have unicode |
|
2337 | # we use it and only print uncolored rewrite if we have unicode | |
2338 | rw = str(rw) |
|
2338 | rw = str(rw) | |
2339 | print(rw, file=io.stdout) |
|
2339 | print(rw, file=io.stdout) | |
2340 | except UnicodeEncodeError: |
|
2340 | except UnicodeEncodeError: | |
2341 | print("------> " + cmd) |
|
2341 | print("------> " + cmd) | |
2342 |
|
2342 | |||
2343 | #------------------------------------------------------------------------- |
|
2343 | #------------------------------------------------------------------------- | |
2344 | # Things related to extracting values/expressions from kernel and user_ns |
|
2344 | # Things related to extracting values/expressions from kernel and user_ns | |
2345 | #------------------------------------------------------------------------- |
|
2345 | #------------------------------------------------------------------------- | |
2346 |
|
2346 | |||
2347 | def _simple_error(self): |
|
2347 | def _simple_error(self): | |
2348 | etype, value = sys.exc_info()[:2] |
|
2348 | etype, value = sys.exc_info()[:2] | |
2349 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
2349 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
2350 |
|
2350 | |||
2351 | def user_variables(self, names): |
|
2351 | def user_variables(self, names): | |
2352 | """Get a list of variable names from the user's namespace. |
|
2352 | """Get a list of variable names from the user's namespace. | |
2353 |
|
2353 | |||
2354 | Parameters |
|
2354 | Parameters | |
2355 | ---------- |
|
2355 | ---------- | |
2356 | names : list of strings |
|
2356 | names : list of strings | |
2357 | A list of names of variables to be read from the user namespace. |
|
2357 | A list of names of variables to be read from the user namespace. | |
2358 |
|
2358 | |||
2359 | Returns |
|
2359 | Returns | |
2360 | ------- |
|
2360 | ------- | |
2361 | A dict, keyed by the input names and with the repr() of each value. |
|
2361 | A dict, keyed by the input names and with the repr() of each value. | |
2362 | """ |
|
2362 | """ | |
2363 | out = {} |
|
2363 | out = {} | |
2364 | user_ns = self.user_ns |
|
2364 | user_ns = self.user_ns | |
2365 | for varname in names: |
|
2365 | for varname in names: | |
2366 | try: |
|
2366 | try: | |
2367 | value = repr(user_ns[varname]) |
|
2367 | value = repr(user_ns[varname]) | |
2368 | except: |
|
2368 | except: | |
2369 | value = self._simple_error() |
|
2369 | value = self._simple_error() | |
2370 | out[varname] = value |
|
2370 | out[varname] = value | |
2371 | return out |
|
2371 | return out | |
2372 |
|
2372 | |||
2373 | def user_expressions(self, expressions): |
|
2373 | def user_expressions(self, expressions): | |
2374 | """Evaluate a dict of expressions in the user's namespace. |
|
2374 | """Evaluate a dict of expressions in the user's namespace. | |
2375 |
|
2375 | |||
2376 | Parameters |
|
2376 | Parameters | |
2377 | ---------- |
|
2377 | ---------- | |
2378 | expressions : dict |
|
2378 | expressions : dict | |
2379 | A dict with string keys and string values. The expression values |
|
2379 | A dict with string keys and string values. The expression values | |
2380 | should be valid Python expressions, each of which will be evaluated |
|
2380 | should be valid Python expressions, each of which will be evaluated | |
2381 | in the user namespace. |
|
2381 | in the user namespace. | |
2382 |
|
2382 | |||
2383 | Returns |
|
2383 | Returns | |
2384 | ------- |
|
2384 | ------- | |
2385 | A dict, keyed like the input expressions dict, with the repr() of each |
|
2385 | A dict, keyed like the input expressions dict, with the repr() of each | |
2386 | value. |
|
2386 | value. | |
2387 | """ |
|
2387 | """ | |
2388 | out = {} |
|
2388 | out = {} | |
2389 | user_ns = self.user_ns |
|
2389 | user_ns = self.user_ns | |
2390 | global_ns = self.user_global_ns |
|
2390 | global_ns = self.user_global_ns | |
2391 | for key, expr in expressions.iteritems(): |
|
2391 | for key, expr in expressions.iteritems(): | |
2392 | try: |
|
2392 | try: | |
2393 | value = repr(eval(expr, global_ns, user_ns)) |
|
2393 | value = repr(eval(expr, global_ns, user_ns)) | |
2394 | except: |
|
2394 | except: | |
2395 | value = self._simple_error() |
|
2395 | value = self._simple_error() | |
2396 | out[key] = value |
|
2396 | out[key] = value | |
2397 | return out |
|
2397 | return out | |
2398 |
|
2398 | |||
2399 | #------------------------------------------------------------------------- |
|
2399 | #------------------------------------------------------------------------- | |
2400 | # Things related to the running of code |
|
2400 | # Things related to the running of code | |
2401 | #------------------------------------------------------------------------- |
|
2401 | #------------------------------------------------------------------------- | |
2402 |
|
2402 | |||
2403 | def ex(self, cmd): |
|
2403 | def ex(self, cmd): | |
2404 | """Execute a normal python statement in user namespace.""" |
|
2404 | """Execute a normal python statement in user namespace.""" | |
2405 | with self.builtin_trap: |
|
2405 | with self.builtin_trap: | |
2406 | exec cmd in self.user_global_ns, self.user_ns |
|
2406 | exec cmd in self.user_global_ns, self.user_ns | |
2407 |
|
2407 | |||
2408 | def ev(self, expr): |
|
2408 | def ev(self, expr): | |
2409 | """Evaluate python expression expr in user namespace. |
|
2409 | """Evaluate python expression expr in user namespace. | |
2410 |
|
2410 | |||
2411 | Returns the result of evaluation |
|
2411 | Returns the result of evaluation | |
2412 | """ |
|
2412 | """ | |
2413 | with self.builtin_trap: |
|
2413 | with self.builtin_trap: | |
2414 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2414 | return eval(expr, self.user_global_ns, self.user_ns) | |
2415 |
|
2415 | |||
2416 | def safe_execfile(self, fname, *where, **kw): |
|
2416 | def safe_execfile(self, fname, *where, **kw): | |
2417 | """A safe version of the builtin execfile(). |
|
2417 | """A safe version of the builtin execfile(). | |
2418 |
|
2418 | |||
2419 | This version will never throw an exception, but instead print |
|
2419 | This version will never throw an exception, but instead print | |
2420 | helpful error messages to the screen. This only works on pure |
|
2420 | helpful error messages to the screen. This only works on pure | |
2421 | Python files with the .py extension. |
|
2421 | Python files with the .py extension. | |
2422 |
|
2422 | |||
2423 | Parameters |
|
2423 | Parameters | |
2424 | ---------- |
|
2424 | ---------- | |
2425 | fname : string |
|
2425 | fname : string | |
2426 | The name of the file to be executed. |
|
2426 | The name of the file to be executed. | |
2427 | where : tuple |
|
2427 | where : tuple | |
2428 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2428 | One or two namespaces, passed to execfile() as (globals,locals). | |
2429 | If only one is given, it is passed as both. |
|
2429 | If only one is given, it is passed as both. | |
2430 | exit_ignore : bool (False) |
|
2430 | exit_ignore : bool (False) | |
2431 | If True, then silence SystemExit for non-zero status (it is always |
|
2431 | If True, then silence SystemExit for non-zero status (it is always | |
2432 | silenced for zero status, as it is so common). |
|
2432 | silenced for zero status, as it is so common). | |
2433 | raise_exceptions : bool (False) |
|
2433 | raise_exceptions : bool (False) | |
2434 | If True raise exceptions everywhere. Meant for testing. |
|
2434 | If True raise exceptions everywhere. Meant for testing. | |
2435 |
|
2435 | |||
2436 | """ |
|
2436 | """ | |
2437 | kw.setdefault('exit_ignore', False) |
|
2437 | kw.setdefault('exit_ignore', False) | |
2438 | kw.setdefault('raise_exceptions', False) |
|
2438 | kw.setdefault('raise_exceptions', False) | |
2439 |
|
2439 | |||
2440 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2440 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2441 |
|
2441 | |||
2442 | # Make sure we can open the file |
|
2442 | # Make sure we can open the file | |
2443 | try: |
|
2443 | try: | |
2444 | with open(fname) as thefile: |
|
2444 | with open(fname) as thefile: | |
2445 | pass |
|
2445 | pass | |
2446 | except: |
|
2446 | except: | |
2447 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2447 | warn('Could not open file <%s> for safe execution.' % fname) | |
2448 | return |
|
2448 | return | |
2449 |
|
2449 | |||
2450 | # Find things also in current directory. This is needed to mimic the |
|
2450 | # Find things also in current directory. This is needed to mimic the | |
2451 | # behavior of running a script from the system command line, where |
|
2451 | # behavior of running a script from the system command line, where | |
2452 | # Python inserts the script's directory into sys.path |
|
2452 | # Python inserts the script's directory into sys.path | |
2453 | dname = os.path.dirname(fname) |
|
2453 | dname = os.path.dirname(fname) | |
2454 |
|
2454 | |||
2455 | with prepended_to_syspath(dname): |
|
2455 | with prepended_to_syspath(dname): | |
2456 | try: |
|
2456 | try: | |
2457 | py3compat.execfile(fname,*where) |
|
2457 | py3compat.execfile(fname,*where) | |
2458 | except SystemExit as status: |
|
2458 | except SystemExit as status: | |
2459 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2459 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2460 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2460 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2461 | # these are considered normal by the OS: |
|
2461 | # these are considered normal by the OS: | |
2462 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2462 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2463 | # 0 |
|
2463 | # 0 | |
2464 | # > python -c'import sys;sys.exit()'; echo $? |
|
2464 | # > python -c'import sys;sys.exit()'; echo $? | |
2465 | # 0 |
|
2465 | # 0 | |
2466 | # For other exit status, we show the exception unless |
|
2466 | # For other exit status, we show the exception unless | |
2467 | # explicitly silenced, but only in short form. |
|
2467 | # explicitly silenced, but only in short form. | |
2468 | if kw['raise_exceptions']: |
|
2468 | if kw['raise_exceptions']: | |
2469 | raise |
|
2469 | raise | |
2470 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2470 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2471 | self.showtraceback(exception_only=True) |
|
2471 | self.showtraceback(exception_only=True) | |
2472 | except: |
|
2472 | except: | |
2473 | if kw['raise_exceptions']: |
|
2473 | if kw['raise_exceptions']: | |
2474 | raise |
|
2474 | raise | |
2475 | self.showtraceback() |
|
2475 | self.showtraceback() | |
2476 |
|
2476 | |||
2477 | def safe_execfile_ipy(self, fname): |
|
2477 | def safe_execfile_ipy(self, fname): | |
2478 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2478 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2479 |
|
2479 | |||
2480 | Parameters |
|
2480 | Parameters | |
2481 | ---------- |
|
2481 | ---------- | |
2482 | fname : str |
|
2482 | fname : str | |
2483 | The name of the file to execute. The filename must have a |
|
2483 | The name of the file to execute. The filename must have a | |
2484 | .ipy extension. |
|
2484 | .ipy extension. | |
2485 | """ |
|
2485 | """ | |
2486 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2486 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2487 |
|
2487 | |||
2488 | # Make sure we can open the file |
|
2488 | # Make sure we can open the file | |
2489 | try: |
|
2489 | try: | |
2490 | with open(fname) as thefile: |
|
2490 | with open(fname) as thefile: | |
2491 | pass |
|
2491 | pass | |
2492 | except: |
|
2492 | except: | |
2493 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2493 | warn('Could not open file <%s> for safe execution.' % fname) | |
2494 | return |
|
2494 | return | |
2495 |
|
2495 | |||
2496 | # Find things also in current directory. This is needed to mimic the |
|
2496 | # Find things also in current directory. This is needed to mimic the | |
2497 | # behavior of running a script from the system command line, where |
|
2497 | # behavior of running a script from the system command line, where | |
2498 | # Python inserts the script's directory into sys.path |
|
2498 | # Python inserts the script's directory into sys.path | |
2499 | dname = os.path.dirname(fname) |
|
2499 | dname = os.path.dirname(fname) | |
2500 |
|
2500 | |||
2501 | with prepended_to_syspath(dname): |
|
2501 | with prepended_to_syspath(dname): | |
2502 | try: |
|
2502 | try: | |
2503 | with open(fname) as thefile: |
|
2503 | with open(fname) as thefile: | |
2504 | # self.run_cell currently captures all exceptions |
|
2504 | # self.run_cell currently captures all exceptions | |
2505 | # raised in user code. It would be nice if there were |
|
2505 | # raised in user code. It would be nice if there were | |
2506 | # versions of runlines, execfile that did raise, so |
|
2506 | # versions of runlines, execfile that did raise, so | |
2507 | # we could catch the errors. |
|
2507 | # we could catch the errors. | |
2508 | self.run_cell(thefile.read(), store_history=False) |
|
2508 | self.run_cell(thefile.read(), store_history=False) | |
2509 | except: |
|
2509 | except: | |
2510 | self.showtraceback() |
|
2510 | self.showtraceback() | |
2511 | warn('Unknown failure executing file: <%s>' % fname) |
|
2511 | warn('Unknown failure executing file: <%s>' % fname) | |
2512 |
|
2512 | |||
2513 | def safe_run_module(self, mod_name, where): |
|
2513 | def safe_run_module(self, mod_name, where): | |
2514 | """A safe version of runpy.run_module(). |
|
2514 | """A safe version of runpy.run_module(). | |
2515 |
|
2515 | |||
2516 | This version will never throw an exception, but instead print |
|
2516 | This version will never throw an exception, but instead print | |
2517 | helpful error messages to the screen. |
|
2517 | helpful error messages to the screen. | |
2518 |
|
2518 | |||
2519 | Parameters |
|
2519 | Parameters | |
2520 | ---------- |
|
2520 | ---------- | |
2521 | mod_name : string |
|
2521 | mod_name : string | |
2522 | The name of the module to be executed. |
|
2522 | The name of the module to be executed. | |
2523 | where : dict |
|
2523 | where : dict | |
2524 | The globals namespace. |
|
2524 | The globals namespace. | |
2525 | """ |
|
2525 | """ | |
2526 | try: |
|
2526 | try: | |
2527 | where.update( |
|
2527 | where.update( | |
2528 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2528 | runpy.run_module(str(mod_name), run_name="__main__", | |
2529 | alter_sys=True) |
|
2529 | alter_sys=True) | |
2530 | ) |
|
2530 | ) | |
2531 | except: |
|
2531 | except: | |
2532 | self.showtraceback() |
|
2532 | self.showtraceback() | |
2533 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2533 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2534 |
|
2534 | |||
2535 | def _run_cached_cell_magic(self, magic_name, line): |
|
2535 | def _run_cached_cell_magic(self, magic_name, line): | |
2536 | """Special method to call a cell magic with the data stored in self. |
|
2536 | """Special method to call a cell magic with the data stored in self. | |
2537 | """ |
|
2537 | """ | |
2538 | cell = self._current_cell_magic_body |
|
2538 | cell = self._current_cell_magic_body | |
2539 | self._current_cell_magic_body = None |
|
2539 | self._current_cell_magic_body = None | |
2540 | return self.run_cell_magic(magic_name, line, cell) |
|
2540 | return self.run_cell_magic(magic_name, line, cell) | |
2541 |
|
2541 | |||
2542 | def run_cell(self, raw_cell, store_history=False, silent=False): |
|
2542 | def run_cell(self, raw_cell, store_history=False, silent=False): | |
2543 | """Run a complete IPython cell. |
|
2543 | """Run a complete IPython cell. | |
2544 |
|
2544 | |||
2545 | Parameters |
|
2545 | Parameters | |
2546 | ---------- |
|
2546 | ---------- | |
2547 | raw_cell : str |
|
2547 | raw_cell : str | |
2548 | The code (including IPython code such as %magic functions) to run. |
|
2548 | The code (including IPython code such as %magic functions) to run. | |
2549 | store_history : bool |
|
2549 | store_history : bool | |
2550 | If True, the raw and translated cell will be stored in IPython's |
|
2550 | If True, the raw and translated cell will be stored in IPython's | |
2551 | history. For user code calling back into IPython's machinery, this |
|
2551 | history. For user code calling back into IPython's machinery, this | |
2552 | should be set to False. |
|
2552 | should be set to False. | |
2553 | silent : bool |
|
2553 | silent : bool | |
2554 | If True, avoid side-effets, such as implicit displayhooks, history, |
|
2554 | If True, avoid side-effets, such as implicit displayhooks, history, | |
2555 | and logging. silent=True forces store_history=False. |
|
2555 | and logging. silent=True forces store_history=False. | |
2556 | """ |
|
2556 | """ | |
2557 | if (not raw_cell) or raw_cell.isspace(): |
|
2557 | if (not raw_cell) or raw_cell.isspace(): | |
2558 | return |
|
2558 | return | |
2559 |
|
2559 | |||
2560 | if silent: |
|
2560 | if silent: | |
2561 | store_history = False |
|
2561 | store_history = False | |
2562 |
|
2562 | |||
2563 | self.input_splitter.push(raw_cell) |
|
2563 | self.input_splitter.push(raw_cell) | |
2564 |
|
2564 | |||
2565 | # Check for cell magics, which leave state behind. This interface is |
|
2565 | # Check for cell magics, which leave state behind. This interface is | |
2566 | # ugly, we need to do something cleaner later... Now the logic is |
|
2566 | # ugly, we need to do something cleaner later... Now the logic is | |
2567 | # simply that the input_splitter remembers if there was a cell magic, |
|
2567 | # simply that the input_splitter remembers if there was a cell magic, | |
2568 | # and in that case we grab the cell body. |
|
2568 | # and in that case we grab the cell body. | |
2569 | if self.input_splitter.cell_magic_parts: |
|
2569 | if self.input_splitter.cell_magic_parts: | |
2570 | self._current_cell_magic_body = \ |
|
2570 | self._current_cell_magic_body = \ | |
2571 | ''.join(self.input_splitter.cell_magic_parts) |
|
2571 | ''.join(self.input_splitter.cell_magic_parts) | |
2572 | cell = self.input_splitter.source_reset() |
|
2572 | cell = self.input_splitter.source_reset() | |
2573 |
|
2573 | |||
2574 | with self.builtin_trap: |
|
2574 | with self.builtin_trap: | |
2575 | prefilter_failed = False |
|
2575 | prefilter_failed = False | |
2576 | if len(cell.splitlines()) == 1: |
|
2576 | if len(cell.splitlines()) == 1: | |
2577 | try: |
|
2577 | try: | |
2578 | # use prefilter_lines to handle trailing newlines |
|
2578 | # use prefilter_lines to handle trailing newlines | |
2579 | # restore trailing newline for ast.parse |
|
2579 | # restore trailing newline for ast.parse | |
2580 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2580 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2581 | except AliasError as e: |
|
2581 | except AliasError as e: | |
2582 | error(e) |
|
2582 | error(e) | |
2583 | prefilter_failed = True |
|
2583 | prefilter_failed = True | |
2584 | except Exception: |
|
2584 | except Exception: | |
2585 | # don't allow prefilter errors to crash IPython |
|
2585 | # don't allow prefilter errors to crash IPython | |
2586 | self.showtraceback() |
|
2586 | self.showtraceback() | |
2587 | prefilter_failed = True |
|
2587 | prefilter_failed = True | |
2588 |
|
2588 | |||
2589 | # Store raw and processed history |
|
2589 | # Store raw and processed history | |
2590 | if store_history: |
|
2590 | if store_history: | |
2591 | self.history_manager.store_inputs(self.execution_count, |
|
2591 | self.history_manager.store_inputs(self.execution_count, | |
2592 | cell, raw_cell) |
|
2592 | cell, raw_cell) | |
2593 | if not silent: |
|
2593 | if not silent: | |
2594 | self.logger.log(cell, raw_cell) |
|
2594 | self.logger.log(cell, raw_cell) | |
2595 |
|
2595 | |||
2596 | if not prefilter_failed: |
|
2596 | if not prefilter_failed: | |
2597 | # don't run if prefilter failed |
|
2597 | # don't run if prefilter failed | |
2598 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2598 | cell_name = self.compile.cache(cell, self.execution_count) | |
2599 |
|
2599 | |||
2600 | with self.display_trap: |
|
2600 | with self.display_trap: | |
2601 | try: |
|
2601 | try: | |
2602 | code_ast = self.compile.ast_parse(cell, |
|
2602 | code_ast = self.compile.ast_parse(cell, | |
2603 | filename=cell_name) |
|
2603 | filename=cell_name) | |
2604 | except IndentationError: |
|
2604 | except IndentationError: | |
2605 | self.showindentationerror() |
|
2605 | self.showindentationerror() | |
2606 | if store_history: |
|
2606 | if store_history: | |
2607 | self.execution_count += 1 |
|
2607 | self.execution_count += 1 | |
2608 | return None |
|
2608 | return None | |
2609 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2609 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2610 | MemoryError): |
|
2610 | MemoryError): | |
2611 | self.showsyntaxerror() |
|
2611 | self.showsyntaxerror() | |
2612 | if store_history: |
|
2612 | if store_history: | |
2613 | self.execution_count += 1 |
|
2613 | self.execution_count += 1 | |
2614 | return None |
|
2614 | return None | |
2615 |
|
2615 | |||
2616 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2616 | interactivity = "none" if silent else self.ast_node_interactivity | |
2617 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2617 | self.run_ast_nodes(code_ast.body, cell_name, | |
2618 | interactivity=interactivity) |
|
2618 | interactivity=interactivity) | |
2619 |
|
2619 | |||
2620 | # Execute any registered post-execution functions. |
|
2620 | # Execute any registered post-execution functions. | |
2621 | # unless we are silent |
|
2621 | # unless we are silent | |
2622 | post_exec = [] if silent else self._post_execute.iteritems() |
|
2622 | post_exec = [] if silent else self._post_execute.iteritems() | |
2623 |
|
2623 | |||
2624 | for func, status in post_exec: |
|
2624 | for func, status in post_exec: | |
2625 | if self.disable_failing_post_execute and not status: |
|
2625 | if self.disable_failing_post_execute and not status: | |
2626 | continue |
|
2626 | continue | |
2627 | try: |
|
2627 | try: | |
2628 | func() |
|
2628 | func() | |
2629 | except KeyboardInterrupt: |
|
2629 | except KeyboardInterrupt: | |
2630 | print("\nKeyboardInterrupt", file=io.stderr) |
|
2630 | print("\nKeyboardInterrupt", file=io.stderr) | |
2631 | except Exception: |
|
2631 | except Exception: | |
2632 | # register as failing: |
|
2632 | # register as failing: | |
2633 | self._post_execute[func] = False |
|
2633 | self._post_execute[func] = False | |
2634 | self.showtraceback() |
|
2634 | self.showtraceback() | |
2635 | print('\n'.join([ |
|
2635 | print('\n'.join([ | |
2636 | "post-execution function %r produced an error." % func, |
|
2636 | "post-execution function %r produced an error." % func, | |
2637 | "If this problem persists, you can disable failing post-exec functions with:", |
|
2637 | "If this problem persists, you can disable failing post-exec functions with:", | |
2638 | "", |
|
2638 | "", | |
2639 | " get_ipython().disable_failing_post_execute = True" |
|
2639 | " get_ipython().disable_failing_post_execute = True" | |
2640 | ]), file=io.stderr) |
|
2640 | ]), file=io.stderr) | |
2641 |
|
2641 | |||
2642 | if store_history: |
|
2642 | if store_history: | |
2643 | # Write output to the database. Does nothing unless |
|
2643 | # Write output to the database. Does nothing unless | |
2644 | # history output logging is enabled. |
|
2644 | # history output logging is enabled. | |
2645 | self.history_manager.store_output(self.execution_count) |
|
2645 | self.history_manager.store_output(self.execution_count) | |
2646 | # Each cell is a *single* input, regardless of how many lines it has |
|
2646 | # Each cell is a *single* input, regardless of how many lines it has | |
2647 | self.execution_count += 1 |
|
2647 | self.execution_count += 1 | |
2648 |
|
2648 | |||
2649 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): |
|
2649 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): | |
2650 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2650 | """Run a sequence of AST nodes. The execution mode depends on the | |
2651 | interactivity parameter. |
|
2651 | interactivity parameter. | |
2652 |
|
2652 | |||
2653 | Parameters |
|
2653 | Parameters | |
2654 | ---------- |
|
2654 | ---------- | |
2655 | nodelist : list |
|
2655 | nodelist : list | |
2656 | A sequence of AST nodes to run. |
|
2656 | A sequence of AST nodes to run. | |
2657 | cell_name : str |
|
2657 | cell_name : str | |
2658 | Will be passed to the compiler as the filename of the cell. Typically |
|
2658 | Will be passed to the compiler as the filename of the cell. Typically | |
2659 | the value returned by ip.compile.cache(cell). |
|
2659 | the value returned by ip.compile.cache(cell). | |
2660 | interactivity : str |
|
2660 | interactivity : str | |
2661 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2661 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2662 | run interactively (displaying output from expressions). 'last_expr' |
|
2662 | run interactively (displaying output from expressions). 'last_expr' | |
2663 | will run the last node interactively only if it is an expression (i.e. |
|
2663 | will run the last node interactively only if it is an expression (i.e. | |
2664 | expressions in loops or other blocks are not displayed. Other values |
|
2664 | expressions in loops or other blocks are not displayed. Other values | |
2665 | for this parameter will raise a ValueError. |
|
2665 | for this parameter will raise a ValueError. | |
2666 | """ |
|
2666 | """ | |
2667 | if not nodelist: |
|
2667 | if not nodelist: | |
2668 | return |
|
2668 | return | |
2669 |
|
2669 | |||
2670 | if interactivity == 'last_expr': |
|
2670 | if interactivity == 'last_expr': | |
2671 | if isinstance(nodelist[-1], ast.Expr): |
|
2671 | if isinstance(nodelist[-1], ast.Expr): | |
2672 | interactivity = "last" |
|
2672 | interactivity = "last" | |
2673 | else: |
|
2673 | else: | |
2674 | interactivity = "none" |
|
2674 | interactivity = "none" | |
2675 |
|
2675 | |||
2676 | if interactivity == 'none': |
|
2676 | if interactivity == 'none': | |
2677 | to_run_exec, to_run_interactive = nodelist, [] |
|
2677 | to_run_exec, to_run_interactive = nodelist, [] | |
2678 | elif interactivity == 'last': |
|
2678 | elif interactivity == 'last': | |
2679 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2679 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2680 | elif interactivity == 'all': |
|
2680 | elif interactivity == 'all': | |
2681 | to_run_exec, to_run_interactive = [], nodelist |
|
2681 | to_run_exec, to_run_interactive = [], nodelist | |
2682 | else: |
|
2682 | else: | |
2683 | raise ValueError("Interactivity was %r" % interactivity) |
|
2683 | raise ValueError("Interactivity was %r" % interactivity) | |
2684 |
|
2684 | |||
2685 | exec_count = self.execution_count |
|
2685 | exec_count = self.execution_count | |
2686 |
|
2686 | |||
2687 | try: |
|
2687 | try: | |
2688 | for i, node in enumerate(to_run_exec): |
|
2688 | for i, node in enumerate(to_run_exec): | |
2689 | mod = ast.Module([node]) |
|
2689 | mod = ast.Module([node]) | |
2690 | code = self.compile(mod, cell_name, "exec") |
|
2690 | code = self.compile(mod, cell_name, "exec") | |
2691 | if self.run_code(code): |
|
2691 | if self.run_code(code): | |
2692 | return True |
|
2692 | return True | |
2693 |
|
2693 | |||
2694 | for i, node in enumerate(to_run_interactive): |
|
2694 | for i, node in enumerate(to_run_interactive): | |
2695 | mod = ast.Interactive([node]) |
|
2695 | mod = ast.Interactive([node]) | |
2696 | code = self.compile(mod, cell_name, "single") |
|
2696 | code = self.compile(mod, cell_name, "single") | |
2697 | if self.run_code(code): |
|
2697 | if self.run_code(code): | |
2698 | return True |
|
2698 | return True | |
2699 |
|
2699 | |||
2700 | # Flush softspace |
|
2700 | # Flush softspace | |
2701 | if softspace(sys.stdout, 0): |
|
2701 | if softspace(sys.stdout, 0): | |
2702 | print() |
|
2702 | print() | |
2703 |
|
2703 | |||
2704 | except: |
|
2704 | except: | |
2705 | # It's possible to have exceptions raised here, typically by |
|
2705 | # It's possible to have exceptions raised here, typically by | |
2706 | # compilation of odd code (such as a naked 'return' outside a |
|
2706 | # compilation of odd code (such as a naked 'return' outside a | |
2707 | # function) that did parse but isn't valid. Typically the exception |
|
2707 | # function) that did parse but isn't valid. Typically the exception | |
2708 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2708 | # is a SyntaxError, but it's safest just to catch anything and show | |
2709 | # the user a traceback. |
|
2709 | # the user a traceback. | |
2710 |
|
2710 | |||
2711 | # We do only one try/except outside the loop to minimize the impact |
|
2711 | # We do only one try/except outside the loop to minimize the impact | |
2712 | # on runtime, and also because if any node in the node list is |
|
2712 | # on runtime, and also because if any node in the node list is | |
2713 | # broken, we should stop execution completely. |
|
2713 | # broken, we should stop execution completely. | |
2714 | self.showtraceback() |
|
2714 | self.showtraceback() | |
2715 |
|
2715 | |||
2716 | return False |
|
2716 | return False | |
2717 |
|
2717 | |||
2718 | def run_code(self, code_obj): |
|
2718 | def run_code(self, code_obj): | |
2719 | """Execute a code object. |
|
2719 | """Execute a code object. | |
2720 |
|
2720 | |||
2721 | When an exception occurs, self.showtraceback() is called to display a |
|
2721 | When an exception occurs, self.showtraceback() is called to display a | |
2722 | traceback. |
|
2722 | traceback. | |
2723 |
|
2723 | |||
2724 | Parameters |
|
2724 | Parameters | |
2725 | ---------- |
|
2725 | ---------- | |
2726 | code_obj : code object |
|
2726 | code_obj : code object | |
2727 | A compiled code object, to be executed |
|
2727 | A compiled code object, to be executed | |
2728 |
|
2728 | |||
2729 | Returns |
|
2729 | Returns | |
2730 | ------- |
|
2730 | ------- | |
2731 | False : successful execution. |
|
2731 | False : successful execution. | |
2732 | True : an error occurred. |
|
2732 | True : an error occurred. | |
2733 | """ |
|
2733 | """ | |
2734 |
|
2734 | |||
2735 | # Set our own excepthook in case the user code tries to call it |
|
2735 | # Set our own excepthook in case the user code tries to call it | |
2736 | # directly, so that the IPython crash handler doesn't get triggered |
|
2736 | # directly, so that the IPython crash handler doesn't get triggered | |
2737 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2737 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2738 |
|
2738 | |||
2739 | # we save the original sys.excepthook in the instance, in case config |
|
2739 | # we save the original sys.excepthook in the instance, in case config | |
2740 | # code (such as magics) needs access to it. |
|
2740 | # code (such as magics) needs access to it. | |
2741 | self.sys_excepthook = old_excepthook |
|
2741 | self.sys_excepthook = old_excepthook | |
2742 | outflag = 1 # happens in more places, so it's easier as default |
|
2742 | outflag = 1 # happens in more places, so it's easier as default | |
2743 | try: |
|
2743 | try: | |
2744 | try: |
|
2744 | try: | |
2745 | self.hooks.pre_run_code_hook() |
|
2745 | self.hooks.pre_run_code_hook() | |
2746 | #rprint('Running code', repr(code_obj)) # dbg |
|
2746 | #rprint('Running code', repr(code_obj)) # dbg | |
2747 | exec code_obj in self.user_global_ns, self.user_ns |
|
2747 | exec code_obj in self.user_global_ns, self.user_ns | |
2748 | finally: |
|
2748 | finally: | |
2749 | # Reset our crash handler in place |
|
2749 | # Reset our crash handler in place | |
2750 | sys.excepthook = old_excepthook |
|
2750 | sys.excepthook = old_excepthook | |
2751 | except SystemExit: |
|
2751 | except SystemExit: | |
2752 | self.showtraceback(exception_only=True) |
|
2752 | self.showtraceback(exception_only=True) | |
2753 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2753 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) | |
2754 | except self.custom_exceptions: |
|
2754 | except self.custom_exceptions: | |
2755 | etype,value,tb = sys.exc_info() |
|
2755 | etype,value,tb = sys.exc_info() | |
2756 | self.CustomTB(etype,value,tb) |
|
2756 | self.CustomTB(etype,value,tb) | |
2757 | except: |
|
2757 | except: | |
2758 | self.showtraceback() |
|
2758 | self.showtraceback() | |
2759 | else: |
|
2759 | else: | |
2760 | outflag = 0 |
|
2760 | outflag = 0 | |
2761 | return outflag |
|
2761 | return outflag | |
2762 |
|
2762 | |||
2763 | # For backwards compatibility |
|
2763 | # For backwards compatibility | |
2764 | runcode = run_code |
|
2764 | runcode = run_code | |
2765 |
|
2765 | |||
2766 | #------------------------------------------------------------------------- |
|
2766 | #------------------------------------------------------------------------- | |
2767 | # Things related to GUI support and pylab |
|
2767 | # Things related to GUI support and pylab | |
2768 | #------------------------------------------------------------------------- |
|
2768 | #------------------------------------------------------------------------- | |
2769 |
|
2769 | |||
2770 | def enable_gui(self, gui=None): |
|
2770 | def enable_gui(self, gui=None): | |
2771 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2771 | raise NotImplementedError('Implement enable_gui in a subclass') | |
2772 |
|
2772 | |||
2773 | def enable_pylab(self, gui=None, import_all=True): |
|
2773 | def enable_pylab(self, gui=None, import_all=True): | |
2774 | """Activate pylab support at runtime. |
|
2774 | """Activate pylab support at runtime. | |
2775 |
|
2775 | |||
2776 | This turns on support for matplotlib, preloads into the interactive |
|
2776 | This turns on support for matplotlib, preloads into the interactive | |
2777 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2777 | namespace all of numpy and pylab, and configures IPython to correctly | |
2778 | interact with the GUI event loop. The GUI backend to be used can be |
|
2778 | interact with the GUI event loop. The GUI backend to be used can be | |
2779 | optionally selected with the optional :param:`gui` argument. |
|
2779 | optionally selected with the optional :param:`gui` argument. | |
2780 |
|
2780 | |||
2781 | Parameters |
|
2781 | Parameters | |
2782 | ---------- |
|
2782 | ---------- | |
2783 | gui : optional, string |
|
2783 | gui : optional, string | |
2784 |
|
2784 | |||
2785 | If given, dictates the choice of matplotlib GUI backend to use |
|
2785 | If given, dictates the choice of matplotlib GUI backend to use | |
2786 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2786 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2787 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2787 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2788 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2788 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2789 | user's matplotlibrc configuration file). Note that not all backends |
|
2789 | user's matplotlibrc configuration file). Note that not all backends | |
2790 | make sense in all contexts, for example a terminal ipython can't |
|
2790 | make sense in all contexts, for example a terminal ipython can't | |
2791 | display figures inline. |
|
2791 | display figures inline. | |
2792 | """ |
|
2792 | """ | |
2793 | from IPython.core.pylabtools import mpl_runner |
|
2793 | from IPython.core.pylabtools import mpl_runner | |
2794 | # We want to prevent the loading of pylab to pollute the user's |
|
2794 | # We want to prevent the loading of pylab to pollute the user's | |
2795 | # namespace as shown by the %who* magics, so we execute the activation |
|
2795 | # namespace as shown by the %who* magics, so we execute the activation | |
2796 | # code in an empty namespace, and we update *both* user_ns and |
|
2796 | # code in an empty namespace, and we update *both* user_ns and | |
2797 | # user_ns_hidden with this information. |
|
2797 | # user_ns_hidden with this information. | |
2798 | ns = {} |
|
2798 | ns = {} | |
2799 | try: |
|
2799 | try: | |
2800 | gui = pylab_activate(ns, gui, import_all, self) |
|
2800 | gui = pylab_activate(ns, gui, import_all, self) | |
2801 | except KeyError: |
|
2801 | except KeyError: | |
2802 | error("Backend %r not supported" % gui) |
|
2802 | error("Backend %r not supported" % gui) | |
2803 | return |
|
2803 | return | |
2804 | self.user_ns.update(ns) |
|
2804 | self.user_ns.update(ns) | |
2805 | self.user_ns_hidden.update(ns) |
|
2805 | self.user_ns_hidden.update(ns) | |
2806 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2806 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2807 | # plot updates into account |
|
2807 | # plot updates into account | |
2808 | self.enable_gui(gui) |
|
2808 | self.enable_gui(gui) | |
2809 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2809 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
2810 | mpl_runner(self.safe_execfile) |
|
2810 | mpl_runner(self.safe_execfile) | |
2811 |
|
2811 | |||
2812 | #------------------------------------------------------------------------- |
|
2812 | #------------------------------------------------------------------------- | |
2813 | # Utilities |
|
2813 | # Utilities | |
2814 | #------------------------------------------------------------------------- |
|
2814 | #------------------------------------------------------------------------- | |
2815 |
|
2815 | |||
2816 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2816 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2817 | """Expand python variables in a string. |
|
2817 | """Expand python variables in a string. | |
2818 |
|
2818 | |||
2819 | The depth argument indicates how many frames above the caller should |
|
2819 | The depth argument indicates how many frames above the caller should | |
2820 | be walked to look for the local namespace where to expand variables. |
|
2820 | be walked to look for the local namespace where to expand variables. | |
2821 |
|
2821 | |||
2822 | The global namespace for expansion is always the user's interactive |
|
2822 | The global namespace for expansion is always the user's interactive | |
2823 | namespace. |
|
2823 | namespace. | |
2824 | """ |
|
2824 | """ | |
2825 | ns = self.user_ns.copy() |
|
2825 | ns = self.user_ns.copy() | |
2826 | ns.update(sys._getframe(depth+1).f_locals) |
|
2826 | ns.update(sys._getframe(depth+1).f_locals) | |
2827 | ns.pop('self', None) |
|
2827 | ns.pop('self', None) | |
2828 | try: |
|
2828 | try: | |
2829 | cmd = formatter.format(cmd, **ns) |
|
2829 | cmd = formatter.format(cmd, **ns) | |
2830 | except Exception: |
|
2830 | except Exception: | |
2831 | # if formatter couldn't format, just let it go untransformed |
|
2831 | # if formatter couldn't format, just let it go untransformed | |
2832 | pass |
|
2832 | pass | |
2833 | return cmd |
|
2833 | return cmd | |
2834 |
|
2834 | |||
2835 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2835 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2836 | """Make a new tempfile and return its filename. |
|
2836 | """Make a new tempfile and return its filename. | |
2837 |
|
2837 | |||
2838 | This makes a call to tempfile.mktemp, but it registers the created |
|
2838 | This makes a call to tempfile.mktemp, but it registers the created | |
2839 | filename internally so ipython cleans it up at exit time. |
|
2839 | filename internally so ipython cleans it up at exit time. | |
2840 |
|
2840 | |||
2841 | Optional inputs: |
|
2841 | Optional inputs: | |
2842 |
|
2842 | |||
2843 | - data(None): if data is given, it gets written out to the temp file |
|
2843 | - data(None): if data is given, it gets written out to the temp file | |
2844 | immediately, and the file is closed again.""" |
|
2844 | immediately, and the file is closed again.""" | |
2845 |
|
2845 | |||
2846 | filename = tempfile.mktemp('.py', prefix) |
|
2846 | filename = tempfile.mktemp('.py', prefix) | |
2847 | self.tempfiles.append(filename) |
|
2847 | self.tempfiles.append(filename) | |
2848 |
|
2848 | |||
2849 | if data: |
|
2849 | if data: | |
2850 | tmp_file = open(filename,'w') |
|
2850 | tmp_file = open(filename,'w') | |
2851 | tmp_file.write(data) |
|
2851 | tmp_file.write(data) | |
2852 | tmp_file.close() |
|
2852 | tmp_file.close() | |
2853 | return filename |
|
2853 | return filename | |
2854 |
|
2854 | |||
2855 | # TODO: This should be removed when Term is refactored. |
|
2855 | # TODO: This should be removed when Term is refactored. | |
2856 | def write(self,data): |
|
2856 | def write(self,data): | |
2857 | """Write a string to the default output""" |
|
2857 | """Write a string to the default output""" | |
2858 | io.stdout.write(data) |
|
2858 | io.stdout.write(data) | |
2859 |
|
2859 | |||
2860 | # TODO: This should be removed when Term is refactored. |
|
2860 | # TODO: This should be removed when Term is refactored. | |
2861 | def write_err(self,data): |
|
2861 | def write_err(self,data): | |
2862 | """Write a string to the default error output""" |
|
2862 | """Write a string to the default error output""" | |
2863 | io.stderr.write(data) |
|
2863 | io.stderr.write(data) | |
2864 |
|
2864 | |||
2865 | def ask_yes_no(self, prompt, default=None): |
|
2865 | def ask_yes_no(self, prompt, default=None): | |
2866 | if self.quiet: |
|
2866 | if self.quiet: | |
2867 | return True |
|
2867 | return True | |
2868 | return ask_yes_no(prompt,default) |
|
2868 | return ask_yes_no(prompt,default) | |
2869 |
|
2869 | |||
2870 | def show_usage(self): |
|
2870 | def show_usage(self): | |
2871 | """Show a usage message""" |
|
2871 | """Show a usage message""" | |
2872 | page.page(IPython.core.usage.interactive_usage) |
|
2872 | page.page(IPython.core.usage.interactive_usage) | |
2873 |
|
2873 | |||
2874 | def extract_input_lines(self, range_str, raw=False): |
|
2874 | def extract_input_lines(self, range_str, raw=False): | |
2875 | """Return as a string a set of input history slices. |
|
2875 | """Return as a string a set of input history slices. | |
2876 |
|
2876 | |||
2877 | Parameters |
|
2877 | Parameters | |
2878 | ---------- |
|
2878 | ---------- | |
2879 | range_str : string |
|
2879 | range_str : string | |
2880 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
2880 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
2881 | since this function is for use by magic functions which get their |
|
2881 | since this function is for use by magic functions which get their | |
2882 | arguments as strings. The number before the / is the session |
|
2882 | arguments as strings. The number before the / is the session | |
2883 | number: ~n goes n back from the current session. |
|
2883 | number: ~n goes n back from the current session. | |
2884 |
|
2884 | |||
2885 | Optional Parameters: |
|
2885 | Optional Parameters: | |
2886 | - raw(False): by default, the processed input is used. If this is |
|
2886 | - raw(False): by default, the processed input is used. If this is | |
2887 | true, the raw input history is used instead. |
|
2887 | true, the raw input history is used instead. | |
2888 |
|
2888 | |||
2889 | Note that slices can be called with two notations: |
|
2889 | Note that slices can be called with two notations: | |
2890 |
|
2890 | |||
2891 | N:M -> standard python form, means including items N...(M-1). |
|
2891 | N:M -> standard python form, means including items N...(M-1). | |
2892 |
|
2892 | |||
2893 | N-M -> include items N..M (closed endpoint).""" |
|
2893 | N-M -> include items N..M (closed endpoint).""" | |
2894 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
2894 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
2895 | return "\n".join(x for _, _, x in lines) |
|
2895 | return "\n".join(x for _, _, x in lines) | |
2896 |
|
2896 | |||
2897 | def find_user_code(self, target, raw=True, py_only=False): |
|
2897 | def find_user_code(self, target, raw=True, py_only=False): | |
2898 | """Get a code string from history, file, url, or a string or macro. |
|
2898 | """Get a code string from history, file, url, or a string or macro. | |
2899 |
|
2899 | |||
2900 | This is mainly used by magic functions. |
|
2900 | This is mainly used by magic functions. | |
2901 |
|
2901 | |||
2902 | Parameters |
|
2902 | Parameters | |
2903 | ---------- |
|
2903 | ---------- | |
2904 |
|
2904 | |||
2905 | target : str |
|
2905 | target : str | |
2906 |
|
2906 | |||
2907 | A string specifying code to retrieve. This will be tried respectively |
|
2907 | A string specifying code to retrieve. This will be tried respectively | |
2908 | as: ranges of input history (see %history for syntax), url, |
|
2908 | as: ranges of input history (see %history for syntax), url, | |
2909 | correspnding .py file, filename, or an expression evaluating to a |
|
2909 | correspnding .py file, filename, or an expression evaluating to a | |
2910 | string or Macro in the user namespace. |
|
2910 | string or Macro in the user namespace. | |
2911 |
|
2911 | |||
2912 | raw : bool |
|
2912 | raw : bool | |
2913 | If true (default), retrieve raw history. Has no effect on the other |
|
2913 | If true (default), retrieve raw history. Has no effect on the other | |
2914 | retrieval mechanisms. |
|
2914 | retrieval mechanisms. | |
2915 |
|
2915 | |||
2916 | py_only : bool (default False) |
|
2916 | py_only : bool (default False) | |
2917 | Only try to fetch python code, do not try alternative methods to decode file |
|
2917 | Only try to fetch python code, do not try alternative methods to decode file | |
2918 | if unicode fails. |
|
2918 | if unicode fails. | |
2919 |
|
2919 | |||
2920 | Returns |
|
2920 | Returns | |
2921 | ------- |
|
2921 | ------- | |
2922 | A string of code. |
|
2922 | A string of code. | |
2923 |
|
2923 | |||
2924 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2924 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
2925 | to an object of another type. In each case, .args[0] is a printable |
|
2925 | to an object of another type. In each case, .args[0] is a printable | |
2926 | message. |
|
2926 | message. | |
2927 | """ |
|
2927 | """ | |
2928 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2928 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
2929 | if code: |
|
2929 | if code: | |
2930 | return code |
|
2930 | return code | |
2931 | utarget = unquote_filename(target) |
|
2931 | utarget = unquote_filename(target) | |
2932 | try: |
|
2932 | try: | |
2933 | if utarget.startswith(('http://', 'https://')): |
|
2933 | if utarget.startswith(('http://', 'https://')): | |
2934 | return openpy.read_py_url(utarget, skip_encoding_cookie=True) |
|
2934 | return openpy.read_py_url(utarget, skip_encoding_cookie=True) | |
2935 | except UnicodeDecodeError: |
|
2935 | except UnicodeDecodeError: | |
2936 | if not py_only : |
|
2936 | if not py_only : | |
2937 | response = urllib.urlopen(target) |
|
2937 | response = urllib.urlopen(target) | |
2938 | return response.read().decode('latin1') |
|
2938 | return response.read().decode('latin1') | |
2939 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
2939 | raise ValueError(("'%s' seem to be unreadable.") % utarget) | |
2940 |
|
2940 | |||
2941 | potential_target = [target] |
|
2941 | potential_target = [target] | |
2942 | try : |
|
2942 | try : | |
2943 | potential_target.insert(0,get_py_filename(target)) |
|
2943 | potential_target.insert(0,get_py_filename(target)) | |
2944 | except IOError: |
|
2944 | except IOError: | |
2945 | pass |
|
2945 | pass | |
2946 |
|
2946 | |||
2947 | for tgt in potential_target : |
|
2947 | for tgt in potential_target : | |
2948 | if os.path.isfile(tgt): # Read file |
|
2948 | if os.path.isfile(tgt): # Read file | |
2949 | try : |
|
2949 | try : | |
2950 | return openpy.read_py_file(tgt, skip_encoding_cookie=True) |
|
2950 | return openpy.read_py_file(tgt, skip_encoding_cookie=True) | |
2951 | except UnicodeDecodeError : |
|
2951 | except UnicodeDecodeError : | |
2952 | if not py_only : |
|
2952 | if not py_only : | |
2953 | with io_open(tgt,'r', encoding='latin1') as f : |
|
2953 | with io_open(tgt,'r', encoding='latin1') as f : | |
2954 | return f.read() |
|
2954 | return f.read() | |
2955 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
2955 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
2956 |
|
2956 | |||
2957 | try: # User namespace |
|
2957 | try: # User namespace | |
2958 | codeobj = eval(target, self.user_ns) |
|
2958 | codeobj = eval(target, self.user_ns) | |
2959 | except Exception: |
|
2959 | except Exception: | |
2960 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
2960 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
2961 | "nor in the user namespace.") % target) |
|
2961 | "nor in the user namespace.") % target) | |
2962 | if isinstance(codeobj, basestring): |
|
2962 | if isinstance(codeobj, basestring): | |
2963 | return codeobj |
|
2963 | return codeobj | |
2964 | elif isinstance(codeobj, Macro): |
|
2964 | elif isinstance(codeobj, Macro): | |
2965 | return codeobj.value |
|
2965 | return codeobj.value | |
2966 |
|
2966 | |||
2967 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2967 | raise TypeError("%s is neither a string nor a macro." % target, | |
2968 | codeobj) |
|
2968 | codeobj) | |
2969 |
|
2969 | |||
2970 | #------------------------------------------------------------------------- |
|
2970 | #------------------------------------------------------------------------- | |
2971 | # Things related to IPython exiting |
|
2971 | # Things related to IPython exiting | |
2972 | #------------------------------------------------------------------------- |
|
2972 | #------------------------------------------------------------------------- | |
2973 | def atexit_operations(self): |
|
2973 | def atexit_operations(self): | |
2974 | """This will be executed at the time of exit. |
|
2974 | """This will be executed at the time of exit. | |
2975 |
|
2975 | |||
2976 | Cleanup operations and saving of persistent data that is done |
|
2976 | Cleanup operations and saving of persistent data that is done | |
2977 | unconditionally by IPython should be performed here. |
|
2977 | unconditionally by IPython should be performed here. | |
2978 |
|
2978 | |||
2979 | For things that may depend on startup flags or platform specifics (such |
|
2979 | For things that may depend on startup flags or platform specifics (such | |
2980 | as having readline or not), register a separate atexit function in the |
|
2980 | as having readline or not), register a separate atexit function in the | |
2981 | code that has the appropriate information, rather than trying to |
|
2981 | code that has the appropriate information, rather than trying to | |
2982 | clutter |
|
2982 | clutter | |
2983 | """ |
|
2983 | """ | |
2984 | # Close the history session (this stores the end time and line count) |
|
2984 | # Close the history session (this stores the end time and line count) | |
2985 | # this must be *before* the tempfile cleanup, in case of temporary |
|
2985 | # this must be *before* the tempfile cleanup, in case of temporary | |
2986 | # history db |
|
2986 | # history db | |
2987 | self.history_manager.end_session() |
|
2987 | self.history_manager.end_session() | |
2988 |
|
2988 | |||
2989 | # Cleanup all tempfiles left around |
|
2989 | # Cleanup all tempfiles left around | |
2990 | for tfile in self.tempfiles: |
|
2990 | for tfile in self.tempfiles: | |
2991 | try: |
|
2991 | try: | |
2992 | os.unlink(tfile) |
|
2992 | os.unlink(tfile) | |
2993 | except OSError: |
|
2993 | except OSError: | |
2994 | pass |
|
2994 | pass | |
2995 |
|
2995 | |||
2996 | # Clear all user namespaces to release all references cleanly. |
|
2996 | # Clear all user namespaces to release all references cleanly. | |
2997 | self.reset(new_session=False) |
|
2997 | self.reset(new_session=False) | |
2998 |
|
2998 | |||
2999 | # Run user hooks |
|
2999 | # Run user hooks | |
3000 | self.hooks.shutdown_hook() |
|
3000 | self.hooks.shutdown_hook() | |
3001 |
|
3001 | |||
3002 | def cleanup(self): |
|
3002 | def cleanup(self): | |
3003 | self.restore_sys_module_state() |
|
3003 | self.restore_sys_module_state() | |
3004 |
|
3004 | |||
3005 |
|
3005 | |||
3006 | class InteractiveShellABC(object): |
|
3006 | class InteractiveShellABC(object): | |
3007 | """An abstract base class for InteractiveShell.""" |
|
3007 | """An abstract base class for InteractiveShell.""" | |
3008 | __metaclass__ = abc.ABCMeta |
|
3008 | __metaclass__ = abc.ABCMeta | |
3009 |
|
3009 | |||
3010 | InteractiveShellABC.register(InteractiveShell) |
|
3010 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,220 +1,220 b'' | |||||
1 | """Logger class for IPython's logging facilities. |
|
1 | """Logger class for IPython's logging facilities. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | #***************************************************************************** |
|
4 | #***************************************************************************** | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
6 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 |
|
11 | |||
12 | #**************************************************************************** |
|
12 | #**************************************************************************** | |
13 | # Modules and globals |
|
13 | # Modules and globals | |
14 |
|
14 | |||
15 | # Python standard modules |
|
15 | # Python standard modules | |
16 | import glob |
|
16 | import glob | |
17 | import io |
|
17 | import io | |
18 | import os |
|
18 | import os | |
19 | import time |
|
19 | import time | |
20 |
|
20 | |||
21 | from IPython.utils.py3compat import str_to_unicode |
|
21 | from IPython.utils.py3compat import str_to_unicode | |
22 |
|
22 | |||
23 | #**************************************************************************** |
|
23 | #**************************************************************************** | |
24 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from |
|
24 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from | |
25 | # ipython and does input cache management. Finish cleanup later... |
|
25 | # ipython and does input cache management. Finish cleanup later... | |
26 |
|
26 | |||
27 | class Logger(object): |
|
27 | class Logger(object): | |
28 | """A Logfile class with different policies for file creation""" |
|
28 | """A Logfile class with different policies for file creation""" | |
29 |
|
29 | |||
30 | def __init__(self, home_dir, logfname='Logger.log', loghead=u'', |
|
30 | def __init__(self, home_dir, logfname='Logger.log', loghead=u'', | |
31 | logmode='over'): |
|
31 | logmode='over'): | |
32 |
|
32 | |||
33 | # this is the full ipython instance, we need some attributes from it |
|
33 | # this is the full ipython instance, we need some attributes from it | |
34 | # which won't exist until later. What a mess, clean up later... |
|
34 | # which won't exist until later. What a mess, clean up later... | |
35 | self.home_dir = home_dir |
|
35 | self.home_dir = home_dir | |
36 |
|
36 | |||
37 | self.logfname = logfname |
|
37 | self.logfname = logfname | |
38 | self.loghead = loghead |
|
38 | self.loghead = loghead | |
39 | self.logmode = logmode |
|
39 | self.logmode = logmode | |
40 | self.logfile = None |
|
40 | self.logfile = None | |
41 |
|
41 | |||
42 | # Whether to log raw or processed input |
|
42 | # Whether to log raw or processed input | |
43 | self.log_raw_input = False |
|
43 | self.log_raw_input = False | |
44 |
|
44 | |||
45 | # whether to also log output |
|
45 | # whether to also log output | |
46 | self.log_output = False |
|
46 | self.log_output = False | |
47 |
|
47 | |||
48 | # whether to put timestamps before each log entry |
|
48 | # whether to put timestamps before each log entry | |
49 | self.timestamp = False |
|
49 | self.timestamp = False | |
50 |
|
50 | |||
51 | # activity control flags |
|
51 | # activity control flags | |
52 | self.log_active = False |
|
52 | self.log_active = False | |
53 |
|
53 | |||
54 | # logmode is a validated property |
|
54 | # logmode is a validated property | |
55 | def _set_mode(self,mode): |
|
55 | def _set_mode(self,mode): | |
56 | if mode not in ['append','backup','global','over','rotate']: |
|
56 | if mode not in ['append','backup','global','over','rotate']: | |
57 |
raise ValueError |
|
57 | raise ValueError('invalid log mode %s given' % mode) | |
58 | self._logmode = mode |
|
58 | self._logmode = mode | |
59 |
|
59 | |||
60 | def _get_mode(self): |
|
60 | def _get_mode(self): | |
61 | return self._logmode |
|
61 | return self._logmode | |
62 |
|
62 | |||
63 | logmode = property(_get_mode,_set_mode) |
|
63 | logmode = property(_get_mode,_set_mode) | |
64 |
|
64 | |||
65 | def logstart(self, logfname=None, loghead=None, logmode=None, |
|
65 | def logstart(self, logfname=None, loghead=None, logmode=None, | |
66 | log_output=False, timestamp=False, log_raw_input=False): |
|
66 | log_output=False, timestamp=False, log_raw_input=False): | |
67 | """Generate a new log-file with a default header. |
|
67 | """Generate a new log-file with a default header. | |
68 |
|
68 | |||
69 | Raises RuntimeError if the log has already been started""" |
|
69 | Raises RuntimeError if the log has already been started""" | |
70 |
|
70 | |||
71 | if self.logfile is not None: |
|
71 | if self.logfile is not None: | |
72 | raise RuntimeError('Log file is already active: %s' % |
|
72 | raise RuntimeError('Log file is already active: %s' % | |
73 | self.logfname) |
|
73 | self.logfname) | |
74 |
|
74 | |||
75 | # The parameters can override constructor defaults |
|
75 | # The parameters can override constructor defaults | |
76 | if logfname is not None: self.logfname = logfname |
|
76 | if logfname is not None: self.logfname = logfname | |
77 | if loghead is not None: self.loghead = loghead |
|
77 | if loghead is not None: self.loghead = loghead | |
78 | if logmode is not None: self.logmode = logmode |
|
78 | if logmode is not None: self.logmode = logmode | |
79 |
|
79 | |||
80 | # Parameters not part of the constructor |
|
80 | # Parameters not part of the constructor | |
81 | self.timestamp = timestamp |
|
81 | self.timestamp = timestamp | |
82 | self.log_output = log_output |
|
82 | self.log_output = log_output | |
83 | self.log_raw_input = log_raw_input |
|
83 | self.log_raw_input = log_raw_input | |
84 |
|
84 | |||
85 | # init depending on the log mode requested |
|
85 | # init depending on the log mode requested | |
86 | isfile = os.path.isfile |
|
86 | isfile = os.path.isfile | |
87 | logmode = self.logmode |
|
87 | logmode = self.logmode | |
88 |
|
88 | |||
89 | if logmode == 'append': |
|
89 | if logmode == 'append': | |
90 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
90 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') | |
91 |
|
91 | |||
92 | elif logmode == 'backup': |
|
92 | elif logmode == 'backup': | |
93 | if isfile(self.logfname): |
|
93 | if isfile(self.logfname): | |
94 | backup_logname = self.logfname+'~' |
|
94 | backup_logname = self.logfname+'~' | |
95 | # Manually remove any old backup, since os.rename may fail |
|
95 | # Manually remove any old backup, since os.rename may fail | |
96 | # under Windows. |
|
96 | # under Windows. | |
97 | if isfile(backup_logname): |
|
97 | if isfile(backup_logname): | |
98 | os.remove(backup_logname) |
|
98 | os.remove(backup_logname) | |
99 | os.rename(self.logfname,backup_logname) |
|
99 | os.rename(self.logfname,backup_logname) | |
100 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
100 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') | |
101 |
|
101 | |||
102 | elif logmode == 'global': |
|
102 | elif logmode == 'global': | |
103 | self.logfname = os.path.join(self.home_dir,self.logfname) |
|
103 | self.logfname = os.path.join(self.home_dir,self.logfname) | |
104 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') |
|
104 | self.logfile = io.open(self.logfname, 'a', encoding='utf-8') | |
105 |
|
105 | |||
106 | elif logmode == 'over': |
|
106 | elif logmode == 'over': | |
107 | if isfile(self.logfname): |
|
107 | if isfile(self.logfname): | |
108 | os.remove(self.logfname) |
|
108 | os.remove(self.logfname) | |
109 | self.logfile = io.open(self.logfname,'w', encoding='utf-8') |
|
109 | self.logfile = io.open(self.logfname,'w', encoding='utf-8') | |
110 |
|
110 | |||
111 | elif logmode == 'rotate': |
|
111 | elif logmode == 'rotate': | |
112 | if isfile(self.logfname): |
|
112 | if isfile(self.logfname): | |
113 | if isfile(self.logfname+'.001~'): |
|
113 | if isfile(self.logfname+'.001~'): | |
114 | old = glob.glob(self.logfname+'.*~') |
|
114 | old = glob.glob(self.logfname+'.*~') | |
115 | old.sort() |
|
115 | old.sort() | |
116 | old.reverse() |
|
116 | old.reverse() | |
117 | for f in old: |
|
117 | for f in old: | |
118 | root, ext = os.path.splitext(f) |
|
118 | root, ext = os.path.splitext(f) | |
119 | num = int(ext[1:-1])+1 |
|
119 | num = int(ext[1:-1])+1 | |
120 | os.rename(f, root+'.'+repr(num).zfill(3)+'~') |
|
120 | os.rename(f, root+'.'+repr(num).zfill(3)+'~') | |
121 | os.rename(self.logfname, self.logfname+'.001~') |
|
121 | os.rename(self.logfname, self.logfname+'.001~') | |
122 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') |
|
122 | self.logfile = io.open(self.logfname, 'w', encoding='utf-8') | |
123 |
|
123 | |||
124 | if logmode != 'append': |
|
124 | if logmode != 'append': | |
125 | self.logfile.write(self.loghead) |
|
125 | self.logfile.write(self.loghead) | |
126 |
|
126 | |||
127 | self.logfile.flush() |
|
127 | self.logfile.flush() | |
128 | self.log_active = True |
|
128 | self.log_active = True | |
129 |
|
129 | |||
130 | def switch_log(self,val): |
|
130 | def switch_log(self,val): | |
131 | """Switch logging on/off. val should be ONLY a boolean.""" |
|
131 | """Switch logging on/off. val should be ONLY a boolean.""" | |
132 |
|
132 | |||
133 | if val not in [False,True,0,1]: |
|
133 | if val not in [False,True,0,1]: | |
134 | raise ValueError, \ |
|
134 | raise ValueError('Call switch_log ONLY with a boolean argument, ' | |
135 | 'Call switch_log ONLY with a boolean argument, not with:',val |
|
135 | 'not with: %s' % val) | |
136 |
|
136 | |||
137 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} |
|
137 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} | |
138 |
|
138 | |||
139 | if self.logfile is None: |
|
139 | if self.logfile is None: | |
140 | print """ |
|
140 | print """ | |
141 | Logging hasn't been started yet (use logstart for that). |
|
141 | Logging hasn't been started yet (use logstart for that). | |
142 |
|
142 | |||
143 | %logon/%logoff are for temporarily starting and stopping logging for a logfile |
|
143 | %logon/%logoff are for temporarily starting and stopping logging for a logfile | |
144 | which already exists. But you must first start the logging process with |
|
144 | which already exists. But you must first start the logging process with | |
145 | %logstart (optionally giving a logfile name).""" |
|
145 | %logstart (optionally giving a logfile name).""" | |
146 |
|
146 | |||
147 | else: |
|
147 | else: | |
148 | if self.log_active == val: |
|
148 | if self.log_active == val: | |
149 | print 'Logging is already',label[val] |
|
149 | print 'Logging is already',label[val] | |
150 | else: |
|
150 | else: | |
151 | print 'Switching logging',label[val] |
|
151 | print 'Switching logging',label[val] | |
152 | self.log_active = not self.log_active |
|
152 | self.log_active = not self.log_active | |
153 | self.log_active_out = self.log_active |
|
153 | self.log_active_out = self.log_active | |
154 |
|
154 | |||
155 | def logstate(self): |
|
155 | def logstate(self): | |
156 | """Print a status message about the logger.""" |
|
156 | """Print a status message about the logger.""" | |
157 | if self.logfile is None: |
|
157 | if self.logfile is None: | |
158 | print 'Logging has not been activated.' |
|
158 | print 'Logging has not been activated.' | |
159 | else: |
|
159 | else: | |
160 | state = self.log_active and 'active' or 'temporarily suspended' |
|
160 | state = self.log_active and 'active' or 'temporarily suspended' | |
161 | print 'Filename :',self.logfname |
|
161 | print 'Filename :',self.logfname | |
162 | print 'Mode :',self.logmode |
|
162 | print 'Mode :',self.logmode | |
163 | print 'Output logging :',self.log_output |
|
163 | print 'Output logging :',self.log_output | |
164 | print 'Raw input log :',self.log_raw_input |
|
164 | print 'Raw input log :',self.log_raw_input | |
165 | print 'Timestamping :',self.timestamp |
|
165 | print 'Timestamping :',self.timestamp | |
166 | print 'State :',state |
|
166 | print 'State :',state | |
167 |
|
167 | |||
168 | def log(self, line_mod, line_ori): |
|
168 | def log(self, line_mod, line_ori): | |
169 | """Write the sources to a log. |
|
169 | """Write the sources to a log. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - line_mod: possibly modified input, such as the transformations made |
|
173 | - line_mod: possibly modified input, such as the transformations made | |
174 | by input prefilters or input handlers of various kinds. This should |
|
174 | by input prefilters or input handlers of various kinds. This should | |
175 | always be valid Python. |
|
175 | always be valid Python. | |
176 |
|
176 | |||
177 | - line_ori: unmodified input line from the user. This is not |
|
177 | - line_ori: unmodified input line from the user. This is not | |
178 | necessarily valid Python. |
|
178 | necessarily valid Python. | |
179 | """ |
|
179 | """ | |
180 |
|
180 | |||
181 | # Write the log line, but decide which one according to the |
|
181 | # Write the log line, but decide which one according to the | |
182 | # log_raw_input flag, set when the log is started. |
|
182 | # log_raw_input flag, set when the log is started. | |
183 | if self.log_raw_input: |
|
183 | if self.log_raw_input: | |
184 | self.log_write(line_ori) |
|
184 | self.log_write(line_ori) | |
185 | else: |
|
185 | else: | |
186 | self.log_write(line_mod) |
|
186 | self.log_write(line_mod) | |
187 |
|
187 | |||
188 | def log_write(self, data, kind='input'): |
|
188 | def log_write(self, data, kind='input'): | |
189 | """Write data to the log file, if active""" |
|
189 | """Write data to the log file, if active""" | |
190 |
|
190 | |||
191 | #print 'data: %r' % data # dbg |
|
191 | #print 'data: %r' % data # dbg | |
192 | if self.log_active and data: |
|
192 | if self.log_active and data: | |
193 | write = self.logfile.write |
|
193 | write = self.logfile.write | |
194 | if kind=='input': |
|
194 | if kind=='input': | |
195 | if self.timestamp: |
|
195 | if self.timestamp: | |
196 | write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n', |
|
196 | write(str_to_unicode(time.strftime('# %a, %d %b %Y %H:%M:%S\n', | |
197 | time.localtime()))) |
|
197 | time.localtime()))) | |
198 | write(data) |
|
198 | write(data) | |
199 | elif kind=='output' and self.log_output: |
|
199 | elif kind=='output' and self.log_output: | |
200 | odata = u'\n'.join([u'#[Out]# %s' % s |
|
200 | odata = u'\n'.join([u'#[Out]# %s' % s | |
201 | for s in data.splitlines()]) |
|
201 | for s in data.splitlines()]) | |
202 | write(u'%s\n' % odata) |
|
202 | write(u'%s\n' % odata) | |
203 | self.logfile.flush() |
|
203 | self.logfile.flush() | |
204 |
|
204 | |||
205 | def logstop(self): |
|
205 | def logstop(self): | |
206 | """Fully stop logging and close log file. |
|
206 | """Fully stop logging and close log file. | |
207 |
|
207 | |||
208 | In order to start logging again, a new logstart() call needs to be |
|
208 | In order to start logging again, a new logstart() call needs to be | |
209 | made, possibly (though not necessarily) with a new filename, mode and |
|
209 | made, possibly (though not necessarily) with a new filename, mode and | |
210 | other options.""" |
|
210 | other options.""" | |
211 |
|
211 | |||
212 | if self.logfile is not None: |
|
212 | if self.logfile is not None: | |
213 | self.logfile.close() |
|
213 | self.logfile.close() | |
214 | self.logfile = None |
|
214 | self.logfile = None | |
215 | else: |
|
215 | else: | |
216 | print "Logging hadn't been started." |
|
216 | print "Logging hadn't been started." | |
217 | self.log_active = False |
|
217 | self.log_active = False | |
218 |
|
218 | |||
219 | # For backwards compatibility, in case anyone was using this. |
|
219 | # For backwards compatibility, in case anyone was using this. | |
220 | close_log = logstop |
|
220 | close_log = logstop |
@@ -1,617 +1,617 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Stdlib |
|
17 | # Stdlib | |
18 | import os |
|
18 | import os | |
19 | import re |
|
19 | import re | |
20 | import sys |
|
20 | import sys | |
21 | import types |
|
21 | import types | |
22 | from getopt import getopt, GetoptError |
|
22 | from getopt import getopt, GetoptError | |
23 |
|
23 | |||
24 | # Our own |
|
24 | # Our own | |
25 | from IPython.config.configurable import Configurable |
|
25 | from IPython.config.configurable import Configurable | |
26 | from IPython.core import oinspect |
|
26 | from IPython.core import oinspect | |
27 | from IPython.core.error import UsageError |
|
27 | from IPython.core.error import UsageError | |
28 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
28 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 | |
29 | from IPython.external.decorator import decorator |
|
29 | from IPython.external.decorator import decorator | |
30 | from IPython.utils.ipstruct import Struct |
|
30 | from IPython.utils.ipstruct import Struct | |
31 | from IPython.utils.process import arg_split |
|
31 | from IPython.utils.process import arg_split | |
32 | from IPython.utils.text import dedent |
|
32 | from IPython.utils.text import dedent | |
33 | from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits |
|
33 | from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits | |
34 | from IPython.utils.warn import error, warn |
|
34 | from IPython.utils.warn import error, warn | |
35 |
|
35 | |||
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 | # Globals |
|
37 | # Globals | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
40 | # A dict we'll use for each class that has magics, used as temporary storage to | |
41 | # pass information between the @line/cell_magic method decorators and the |
|
41 | # pass information between the @line/cell_magic method decorators and the | |
42 | # @magics_class class decorator, because the method decorators have no |
|
42 | # @magics_class class decorator, because the method decorators have no | |
43 | # access to the class when they run. See for more details: |
|
43 | # access to the class when they run. See for more details: | |
44 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
44 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class | |
45 |
|
45 | |||
46 | magics = dict(line={}, cell={}) |
|
46 | magics = dict(line={}, cell={}) | |
47 |
|
47 | |||
48 | magic_kinds = ('line', 'cell') |
|
48 | magic_kinds = ('line', 'cell') | |
49 | magic_spec = ('line', 'cell', 'line_cell') |
|
49 | magic_spec = ('line', 'cell', 'line_cell') | |
50 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
50 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) | |
51 |
|
51 | |||
52 | #----------------------------------------------------------------------------- |
|
52 | #----------------------------------------------------------------------------- | |
53 | # Utility classes and functions |
|
53 | # Utility classes and functions | |
54 | #----------------------------------------------------------------------------- |
|
54 | #----------------------------------------------------------------------------- | |
55 |
|
55 | |||
56 | class Bunch: pass |
|
56 | class Bunch: pass | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | def on_off(tag): |
|
59 | def on_off(tag): | |
60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
60 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
61 | return ['OFF','ON'][tag] |
|
61 | return ['OFF','ON'][tag] | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def compress_dhist(dh): |
|
64 | def compress_dhist(dh): | |
65 | """Compress a directory history into a new one with at most 20 entries. |
|
65 | """Compress a directory history into a new one with at most 20 entries. | |
66 |
|
66 | |||
67 | Return a new list made from the first and last 10 elements of dhist after |
|
67 | Return a new list made from the first and last 10 elements of dhist after | |
68 | removal of duplicates. |
|
68 | removal of duplicates. | |
69 | """ |
|
69 | """ | |
70 | head, tail = dh[:-10], dh[-10:] |
|
70 | head, tail = dh[:-10], dh[-10:] | |
71 |
|
71 | |||
72 | newhead = [] |
|
72 | newhead = [] | |
73 | done = set() |
|
73 | done = set() | |
74 | for h in head: |
|
74 | for h in head: | |
75 | if h in done: |
|
75 | if h in done: | |
76 | continue |
|
76 | continue | |
77 | newhead.append(h) |
|
77 | newhead.append(h) | |
78 | done.add(h) |
|
78 | done.add(h) | |
79 |
|
79 | |||
80 | return newhead + tail |
|
80 | return newhead + tail | |
81 |
|
81 | |||
82 |
|
82 | |||
83 | def needs_local_scope(func): |
|
83 | def needs_local_scope(func): | |
84 | """Decorator to mark magic functions which need to local scope to run.""" |
|
84 | """Decorator to mark magic functions which need to local scope to run.""" | |
85 | func.needs_local_scope = True |
|
85 | func.needs_local_scope = True | |
86 | return func |
|
86 | return func | |
87 |
|
87 | |||
88 | #----------------------------------------------------------------------------- |
|
88 | #----------------------------------------------------------------------------- | |
89 | # Class and method decorators for registering magics |
|
89 | # Class and method decorators for registering magics | |
90 | #----------------------------------------------------------------------------- |
|
90 | #----------------------------------------------------------------------------- | |
91 |
|
91 | |||
92 | def magics_class(cls): |
|
92 | def magics_class(cls): | |
93 | """Class decorator for all subclasses of the main Magics class. |
|
93 | """Class decorator for all subclasses of the main Magics class. | |
94 |
|
94 | |||
95 | Any class that subclasses Magics *must* also apply this decorator, to |
|
95 | Any class that subclasses Magics *must* also apply this decorator, to | |
96 | ensure that all the methods that have been decorated as line/cell magics |
|
96 | ensure that all the methods that have been decorated as line/cell magics | |
97 | get correctly registered in the class instance. This is necessary because |
|
97 | get correctly registered in the class instance. This is necessary because | |
98 | when method decorators run, the class does not exist yet, so they |
|
98 | when method decorators run, the class does not exist yet, so they | |
99 | temporarily store their information into a module global. Application of |
|
99 | temporarily store their information into a module global. Application of | |
100 | this class decorator copies that global data to the class instance and |
|
100 | this class decorator copies that global data to the class instance and | |
101 | clears the global. |
|
101 | clears the global. | |
102 |
|
102 | |||
103 | Obviously, this mechanism is not thread-safe, which means that the |
|
103 | Obviously, this mechanism is not thread-safe, which means that the | |
104 | *creation* of subclasses of Magic should only be done in a single-thread |
|
104 | *creation* of subclasses of Magic should only be done in a single-thread | |
105 | context. Instantiation of the classes has no restrictions. Given that |
|
105 | context. Instantiation of the classes has no restrictions. Given that | |
106 | these classes are typically created at IPython startup time and before user |
|
106 | these classes are typically created at IPython startup time and before user | |
107 | application code becomes active, in practice this should not pose any |
|
107 | application code becomes active, in practice this should not pose any | |
108 | problems. |
|
108 | problems. | |
109 | """ |
|
109 | """ | |
110 | cls.registered = True |
|
110 | cls.registered = True | |
111 | cls.magics = dict(line = magics['line'], |
|
111 | cls.magics = dict(line = magics['line'], | |
112 | cell = magics['cell']) |
|
112 | cell = magics['cell']) | |
113 | magics['line'] = {} |
|
113 | magics['line'] = {} | |
114 | magics['cell'] = {} |
|
114 | magics['cell'] = {} | |
115 | return cls |
|
115 | return cls | |
116 |
|
116 | |||
117 |
|
117 | |||
118 | def record_magic(dct, magic_kind, magic_name, func): |
|
118 | def record_magic(dct, magic_kind, magic_name, func): | |
119 | """Utility function to store a function as a magic of a specific kind. |
|
119 | """Utility function to store a function as a magic of a specific kind. | |
120 |
|
120 | |||
121 | Parameters |
|
121 | Parameters | |
122 | ---------- |
|
122 | ---------- | |
123 | dct : dict |
|
123 | dct : dict | |
124 | A dictionary with 'line' and 'cell' subdicts. |
|
124 | A dictionary with 'line' and 'cell' subdicts. | |
125 |
|
125 | |||
126 | magic_kind : str |
|
126 | magic_kind : str | |
127 | Kind of magic to be stored. |
|
127 | Kind of magic to be stored. | |
128 |
|
128 | |||
129 | magic_name : str |
|
129 | magic_name : str | |
130 | Key to store the magic as. |
|
130 | Key to store the magic as. | |
131 |
|
131 | |||
132 | func : function |
|
132 | func : function | |
133 | Callable object to store. |
|
133 | Callable object to store. | |
134 | """ |
|
134 | """ | |
135 | if magic_kind == 'line_cell': |
|
135 | if magic_kind == 'line_cell': | |
136 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
136 | dct['line'][magic_name] = dct['cell'][magic_name] = func | |
137 | else: |
|
137 | else: | |
138 | dct[magic_kind][magic_name] = func |
|
138 | dct[magic_kind][magic_name] = func | |
139 |
|
139 | |||
140 |
|
140 | |||
141 | def validate_type(magic_kind): |
|
141 | def validate_type(magic_kind): | |
142 | """Ensure that the given magic_kind is valid. |
|
142 | """Ensure that the given magic_kind is valid. | |
143 |
|
143 | |||
144 | Check that the given magic_kind is one of the accepted spec types (stored |
|
144 | Check that the given magic_kind is one of the accepted spec types (stored | |
145 | in the global `magic_spec`), raise ValueError otherwise. |
|
145 | in the global `magic_spec`), raise ValueError otherwise. | |
146 | """ |
|
146 | """ | |
147 | if magic_kind not in magic_spec: |
|
147 | if magic_kind not in magic_spec: | |
148 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
148 | raise ValueError('magic_kind must be one of %s, %s given' % | |
149 | magic_kinds, magic_kind) |
|
149 | magic_kinds, magic_kind) | |
150 |
|
150 | |||
151 |
|
151 | |||
152 | # The docstrings for the decorator below will be fairly similar for the two |
|
152 | # The docstrings for the decorator below will be fairly similar for the two | |
153 | # types (method and function), so we generate them here once and reuse the |
|
153 | # types (method and function), so we generate them here once and reuse the | |
154 | # templates below. |
|
154 | # templates below. | |
155 | _docstring_template = \ |
|
155 | _docstring_template = \ | |
156 | """Decorate the given {0} as {1} magic. |
|
156 | """Decorate the given {0} as {1} magic. | |
157 |
|
157 | |||
158 | The decorator can be used with or without arguments, as follows. |
|
158 | The decorator can be used with or without arguments, as follows. | |
159 |
|
159 | |||
160 | i) without arguments: it will create a {1} magic named as the {0} being |
|
160 | i) without arguments: it will create a {1} magic named as the {0} being | |
161 | decorated:: |
|
161 | decorated:: | |
162 |
|
162 | |||
163 | @deco |
|
163 | @deco | |
164 | def foo(...) |
|
164 | def foo(...) | |
165 |
|
165 | |||
166 | will create a {1} magic named `foo`. |
|
166 | will create a {1} magic named `foo`. | |
167 |
|
167 | |||
168 | ii) with one string argument: which will be used as the actual name of the |
|
168 | ii) with one string argument: which will be used as the actual name of the | |
169 | resulting magic:: |
|
169 | resulting magic:: | |
170 |
|
170 | |||
171 | @deco('bar') |
|
171 | @deco('bar') | |
172 | def foo(...) |
|
172 | def foo(...) | |
173 |
|
173 | |||
174 | will create a {1} magic named `bar`. |
|
174 | will create a {1} magic named `bar`. | |
175 | """ |
|
175 | """ | |
176 |
|
176 | |||
177 | # These two are decorator factories. While they are conceptually very similar, |
|
177 | # These two are decorator factories. While they are conceptually very similar, | |
178 | # there are enough differences in the details that it's simpler to have them |
|
178 | # there are enough differences in the details that it's simpler to have them | |
179 | # written as completely standalone functions rather than trying to share code |
|
179 | # written as completely standalone functions rather than trying to share code | |
180 | # and make a single one with convoluted logic. |
|
180 | # and make a single one with convoluted logic. | |
181 |
|
181 | |||
182 | def _method_magic_marker(magic_kind): |
|
182 | def _method_magic_marker(magic_kind): | |
183 | """Decorator factory for methods in Magics subclasses. |
|
183 | """Decorator factory for methods in Magics subclasses. | |
184 | """ |
|
184 | """ | |
185 |
|
185 | |||
186 | validate_type(magic_kind) |
|
186 | validate_type(magic_kind) | |
187 |
|
187 | |||
188 | # This is a closure to capture the magic_kind. We could also use a class, |
|
188 | # This is a closure to capture the magic_kind. We could also use a class, | |
189 | # but it's overkill for just that one bit of state. |
|
189 | # but it's overkill for just that one bit of state. | |
190 | def magic_deco(arg): |
|
190 | def magic_deco(arg): | |
191 | call = lambda f, *a, **k: f(*a, **k) |
|
191 | call = lambda f, *a, **k: f(*a, **k) | |
192 |
|
192 | |||
193 | if callable(arg): |
|
193 | if callable(arg): | |
194 | # "Naked" decorator call (just @foo, no args) |
|
194 | # "Naked" decorator call (just @foo, no args) | |
195 | func = arg |
|
195 | func = arg | |
196 | name = func.func_name |
|
196 | name = func.func_name | |
197 | retval = decorator(call, func) |
|
197 | retval = decorator(call, func) | |
198 | record_magic(magics, magic_kind, name, name) |
|
198 | record_magic(magics, magic_kind, name, name) | |
199 | elif isinstance(arg, basestring): |
|
199 | elif isinstance(arg, basestring): | |
200 | # Decorator called with arguments (@foo('bar')) |
|
200 | # Decorator called with arguments (@foo('bar')) | |
201 | name = arg |
|
201 | name = arg | |
202 | def mark(func, *a, **kw): |
|
202 | def mark(func, *a, **kw): | |
203 | record_magic(magics, magic_kind, name, func.func_name) |
|
203 | record_magic(magics, magic_kind, name, func.func_name) | |
204 | return decorator(call, func) |
|
204 | return decorator(call, func) | |
205 | retval = mark |
|
205 | retval = mark | |
206 | else: |
|
206 | else: | |
207 | raise TypeError("Decorator can only be called with " |
|
207 | raise TypeError("Decorator can only be called with " | |
208 | "string or function") |
|
208 | "string or function") | |
209 | return retval |
|
209 | return retval | |
210 |
|
210 | |||
211 | # Ensure the resulting decorator has a usable docstring |
|
211 | # Ensure the resulting decorator has a usable docstring | |
212 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
212 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) | |
213 | return magic_deco |
|
213 | return magic_deco | |
214 |
|
214 | |||
215 |
|
215 | |||
216 | def _function_magic_marker(magic_kind): |
|
216 | def _function_magic_marker(magic_kind): | |
217 | """Decorator factory for standalone functions. |
|
217 | """Decorator factory for standalone functions. | |
218 | """ |
|
218 | """ | |
219 | validate_type(magic_kind) |
|
219 | validate_type(magic_kind) | |
220 |
|
220 | |||
221 | # This is a closure to capture the magic_kind. We could also use a class, |
|
221 | # This is a closure to capture the magic_kind. We could also use a class, | |
222 | # but it's overkill for just that one bit of state. |
|
222 | # but it's overkill for just that one bit of state. | |
223 | def magic_deco(arg): |
|
223 | def magic_deco(arg): | |
224 | call = lambda f, *a, **k: f(*a, **k) |
|
224 | call = lambda f, *a, **k: f(*a, **k) | |
225 |
|
225 | |||
226 | # Find get_ipython() in the caller's namespace |
|
226 | # Find get_ipython() in the caller's namespace | |
227 | caller = sys._getframe(1) |
|
227 | caller = sys._getframe(1) | |
228 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
228 | for ns in ['f_locals', 'f_globals', 'f_builtins']: | |
229 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
229 | get_ipython = getattr(caller, ns).get('get_ipython') | |
230 | if get_ipython is not None: |
|
230 | if get_ipython is not None: | |
231 | break |
|
231 | break | |
232 | else: |
|
232 | else: | |
233 | raise NameError('Decorator can only run in context where ' |
|
233 | raise NameError('Decorator can only run in context where ' | |
234 | '`get_ipython` exists') |
|
234 | '`get_ipython` exists') | |
235 |
|
235 | |||
236 | ip = get_ipython() |
|
236 | ip = get_ipython() | |
237 |
|
237 | |||
238 | if callable(arg): |
|
238 | if callable(arg): | |
239 | # "Naked" decorator call (just @foo, no args) |
|
239 | # "Naked" decorator call (just @foo, no args) | |
240 | func = arg |
|
240 | func = arg | |
241 | name = func.func_name |
|
241 | name = func.func_name | |
242 | ip.register_magic_function(func, magic_kind, name) |
|
242 | ip.register_magic_function(func, magic_kind, name) | |
243 | retval = decorator(call, func) |
|
243 | retval = decorator(call, func) | |
244 | elif isinstance(arg, basestring): |
|
244 | elif isinstance(arg, basestring): | |
245 | # Decorator called with arguments (@foo('bar')) |
|
245 | # Decorator called with arguments (@foo('bar')) | |
246 | name = arg |
|
246 | name = arg | |
247 | def mark(func, *a, **kw): |
|
247 | def mark(func, *a, **kw): | |
248 | ip.register_magic_function(func, magic_kind, name) |
|
248 | ip.register_magic_function(func, magic_kind, name) | |
249 | return decorator(call, func) |
|
249 | return decorator(call, func) | |
250 | retval = mark |
|
250 | retval = mark | |
251 | else: |
|
251 | else: | |
252 | raise TypeError("Decorator can only be called with " |
|
252 | raise TypeError("Decorator can only be called with " | |
253 | "string or function") |
|
253 | "string or function") | |
254 | return retval |
|
254 | return retval | |
255 |
|
255 | |||
256 | # Ensure the resulting decorator has a usable docstring |
|
256 | # Ensure the resulting decorator has a usable docstring | |
257 | ds = _docstring_template.format('function', magic_kind) |
|
257 | ds = _docstring_template.format('function', magic_kind) | |
258 |
|
258 | |||
259 | ds += dedent(""" |
|
259 | ds += dedent(""" | |
260 | Note: this decorator can only be used in a context where IPython is already |
|
260 | Note: this decorator can only be used in a context where IPython is already | |
261 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
261 | active, so that the `get_ipython()` call succeeds. You can therefore use | |
262 | it in your startup files loaded after IPython initializes, but *not* in the |
|
262 | it in your startup files loaded after IPython initializes, but *not* in the | |
263 | IPython configuration file itself, which is executed before IPython is |
|
263 | IPython configuration file itself, which is executed before IPython is | |
264 | fully up and running. Any file located in the `startup` subdirectory of |
|
264 | fully up and running. Any file located in the `startup` subdirectory of | |
265 | your configuration profile will be OK in this sense. |
|
265 | your configuration profile will be OK in this sense. | |
266 | """) |
|
266 | """) | |
267 |
|
267 | |||
268 | magic_deco.__doc__ = ds |
|
268 | magic_deco.__doc__ = ds | |
269 | return magic_deco |
|
269 | return magic_deco | |
270 |
|
270 | |||
271 |
|
271 | |||
272 | # Create the actual decorators for public use |
|
272 | # Create the actual decorators for public use | |
273 |
|
273 | |||
274 | # These three are used to decorate methods in class definitions |
|
274 | # These three are used to decorate methods in class definitions | |
275 | line_magic = _method_magic_marker('line') |
|
275 | line_magic = _method_magic_marker('line') | |
276 | cell_magic = _method_magic_marker('cell') |
|
276 | cell_magic = _method_magic_marker('cell') | |
277 | line_cell_magic = _method_magic_marker('line_cell') |
|
277 | line_cell_magic = _method_magic_marker('line_cell') | |
278 |
|
278 | |||
279 | # These three decorate standalone functions and perform the decoration |
|
279 | # These three decorate standalone functions and perform the decoration | |
280 | # immediately. They can only run where get_ipython() works |
|
280 | # immediately. They can only run where get_ipython() works | |
281 | register_line_magic = _function_magic_marker('line') |
|
281 | register_line_magic = _function_magic_marker('line') | |
282 | register_cell_magic = _function_magic_marker('cell') |
|
282 | register_cell_magic = _function_magic_marker('cell') | |
283 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
283 | register_line_cell_magic = _function_magic_marker('line_cell') | |
284 |
|
284 | |||
285 | #----------------------------------------------------------------------------- |
|
285 | #----------------------------------------------------------------------------- | |
286 | # Core Magic classes |
|
286 | # Core Magic classes | |
287 | #----------------------------------------------------------------------------- |
|
287 | #----------------------------------------------------------------------------- | |
288 |
|
288 | |||
289 | class MagicsManager(Configurable): |
|
289 | class MagicsManager(Configurable): | |
290 | """Object that handles all magic-related functionality for IPython. |
|
290 | """Object that handles all magic-related functionality for IPython. | |
291 | """ |
|
291 | """ | |
292 | # Non-configurable class attributes |
|
292 | # Non-configurable class attributes | |
293 |
|
293 | |||
294 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
294 | # A two-level dict, first keyed by magic type, then by magic function, and | |
295 | # holding the actual callable object as value. This is the dict used for |
|
295 | # holding the actual callable object as value. This is the dict used for | |
296 | # magic function dispatch |
|
296 | # magic function dispatch | |
297 | magics = Dict |
|
297 | magics = Dict | |
298 |
|
298 | |||
299 | # A registry of the original objects that we've been given holding magics. |
|
299 | # A registry of the original objects that we've been given holding magics. | |
300 | registry = Dict |
|
300 | registry = Dict | |
301 |
|
301 | |||
302 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
302 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
303 |
|
303 | |||
304 | auto_magic = Bool(True, config=True, help= |
|
304 | auto_magic = Bool(True, config=True, help= | |
305 | "Automatically call line magics without requiring explicit % prefix") |
|
305 | "Automatically call line magics without requiring explicit % prefix") | |
306 |
|
306 | |||
307 | _auto_status = [ |
|
307 | _auto_status = [ | |
308 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
308 | 'Automagic is OFF, % prefix IS needed for line magics.', | |
309 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
309 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] | |
310 |
|
310 | |||
311 | user_magics = Instance('IPython.core.magics.UserMagics') |
|
311 | user_magics = Instance('IPython.core.magics.UserMagics') | |
312 |
|
312 | |||
313 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
313 | def __init__(self, shell=None, config=None, user_magics=None, **traits): | |
314 |
|
314 | |||
315 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
315 | super(MagicsManager, self).__init__(shell=shell, config=config, | |
316 | user_magics=user_magics, **traits) |
|
316 | user_magics=user_magics, **traits) | |
317 | self.magics = dict(line={}, cell={}) |
|
317 | self.magics = dict(line={}, cell={}) | |
318 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
318 | # Let's add the user_magics to the registry for uniformity, so *all* | |
319 | # registered magic containers can be found there. |
|
319 | # registered magic containers can be found there. | |
320 | self.registry[user_magics.__class__.__name__] = user_magics |
|
320 | self.registry[user_magics.__class__.__name__] = user_magics | |
321 |
|
321 | |||
322 | def auto_status(self): |
|
322 | def auto_status(self): | |
323 | """Return descriptive string with automagic status.""" |
|
323 | """Return descriptive string with automagic status.""" | |
324 | return self._auto_status[self.auto_magic] |
|
324 | return self._auto_status[self.auto_magic] | |
325 |
|
325 | |||
326 | def lsmagic_info(self): |
|
326 | def lsmagic_info(self): | |
327 | magic_list = [] |
|
327 | magic_list = [] | |
328 | for m_type in self.magics : |
|
328 | for m_type in self.magics : | |
329 | for m_name,mgc in self.magics[m_type].items(): |
|
329 | for m_name,mgc in self.magics[m_type].items(): | |
330 | try : |
|
330 | try : | |
331 | magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__}) |
|
331 | magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__}) | |
332 | except AttributeError : |
|
332 | except AttributeError : | |
333 | magic_list.append({'name':m_name,'type':m_type,'class':'Other'}) |
|
333 | magic_list.append({'name':m_name,'type':m_type,'class':'Other'}) | |
334 | return magic_list |
|
334 | return magic_list | |
335 |
|
335 | |||
336 | def lsmagic(self): |
|
336 | def lsmagic(self): | |
337 | """Return a dict of currently available magic functions. |
|
337 | """Return a dict of currently available magic functions. | |
338 |
|
338 | |||
339 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
339 | The return dict has the keys 'line' and 'cell', corresponding to the | |
340 | two types of magics we support. Each value is a list of names. |
|
340 | two types of magics we support. Each value is a list of names. | |
341 | """ |
|
341 | """ | |
342 | return self.magics |
|
342 | return self.magics | |
343 |
|
343 | |||
344 | def lsmagic_docs(self, brief=False, missing=''): |
|
344 | def lsmagic_docs(self, brief=False, missing=''): | |
345 | """Return dict of documentation of magic functions. |
|
345 | """Return dict of documentation of magic functions. | |
346 |
|
346 | |||
347 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
347 | The return dict has the keys 'line' and 'cell', corresponding to the | |
348 | two types of magics we support. Each value is a dict keyed by magic |
|
348 | two types of magics we support. Each value is a dict keyed by magic | |
349 | name whose value is the function docstring. If a docstring is |
|
349 | name whose value is the function docstring. If a docstring is | |
350 | unavailable, the value of `missing` is used instead. |
|
350 | unavailable, the value of `missing` is used instead. | |
351 |
|
351 | |||
352 | If brief is True, only the first line of each docstring will be returned. |
|
352 | If brief is True, only the first line of each docstring will be returned. | |
353 | """ |
|
353 | """ | |
354 | docs = {} |
|
354 | docs = {} | |
355 | for m_type in self.magics: |
|
355 | for m_type in self.magics: | |
356 | m_docs = {} |
|
356 | m_docs = {} | |
357 | for m_name, m_func in self.magics[m_type].iteritems(): |
|
357 | for m_name, m_func in self.magics[m_type].iteritems(): | |
358 | if m_func.__doc__: |
|
358 | if m_func.__doc__: | |
359 | if brief: |
|
359 | if brief: | |
360 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
360 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] | |
361 | else: |
|
361 | else: | |
362 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
362 | m_docs[m_name] = m_func.__doc__.rstrip() | |
363 | else: |
|
363 | else: | |
364 | m_docs[m_name] = missing |
|
364 | m_docs[m_name] = missing | |
365 | docs[m_type] = m_docs |
|
365 | docs[m_type] = m_docs | |
366 | return docs |
|
366 | return docs | |
367 |
|
367 | |||
368 | def register(self, *magic_objects): |
|
368 | def register(self, *magic_objects): | |
369 | """Register one or more instances of Magics. |
|
369 | """Register one or more instances of Magics. | |
370 |
|
370 | |||
371 | Take one or more classes or instances of classes that subclass the main |
|
371 | Take one or more classes or instances of classes that subclass the main | |
372 | `core.Magic` class, and register them with IPython to use the magic |
|
372 | `core.Magic` class, and register them with IPython to use the magic | |
373 | functions they provide. The registration process will then ensure that |
|
373 | functions they provide. The registration process will then ensure that | |
374 | any methods that have decorated to provide line and/or cell magics will |
|
374 | any methods that have decorated to provide line and/or cell magics will | |
375 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
375 | be recognized with the `%x`/`%%x` syntax as a line/cell magic | |
376 | respectively. |
|
376 | respectively. | |
377 |
|
377 | |||
378 | If classes are given, they will be instantiated with the default |
|
378 | If classes are given, they will be instantiated with the default | |
379 | constructor. If your classes need a custom constructor, you should |
|
379 | constructor. If your classes need a custom constructor, you should | |
380 | instanitate them first and pass the instance. |
|
380 | instanitate them first and pass the instance. | |
381 |
|
381 | |||
382 | The provided arguments can be an arbitrary mix of classes and instances. |
|
382 | The provided arguments can be an arbitrary mix of classes and instances. | |
383 |
|
383 | |||
384 | Parameters |
|
384 | Parameters | |
385 | ---------- |
|
385 | ---------- | |
386 | magic_objects : one or more classes or instances |
|
386 | magic_objects : one or more classes or instances | |
387 | """ |
|
387 | """ | |
388 | # Start by validating them to ensure they have all had their magic |
|
388 | # Start by validating them to ensure they have all had their magic | |
389 | # methods registered at the instance level |
|
389 | # methods registered at the instance level | |
390 | for m in magic_objects: |
|
390 | for m in magic_objects: | |
391 | if not m.registered: |
|
391 | if not m.registered: | |
392 | raise ValueError("Class of magics %r was constructed without " |
|
392 | raise ValueError("Class of magics %r was constructed without " | |
393 | "the @register_magics class decorator") |
|
393 | "the @register_magics class decorator") | |
394 | if type(m) in (type, MetaHasTraits): |
|
394 | if type(m) in (type, MetaHasTraits): | |
395 | # If we're given an uninstantiated class |
|
395 | # If we're given an uninstantiated class | |
396 | m = m(shell=self.shell) |
|
396 | m = m(shell=self.shell) | |
397 |
|
397 | |||
398 | # Now that we have an instance, we can register it and update the |
|
398 | # Now that we have an instance, we can register it and update the | |
399 | # table of callables |
|
399 | # table of callables | |
400 | self.registry[m.__class__.__name__] = m |
|
400 | self.registry[m.__class__.__name__] = m | |
401 | for mtype in magic_kinds: |
|
401 | for mtype in magic_kinds: | |
402 | self.magics[mtype].update(m.magics[mtype]) |
|
402 | self.magics[mtype].update(m.magics[mtype]) | |
403 |
|
403 | |||
404 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
404 | def register_function(self, func, magic_kind='line', magic_name=None): | |
405 | """Expose a standalone function as magic function for IPython. |
|
405 | """Expose a standalone function as magic function for IPython. | |
406 |
|
406 | |||
407 | This will create an IPython magic (line, cell or both) from a |
|
407 | This will create an IPython magic (line, cell or both) from a | |
408 | standalone function. The functions should have the following |
|
408 | standalone function. The functions should have the following | |
409 | signatures: |
|
409 | signatures: | |
410 |
|
410 | |||
411 | * For line magics: `def f(line)` |
|
411 | * For line magics: `def f(line)` | |
412 | * For cell magics: `def f(line, cell)` |
|
412 | * For cell magics: `def f(line, cell)` | |
413 | * For a function that does both: `def f(line, cell=None)` |
|
413 | * For a function that does both: `def f(line, cell=None)` | |
414 |
|
414 | |||
415 | In the latter case, the function will be called with `cell==None` when |
|
415 | In the latter case, the function will be called with `cell==None` when | |
416 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
416 | invoked as `%f`, and with cell as a string when invoked as `%%f`. | |
417 |
|
417 | |||
418 | Parameters |
|
418 | Parameters | |
419 | ---------- |
|
419 | ---------- | |
420 | func : callable |
|
420 | func : callable | |
421 | Function to be registered as a magic. |
|
421 | Function to be registered as a magic. | |
422 |
|
422 | |||
423 | magic_kind : str |
|
423 | magic_kind : str | |
424 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
424 | Kind of magic, one of 'line', 'cell' or 'line_cell' | |
425 |
|
425 | |||
426 | magic_name : optional str |
|
426 | magic_name : optional str | |
427 | If given, the name the magic will have in the IPython namespace. By |
|
427 | If given, the name the magic will have in the IPython namespace. By | |
428 | default, the name of the function itself is used. |
|
428 | default, the name of the function itself is used. | |
429 | """ |
|
429 | """ | |
430 |
|
430 | |||
431 | # Create the new method in the user_magics and register it in the |
|
431 | # Create the new method in the user_magics and register it in the | |
432 | # global table |
|
432 | # global table | |
433 | validate_type(magic_kind) |
|
433 | validate_type(magic_kind) | |
434 | magic_name = func.func_name if magic_name is None else magic_name |
|
434 | magic_name = func.func_name if magic_name is None else magic_name | |
435 | setattr(self.user_magics, magic_name, func) |
|
435 | setattr(self.user_magics, magic_name, func) | |
436 | record_magic(self.magics, magic_kind, magic_name, func) |
|
436 | record_magic(self.magics, magic_kind, magic_name, func) | |
437 |
|
437 | |||
438 | def define_magic(self, name, func): |
|
438 | def define_magic(self, name, func): | |
439 | """[Deprecated] Expose own function as magic function for IPython. |
|
439 | """[Deprecated] Expose own function as magic function for IPython. | |
440 |
|
440 | |||
441 | Example:: |
|
441 | Example:: | |
442 |
|
442 | |||
443 | def foo_impl(self, parameter_s=''): |
|
443 | def foo_impl(self, parameter_s=''): | |
444 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
444 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
445 | print 'Magic function. Passed parameter is between < >:' |
|
445 | print 'Magic function. Passed parameter is between < >:' | |
446 | print '<%s>' % parameter_s |
|
446 | print '<%s>' % parameter_s | |
447 | print 'The self object is:', self |
|
447 | print 'The self object is:', self | |
448 |
|
448 | |||
449 | ip.define_magic('foo',foo_impl) |
|
449 | ip.define_magic('foo',foo_impl) | |
450 | """ |
|
450 | """ | |
451 | meth = types.MethodType(func, self.user_magics) |
|
451 | meth = types.MethodType(func, self.user_magics) | |
452 | setattr(self.user_magics, name, meth) |
|
452 | setattr(self.user_magics, name, meth) | |
453 | record_magic(self.magics, 'line', name, meth) |
|
453 | record_magic(self.magics, 'line', name, meth) | |
454 |
|
454 | |||
455 | # Key base class that provides the central functionality for magics. |
|
455 | # Key base class that provides the central functionality for magics. | |
456 |
|
456 | |||
457 | class Magics(object): |
|
457 | class Magics(object): | |
458 | """Base class for implementing magic functions. |
|
458 | """Base class for implementing magic functions. | |
459 |
|
459 | |||
460 | Shell functions which can be reached as %function_name. All magic |
|
460 | Shell functions which can be reached as %function_name. All magic | |
461 | functions should accept a string, which they can parse for their own |
|
461 | functions should accept a string, which they can parse for their own | |
462 | needs. This can make some functions easier to type, eg `%cd ../` |
|
462 | needs. This can make some functions easier to type, eg `%cd ../` | |
463 | vs. `%cd("../")` |
|
463 | vs. `%cd("../")` | |
464 |
|
464 | |||
465 | Classes providing magic functions need to subclass this class, and they |
|
465 | Classes providing magic functions need to subclass this class, and they | |
466 | MUST: |
|
466 | MUST: | |
467 |
|
467 | |||
468 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
468 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate | |
469 | individual methods as magic functions, AND |
|
469 | individual methods as magic functions, AND | |
470 |
|
470 | |||
471 | - Use the class decorator `@magics_class` to ensure that the magic |
|
471 | - Use the class decorator `@magics_class` to ensure that the magic | |
472 | methods are properly registered at the instance level upon instance |
|
472 | methods are properly registered at the instance level upon instance | |
473 | initialization. |
|
473 | initialization. | |
474 |
|
474 | |||
475 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
475 | See :mod:`magic_functions` for examples of actual implementation classes. | |
476 | """ |
|
476 | """ | |
477 | # Dict holding all command-line options for each magic. |
|
477 | # Dict holding all command-line options for each magic. | |
478 | options_table = None |
|
478 | options_table = None | |
479 | # Dict for the mapping of magic names to methods, set by class decorator |
|
479 | # Dict for the mapping of magic names to methods, set by class decorator | |
480 | magics = None |
|
480 | magics = None | |
481 | # Flag to check that the class decorator was properly applied |
|
481 | # Flag to check that the class decorator was properly applied | |
482 | registered = False |
|
482 | registered = False | |
483 | # Instance of IPython shell |
|
483 | # Instance of IPython shell | |
484 | shell = None |
|
484 | shell = None | |
485 |
|
485 | |||
486 | def __init__(self, shell): |
|
486 | def __init__(self, shell): | |
487 | if not(self.__class__.registered): |
|
487 | if not(self.__class__.registered): | |
488 | raise ValueError('Magics subclass without registration - ' |
|
488 | raise ValueError('Magics subclass without registration - ' | |
489 | 'did you forget to apply @magics_class?') |
|
489 | 'did you forget to apply @magics_class?') | |
490 | self.shell = shell |
|
490 | self.shell = shell | |
491 | self.options_table = {} |
|
491 | self.options_table = {} | |
492 | # The method decorators are run when the instance doesn't exist yet, so |
|
492 | # The method decorators are run when the instance doesn't exist yet, so | |
493 | # they can only record the names of the methods they are supposed to |
|
493 | # they can only record the names of the methods they are supposed to | |
494 | # grab. Only now, that the instance exists, can we create the proper |
|
494 | # grab. Only now, that the instance exists, can we create the proper | |
495 | # mapping to bound methods. So we read the info off the original names |
|
495 | # mapping to bound methods. So we read the info off the original names | |
496 | # table and replace each method name by the actual bound method. |
|
496 | # table and replace each method name by the actual bound method. | |
497 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
497 | # But we mustn't clobber the *class* mapping, in case of multiple instances. | |
498 | class_magics = self.magics |
|
498 | class_magics = self.magics | |
499 | self.magics = {} |
|
499 | self.magics = {} | |
500 | for mtype in magic_kinds: |
|
500 | for mtype in magic_kinds: | |
501 | tab = self.magics[mtype] = {} |
|
501 | tab = self.magics[mtype] = {} | |
502 | cls_tab = class_magics[mtype] |
|
502 | cls_tab = class_magics[mtype] | |
503 | for magic_name, meth_name in cls_tab.iteritems(): |
|
503 | for magic_name, meth_name in cls_tab.iteritems(): | |
504 | if isinstance(meth_name, basestring): |
|
504 | if isinstance(meth_name, basestring): | |
505 | # it's a method name, grab it |
|
505 | # it's a method name, grab it | |
506 | tab[magic_name] = getattr(self, meth_name) |
|
506 | tab[magic_name] = getattr(self, meth_name) | |
507 | else: |
|
507 | else: | |
508 | # it's the real thing |
|
508 | # it's the real thing | |
509 | tab[magic_name] = meth_name |
|
509 | tab[magic_name] = meth_name | |
510 |
|
510 | |||
511 | def arg_err(self,func): |
|
511 | def arg_err(self,func): | |
512 | """Print docstring if incorrect arguments were passed""" |
|
512 | """Print docstring if incorrect arguments were passed""" | |
513 | print 'Error in arguments:' |
|
513 | print 'Error in arguments:' | |
514 | print oinspect.getdoc(func) |
|
514 | print oinspect.getdoc(func) | |
515 |
|
515 | |||
516 | def format_latex(self, strng): |
|
516 | def format_latex(self, strng): | |
517 | """Format a string for latex inclusion.""" |
|
517 | """Format a string for latex inclusion.""" | |
518 |
|
518 | |||
519 | # Characters that need to be escaped for latex: |
|
519 | # Characters that need to be escaped for latex: | |
520 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
520 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
521 | # Magic command names as headers: |
|
521 | # Magic command names as headers: | |
522 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
522 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
523 | re.MULTILINE) |
|
523 | re.MULTILINE) | |
524 | # Magic commands |
|
524 | # Magic commands | |
525 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
525 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
526 | re.MULTILINE) |
|
526 | re.MULTILINE) | |
527 | # Paragraph continue |
|
527 | # Paragraph continue | |
528 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
528 | par_re = re.compile(r'\\$',re.MULTILINE) | |
529 |
|
529 | |||
530 | # The "\n" symbol |
|
530 | # The "\n" symbol | |
531 | newline_re = re.compile(r'\\n') |
|
531 | newline_re = re.compile(r'\\n') | |
532 |
|
532 | |||
533 | # Now build the string for output: |
|
533 | # Now build the string for output: | |
534 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
534 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
535 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
535 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
536 | strng) |
|
536 | strng) | |
537 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
537 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
538 | strng = par_re.sub(r'\\\\',strng) |
|
538 | strng = par_re.sub(r'\\\\',strng) | |
539 | strng = escape_re.sub(r'\\\1',strng) |
|
539 | strng = escape_re.sub(r'\\\1',strng) | |
540 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
540 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
541 | return strng |
|
541 | return strng | |
542 |
|
542 | |||
543 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
543 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): | |
544 | """Parse options passed to an argument string. |
|
544 | """Parse options passed to an argument string. | |
545 |
|
545 | |||
546 | The interface is similar to that of getopt(), but it returns back a |
|
546 | The interface is similar to that of getopt(), but it returns back a | |
547 | Struct with the options as keys and the stripped argument string still |
|
547 | Struct with the options as keys and the stripped argument string still | |
548 | as a string. |
|
548 | as a string. | |
549 |
|
549 | |||
550 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
550 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
551 | This allows us to easily expand variables, glob files, quote |
|
551 | This allows us to easily expand variables, glob files, quote | |
552 | arguments, etc. |
|
552 | arguments, etc. | |
553 |
|
553 | |||
554 | Options: |
|
554 | Options: | |
555 | -mode: default 'string'. If given as 'list', the argument string is |
|
555 | -mode: default 'string'. If given as 'list', the argument string is | |
556 | returned as a list (split on whitespace) instead of a string. |
|
556 | returned as a list (split on whitespace) instead of a string. | |
557 |
|
557 | |||
558 | -list_all: put all option values in lists. Normally only options |
|
558 | -list_all: put all option values in lists. Normally only options | |
559 | appearing more than once are put in a list. |
|
559 | appearing more than once are put in a list. | |
560 |
|
560 | |||
561 | -posix (True): whether to split the input line in POSIX mode or not, |
|
561 | -posix (True): whether to split the input line in POSIX mode or not, | |
562 | as per the conventions outlined in the shlex module from the |
|
562 | as per the conventions outlined in the shlex module from the | |
563 | standard library.""" |
|
563 | standard library.""" | |
564 |
|
564 | |||
565 | # inject default options at the beginning of the input line |
|
565 | # inject default options at the beginning of the input line | |
566 | caller = sys._getframe(1).f_code.co_name |
|
566 | caller = sys._getframe(1).f_code.co_name | |
567 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
567 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
568 |
|
568 | |||
569 | mode = kw.get('mode','string') |
|
569 | mode = kw.get('mode','string') | |
570 | if mode not in ['string','list']: |
|
570 | if mode not in ['string','list']: | |
571 |
raise ValueError |
|
571 | raise ValueError('incorrect mode given: %s' % mode) | |
572 | # Get options |
|
572 | # Get options | |
573 | list_all = kw.get('list_all',0) |
|
573 | list_all = kw.get('list_all',0) | |
574 | posix = kw.get('posix', os.name == 'posix') |
|
574 | posix = kw.get('posix', os.name == 'posix') | |
575 | strict = kw.get('strict', True) |
|
575 | strict = kw.get('strict', True) | |
576 |
|
576 | |||
577 | # Check if we have more than one argument to warrant extra processing: |
|
577 | # Check if we have more than one argument to warrant extra processing: | |
578 | odict = {} # Dictionary with options |
|
578 | odict = {} # Dictionary with options | |
579 | args = arg_str.split() |
|
579 | args = arg_str.split() | |
580 | if len(args) >= 1: |
|
580 | if len(args) >= 1: | |
581 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
581 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
582 | # need to look for options |
|
582 | # need to look for options | |
583 | argv = arg_split(arg_str, posix, strict) |
|
583 | argv = arg_split(arg_str, posix, strict) | |
584 | # Do regular option processing |
|
584 | # Do regular option processing | |
585 | try: |
|
585 | try: | |
586 | opts,args = getopt(argv, opt_str, long_opts) |
|
586 | opts,args = getopt(argv, opt_str, long_opts) | |
587 | except GetoptError as e: |
|
587 | except GetoptError as e: | |
588 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
588 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
589 | " ".join(long_opts))) |
|
589 | " ".join(long_opts))) | |
590 | for o,a in opts: |
|
590 | for o,a in opts: | |
591 | if o.startswith('--'): |
|
591 | if o.startswith('--'): | |
592 | o = o[2:] |
|
592 | o = o[2:] | |
593 | else: |
|
593 | else: | |
594 | o = o[1:] |
|
594 | o = o[1:] | |
595 | try: |
|
595 | try: | |
596 | odict[o].append(a) |
|
596 | odict[o].append(a) | |
597 | except AttributeError: |
|
597 | except AttributeError: | |
598 | odict[o] = [odict[o],a] |
|
598 | odict[o] = [odict[o],a] | |
599 | except KeyError: |
|
599 | except KeyError: | |
600 | if list_all: |
|
600 | if list_all: | |
601 | odict[o] = [a] |
|
601 | odict[o] = [a] | |
602 | else: |
|
602 | else: | |
603 | odict[o] = a |
|
603 | odict[o] = a | |
604 |
|
604 | |||
605 | # Prepare opts,args for return |
|
605 | # Prepare opts,args for return | |
606 | opts = Struct(odict) |
|
606 | opts = Struct(odict) | |
607 | if mode == 'string': |
|
607 | if mode == 'string': | |
608 | args = ' '.join(args) |
|
608 | args = ' '.join(args) | |
609 |
|
609 | |||
610 | return opts,args |
|
610 | return opts,args | |
611 |
|
611 | |||
612 | def default_option(self, fn, optstr): |
|
612 | def default_option(self, fn, optstr): | |
613 | """Make an entry in the options_table for fn, with value optstr""" |
|
613 | """Make an entry in the options_table for fn, with value optstr""" | |
614 |
|
614 | |||
615 | if fn not in self.lsmagic(): |
|
615 | if fn not in self.lsmagic(): | |
616 | error("%s is not a magic function" % fn) |
|
616 | error("%s is not a magic function" % fn) | |
617 | self.options_table[fn] = optstr |
|
617 | self.options_table[fn] = optstr |
@@ -1,1244 +1,1244 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | ultratb.py -- Spice up your tracebacks! |
|
3 | ultratb.py -- Spice up your tracebacks! | |
4 |
|
4 | |||
5 | * ColorTB |
|
5 | * ColorTB | |
6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
6 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
7 | ColorTB class is a solution to that problem. It colors the different parts of a | |
8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
8 | traceback in a manner similar to what you would expect from a syntax-highlighting | |
9 | text editor. |
|
9 | text editor. | |
10 |
|
10 | |||
11 | Installation instructions for ColorTB: |
|
11 | Installation instructions for ColorTB: | |
12 | import sys,ultratb |
|
12 | import sys,ultratb | |
13 | sys.excepthook = ultratb.ColorTB() |
|
13 | sys.excepthook = ultratb.ColorTB() | |
14 |
|
14 | |||
15 | * VerboseTB |
|
15 | * VerboseTB | |
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML | |
18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
18 | and intended it for CGI programmers, but why should they have all the fun? I | |
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, | |
20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
20 | but kind of neat, and maybe useful for long-running programs that you believe | |
21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
21 | are bug-free. If a crash *does* occur in that type of program you want details. | |
22 | Give it a shot--you'll love it or you'll hate it. |
|
22 | Give it a shot--you'll love it or you'll hate it. | |
23 |
|
23 | |||
24 | Note: |
|
24 | Note: | |
25 |
|
25 | |||
26 | The Verbose mode prints the variables currently visible where the exception |
|
26 | The Verbose mode prints the variables currently visible where the exception | |
27 | happened (shortening their strings if too long). This can potentially be |
|
27 | happened (shortening their strings if too long). This can potentially be | |
28 | very slow, if you happen to have a huge data structure whose string |
|
28 | very slow, if you happen to have a huge data structure whose string | |
29 | representation is complex to compute. Your computer may appear to freeze for |
|
29 | representation is complex to compute. Your computer may appear to freeze for | |
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback | |
31 | with Ctrl-C (maybe hitting it more than once). |
|
31 | with Ctrl-C (maybe hitting it more than once). | |
32 |
|
32 | |||
33 | If you encounter this kind of situation often, you may want to use the |
|
33 | If you encounter this kind of situation often, you may want to use the | |
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting | |
35 | variables (but otherwise includes the information and context given by |
|
35 | variables (but otherwise includes the information and context given by | |
36 | Verbose). |
|
36 | Verbose). | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | Installation instructions for ColorTB: |
|
39 | Installation instructions for ColorTB: | |
40 | import sys,ultratb |
|
40 | import sys,ultratb | |
41 | sys.excepthook = ultratb.VerboseTB() |
|
41 | sys.excepthook = ultratb.VerboseTB() | |
42 |
|
42 | |||
43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
43 | Note: Much of the code in this module was lifted verbatim from the standard | |
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
45 |
|
45 | |||
46 | * Color schemes |
|
46 | * Color schemes | |
47 | The colors are defined in the class TBTools through the use of the |
|
47 | The colors are defined in the class TBTools through the use of the | |
48 | ColorSchemeTable class. Currently the following exist: |
|
48 | ColorSchemeTable class. Currently the following exist: | |
49 |
|
49 | |||
50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
50 | - NoColor: allows all of this module to be used in any terminal (the color | |
51 | escapes are just dummy blank strings). |
|
51 | escapes are just dummy blank strings). | |
52 |
|
52 | |||
53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
53 | - Linux: is meant to look good in a terminal like the Linux console (black | |
54 | or very dark background). |
|
54 | or very dark background). | |
55 |
|
55 | |||
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable | |
57 | in light background terminals. |
|
57 | in light background terminals. | |
58 |
|
58 | |||
59 | You can implement other color schemes easily, the syntax is fairly |
|
59 | You can implement other color schemes easily, the syntax is fairly | |
60 | self-explanatory. Please send back new schemes you develop to the author for |
|
60 | self-explanatory. Please send back new schemes you develop to the author for | |
61 | possible inclusion in future releases. |
|
61 | possible inclusion in future releases. | |
62 | """ |
|
62 | """ | |
63 |
|
63 | |||
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | |
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
67 | # |
|
67 | # | |
68 | # Distributed under the terms of the BSD License. The full license is in |
|
68 | # Distributed under the terms of the BSD License. The full license is in | |
69 | # the file COPYING, distributed as part of this software. |
|
69 | # the file COPYING, distributed as part of this software. | |
70 | #***************************************************************************** |
|
70 | #***************************************************************************** | |
71 |
|
71 | |||
72 | from __future__ import with_statement |
|
72 | from __future__ import with_statement | |
73 |
|
73 | |||
74 | import inspect |
|
74 | import inspect | |
75 | import keyword |
|
75 | import keyword | |
76 | import linecache |
|
76 | import linecache | |
77 | import os |
|
77 | import os | |
78 | import pydoc |
|
78 | import pydoc | |
79 | import re |
|
79 | import re | |
80 | import sys |
|
80 | import sys | |
81 | import time |
|
81 | import time | |
82 | import tokenize |
|
82 | import tokenize | |
83 | import traceback |
|
83 | import traceback | |
84 | import types |
|
84 | import types | |
85 |
|
85 | |||
86 | try: # Python 2 |
|
86 | try: # Python 2 | |
87 | generate_tokens = tokenize.generate_tokens |
|
87 | generate_tokens = tokenize.generate_tokens | |
88 | except AttributeError: # Python 3 |
|
88 | except AttributeError: # Python 3 | |
89 | generate_tokens = tokenize.tokenize |
|
89 | generate_tokens = tokenize.tokenize | |
90 |
|
90 | |||
91 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
91 | # For purposes of monkeypatching inspect to fix a bug in it. | |
92 | from inspect import getsourcefile, getfile, getmodule,\ |
|
92 | from inspect import getsourcefile, getfile, getmodule,\ | |
93 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
93 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode | |
94 |
|
94 | |||
95 | # IPython's own modules |
|
95 | # IPython's own modules | |
96 | # Modified pdb which doesn't damage IPython's readline handling |
|
96 | # Modified pdb which doesn't damage IPython's readline handling | |
97 | from IPython.core import debugger, ipapi |
|
97 | from IPython.core import debugger, ipapi | |
98 | from IPython.core.display_trap import DisplayTrap |
|
98 | from IPython.core.display_trap import DisplayTrap | |
99 | from IPython.core.excolors import exception_colors |
|
99 | from IPython.core.excolors import exception_colors | |
100 | from IPython.utils import PyColorize |
|
100 | from IPython.utils import PyColorize | |
101 | from IPython.utils import io |
|
101 | from IPython.utils import io | |
102 | from IPython.utils import py3compat |
|
102 | from IPython.utils import py3compat | |
103 | from IPython.utils import pyfile |
|
103 | from IPython.utils import pyfile | |
104 | from IPython.utils.data import uniq_stable |
|
104 | from IPython.utils.data import uniq_stable | |
105 | from IPython.utils.warn import info, error |
|
105 | from IPython.utils.warn import info, error | |
106 |
|
106 | |||
107 | # Globals |
|
107 | # Globals | |
108 | # amount of space to put line numbers before verbose tracebacks |
|
108 | # amount of space to put line numbers before verbose tracebacks | |
109 | INDENT_SIZE = 8 |
|
109 | INDENT_SIZE = 8 | |
110 |
|
110 | |||
111 | # Default color scheme. This is used, for example, by the traceback |
|
111 | # Default color scheme. This is used, for example, by the traceback | |
112 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
112 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
113 | # value is used, but havinga module global makes this functionality available |
|
113 | # value is used, but havinga module global makes this functionality available | |
114 | # to users of ultratb who are NOT running inside ipython. |
|
114 | # to users of ultratb who are NOT running inside ipython. | |
115 | DEFAULT_SCHEME = 'NoColor' |
|
115 | DEFAULT_SCHEME = 'NoColor' | |
116 |
|
116 | |||
117 | #--------------------------------------------------------------------------- |
|
117 | #--------------------------------------------------------------------------- | |
118 | # Code begins |
|
118 | # Code begins | |
119 |
|
119 | |||
120 | # Utility functions |
|
120 | # Utility functions | |
121 | def inspect_error(): |
|
121 | def inspect_error(): | |
122 | """Print a message about internal inspect errors. |
|
122 | """Print a message about internal inspect errors. | |
123 |
|
123 | |||
124 | These are unfortunately quite common.""" |
|
124 | These are unfortunately quite common.""" | |
125 |
|
125 | |||
126 | error('Internal Python error in the inspect module.\n' |
|
126 | error('Internal Python error in the inspect module.\n' | |
127 | 'Below is the traceback from this internal error.\n') |
|
127 | 'Below is the traceback from this internal error.\n') | |
128 |
|
128 | |||
129 |
|
129 | |||
130 | # N.B. This function is a monkeypatch we are currently not applying. |
|
130 | # N.B. This function is a monkeypatch we are currently not applying. | |
131 | # It was written some time ago, to fix an apparent Python bug with |
|
131 | # It was written some time ago, to fix an apparent Python bug with | |
132 | # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions |
|
132 | # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions | |
133 | # the bug occurred, so we can't tell if it has been fixed. If it reappears, we |
|
133 | # the bug occurred, so we can't tell if it has been fixed. If it reappears, we | |
134 | # will apply the monkeypatch again. Also, note that findsource() is not called |
|
134 | # will apply the monkeypatch again. Also, note that findsource() is not called | |
135 | # by our code at this time - we don't know if it was when the monkeypatch was |
|
135 | # by our code at this time - we don't know if it was when the monkeypatch was | |
136 | # written, or if the monkeypatch is needed for some other code (like a debugger). |
|
136 | # written, or if the monkeypatch is needed for some other code (like a debugger). | |
137 | # For the discussion about not applying it, see gh-1229. TK, Jan 2011. |
|
137 | # For the discussion about not applying it, see gh-1229. TK, Jan 2011. | |
138 | def findsource(object): |
|
138 | def findsource(object): | |
139 | """Return the entire source file and starting line number for an object. |
|
139 | """Return the entire source file and starting line number for an object. | |
140 |
|
140 | |||
141 | The argument may be a module, class, method, function, traceback, frame, |
|
141 | The argument may be a module, class, method, function, traceback, frame, | |
142 | or code object. The source code is returned as a list of all the lines |
|
142 | or code object. The source code is returned as a list of all the lines | |
143 | in the file and the line number indexes a line in that list. An IOError |
|
143 | in the file and the line number indexes a line in that list. An IOError | |
144 | is raised if the source code cannot be retrieved. |
|
144 | is raised if the source code cannot be retrieved. | |
145 |
|
145 | |||
146 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
146 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" | |
147 |
|
147 | |||
148 | file = getsourcefile(object) or getfile(object) |
|
148 | file = getsourcefile(object) or getfile(object) | |
149 | # If the object is a frame, then trying to get the globals dict from its |
|
149 | # If the object is a frame, then trying to get the globals dict from its | |
150 | # module won't work. Instead, the frame object itself has the globals |
|
150 | # module won't work. Instead, the frame object itself has the globals | |
151 | # dictionary. |
|
151 | # dictionary. | |
152 | globals_dict = None |
|
152 | globals_dict = None | |
153 | if inspect.isframe(object): |
|
153 | if inspect.isframe(object): | |
154 | # XXX: can this ever be false? |
|
154 | # XXX: can this ever be false? | |
155 | globals_dict = object.f_globals |
|
155 | globals_dict = object.f_globals | |
156 | else: |
|
156 | else: | |
157 | module = getmodule(object, file) |
|
157 | module = getmodule(object, file) | |
158 | if module: |
|
158 | if module: | |
159 | globals_dict = module.__dict__ |
|
159 | globals_dict = module.__dict__ | |
160 | lines = linecache.getlines(file, globals_dict) |
|
160 | lines = linecache.getlines(file, globals_dict) | |
161 | if not lines: |
|
161 | if not lines: | |
162 | raise IOError('could not get source code') |
|
162 | raise IOError('could not get source code') | |
163 |
|
163 | |||
164 | if ismodule(object): |
|
164 | if ismodule(object): | |
165 | return lines, 0 |
|
165 | return lines, 0 | |
166 |
|
166 | |||
167 | if isclass(object): |
|
167 | if isclass(object): | |
168 | name = object.__name__ |
|
168 | name = object.__name__ | |
169 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
169 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | |
170 | # make some effort to find the best matching class definition: |
|
170 | # make some effort to find the best matching class definition: | |
171 | # use the one with the least indentation, which is the one |
|
171 | # use the one with the least indentation, which is the one | |
172 | # that's most probably not inside a function definition. |
|
172 | # that's most probably not inside a function definition. | |
173 | candidates = [] |
|
173 | candidates = [] | |
174 | for i in range(len(lines)): |
|
174 | for i in range(len(lines)): | |
175 | match = pat.match(lines[i]) |
|
175 | match = pat.match(lines[i]) | |
176 | if match: |
|
176 | if match: | |
177 | # if it's at toplevel, it's already the best one |
|
177 | # if it's at toplevel, it's already the best one | |
178 | if lines[i][0] == 'c': |
|
178 | if lines[i][0] == 'c': | |
179 | return lines, i |
|
179 | return lines, i | |
180 | # else add whitespace to candidate list |
|
180 | # else add whitespace to candidate list | |
181 | candidates.append((match.group(1), i)) |
|
181 | candidates.append((match.group(1), i)) | |
182 | if candidates: |
|
182 | if candidates: | |
183 | # this will sort by whitespace, and by line number, |
|
183 | # this will sort by whitespace, and by line number, | |
184 | # less whitespace first |
|
184 | # less whitespace first | |
185 | candidates.sort() |
|
185 | candidates.sort() | |
186 | return lines, candidates[0][1] |
|
186 | return lines, candidates[0][1] | |
187 | else: |
|
187 | else: | |
188 | raise IOError('could not find class definition') |
|
188 | raise IOError('could not find class definition') | |
189 |
|
189 | |||
190 | if ismethod(object): |
|
190 | if ismethod(object): | |
191 | object = object.im_func |
|
191 | object = object.im_func | |
192 | if isfunction(object): |
|
192 | if isfunction(object): | |
193 | object = object.func_code |
|
193 | object = object.func_code | |
194 | if istraceback(object): |
|
194 | if istraceback(object): | |
195 | object = object.tb_frame |
|
195 | object = object.tb_frame | |
196 | if isframe(object): |
|
196 | if isframe(object): | |
197 | object = object.f_code |
|
197 | object = object.f_code | |
198 | if iscode(object): |
|
198 | if iscode(object): | |
199 | if not hasattr(object, 'co_firstlineno'): |
|
199 | if not hasattr(object, 'co_firstlineno'): | |
200 | raise IOError('could not find function definition') |
|
200 | raise IOError('could not find function definition') | |
201 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
201 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | |
202 | pmatch = pat.match |
|
202 | pmatch = pat.match | |
203 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
203 | # fperez - fix: sometimes, co_firstlineno can give a number larger than | |
204 | # the length of lines, which causes an error. Safeguard against that. |
|
204 | # the length of lines, which causes an error. Safeguard against that. | |
205 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
205 | lnum = min(object.co_firstlineno,len(lines))-1 | |
206 | while lnum > 0: |
|
206 | while lnum > 0: | |
207 | if pmatch(lines[lnum]): break |
|
207 | if pmatch(lines[lnum]): break | |
208 | lnum -= 1 |
|
208 | lnum -= 1 | |
209 |
|
209 | |||
210 | return lines, lnum |
|
210 | return lines, lnum | |
211 | raise IOError('could not find code object') |
|
211 | raise IOError('could not find code object') | |
212 |
|
212 | |||
213 | # Not applying the monkeypatch - see above the function for details. TK, Jan 2012 |
|
213 | # Not applying the monkeypatch - see above the function for details. TK, Jan 2012 | |
214 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
214 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 | |
215 | #if sys.version_info[:2] >= (2,5): |
|
215 | #if sys.version_info[:2] >= (2,5): | |
216 | # inspect.findsource = findsource |
|
216 | # inspect.findsource = findsource | |
217 |
|
217 | |||
218 | def fix_frame_records_filenames(records): |
|
218 | def fix_frame_records_filenames(records): | |
219 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
219 | """Try to fix the filenames in each record from inspect.getinnerframes(). | |
220 |
|
220 | |||
221 | Particularly, modules loaded from within zip files have useless filenames |
|
221 | Particularly, modules loaded from within zip files have useless filenames | |
222 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
222 | attached to their code object, and inspect.getinnerframes() just uses it. | |
223 | """ |
|
223 | """ | |
224 | fixed_records = [] |
|
224 | fixed_records = [] | |
225 | for frame, filename, line_no, func_name, lines, index in records: |
|
225 | for frame, filename, line_no, func_name, lines, index in records: | |
226 | # Look inside the frame's globals dictionary for __file__, which should |
|
226 | # Look inside the frame's globals dictionary for __file__, which should | |
227 | # be better. |
|
227 | # be better. | |
228 | better_fn = frame.f_globals.get('__file__', None) |
|
228 | better_fn = frame.f_globals.get('__file__', None) | |
229 | if isinstance(better_fn, str): |
|
229 | if isinstance(better_fn, str): | |
230 | # Check the type just in case someone did something weird with |
|
230 | # Check the type just in case someone did something weird with | |
231 | # __file__. It might also be None if the error occurred during |
|
231 | # __file__. It might also be None if the error occurred during | |
232 | # import. |
|
232 | # import. | |
233 | filename = better_fn |
|
233 | filename = better_fn | |
234 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
234 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) | |
235 | return fixed_records |
|
235 | return fixed_records | |
236 |
|
236 | |||
237 |
|
237 | |||
238 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
238 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): | |
239 | import linecache |
|
239 | import linecache | |
240 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
240 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 | |
241 |
|
241 | |||
242 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
242 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) | |
243 |
|
243 | |||
244 | # If the error is at the console, don't build any context, since it would |
|
244 | # If the error is at the console, don't build any context, since it would | |
245 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
245 | # otherwise produce 5 blank lines printed out (there is no file at the | |
246 | # console) |
|
246 | # console) | |
247 | rec_check = records[tb_offset:] |
|
247 | rec_check = records[tb_offset:] | |
248 | try: |
|
248 | try: | |
249 | rname = rec_check[0][1] |
|
249 | rname = rec_check[0][1] | |
250 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
250 | if rname == '<ipython console>' or rname.endswith('<string>'): | |
251 | return rec_check |
|
251 | return rec_check | |
252 | except IndexError: |
|
252 | except IndexError: | |
253 | pass |
|
253 | pass | |
254 |
|
254 | |||
255 | aux = traceback.extract_tb(etb) |
|
255 | aux = traceback.extract_tb(etb) | |
256 | assert len(records) == len(aux) |
|
256 | assert len(records) == len(aux) | |
257 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
257 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): | |
258 | maybeStart = lnum-1 - context//2 |
|
258 | maybeStart = lnum-1 - context//2 | |
259 | start = max(maybeStart, 0) |
|
259 | start = max(maybeStart, 0) | |
260 | end = start + context |
|
260 | end = start + context | |
261 | lines = linecache.getlines(file)[start:end] |
|
261 | lines = linecache.getlines(file)[start:end] | |
262 | buf = list(records[i]) |
|
262 | buf = list(records[i]) | |
263 | buf[LNUM_POS] = lnum |
|
263 | buf[LNUM_POS] = lnum | |
264 | buf[INDEX_POS] = lnum - 1 - start |
|
264 | buf[INDEX_POS] = lnum - 1 - start | |
265 | buf[LINES_POS] = lines |
|
265 | buf[LINES_POS] = lines | |
266 | records[i] = tuple(buf) |
|
266 | records[i] = tuple(buf) | |
267 | return records[tb_offset:] |
|
267 | return records[tb_offset:] | |
268 |
|
268 | |||
269 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
269 | # Helper function -- largely belongs to VerboseTB, but we need the same | |
270 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
270 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | |
271 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
271 | # can be recognized properly by ipython.el's py-traceback-line-re | |
272 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
272 | # (SyntaxErrors have to be treated specially because they have no traceback) | |
273 |
|
273 | |||
274 | _parser = PyColorize.Parser() |
|
274 | _parser = PyColorize.Parser() | |
275 |
|
275 | |||
276 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
276 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): | |
277 | numbers_width = INDENT_SIZE - 1 |
|
277 | numbers_width = INDENT_SIZE - 1 | |
278 | res = [] |
|
278 | res = [] | |
279 | i = lnum - index |
|
279 | i = lnum - index | |
280 |
|
280 | |||
281 | # This lets us get fully syntax-highlighted tracebacks. |
|
281 | # This lets us get fully syntax-highlighted tracebacks. | |
282 | if scheme is None: |
|
282 | if scheme is None: | |
283 | ipinst = ipapi.get() |
|
283 | ipinst = ipapi.get() | |
284 | if ipinst is not None: |
|
284 | if ipinst is not None: | |
285 | scheme = ipinst.colors |
|
285 | scheme = ipinst.colors | |
286 | else: |
|
286 | else: | |
287 | scheme = DEFAULT_SCHEME |
|
287 | scheme = DEFAULT_SCHEME | |
288 |
|
288 | |||
289 | _line_format = _parser.format2 |
|
289 | _line_format = _parser.format2 | |
290 |
|
290 | |||
291 | for line in lines: |
|
291 | for line in lines: | |
292 | # FIXME: we need to ensure the source is a pure string at this point, |
|
292 | # FIXME: we need to ensure the source is a pure string at this point, | |
293 | # else the coloring code makes a royal mess. This is in need of a |
|
293 | # else the coloring code makes a royal mess. This is in need of a | |
294 | # serious refactoring, so that all of the ultratb and PyColorize code |
|
294 | # serious refactoring, so that all of the ultratb and PyColorize code | |
295 | # is unicode-safe. So for now this is rather an ugly hack, but |
|
295 | # is unicode-safe. So for now this is rather an ugly hack, but | |
296 | # necessary to at least have readable tracebacks. Improvements welcome! |
|
296 | # necessary to at least have readable tracebacks. Improvements welcome! | |
297 | line = py3compat.cast_bytes_py2(line, 'utf-8') |
|
297 | line = py3compat.cast_bytes_py2(line, 'utf-8') | |
298 |
|
298 | |||
299 | new_line, err = _line_format(line, 'str', scheme) |
|
299 | new_line, err = _line_format(line, 'str', scheme) | |
300 | if not err: line = new_line |
|
300 | if not err: line = new_line | |
301 |
|
301 | |||
302 | if i == lnum: |
|
302 | if i == lnum: | |
303 | # This is the line with the error |
|
303 | # This is the line with the error | |
304 | pad = numbers_width - len(str(i)) |
|
304 | pad = numbers_width - len(str(i)) | |
305 | if pad >= 3: |
|
305 | if pad >= 3: | |
306 | marker = '-'*(pad-3) + '-> ' |
|
306 | marker = '-'*(pad-3) + '-> ' | |
307 | elif pad == 2: |
|
307 | elif pad == 2: | |
308 | marker = '> ' |
|
308 | marker = '> ' | |
309 | elif pad == 1: |
|
309 | elif pad == 1: | |
310 | marker = '>' |
|
310 | marker = '>' | |
311 | else: |
|
311 | else: | |
312 | marker = '' |
|
312 | marker = '' | |
313 | num = marker + str(i) |
|
313 | num = marker + str(i) | |
314 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
314 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, | |
315 | Colors.line, line, Colors.Normal) |
|
315 | Colors.line, line, Colors.Normal) | |
316 | else: |
|
316 | else: | |
317 | num = '%*s' % (numbers_width,i) |
|
317 | num = '%*s' % (numbers_width,i) | |
318 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
318 | line = '%s%s%s %s' %(Colors.lineno, num, | |
319 | Colors.Normal, line) |
|
319 | Colors.Normal, line) | |
320 |
|
320 | |||
321 | res.append(line) |
|
321 | res.append(line) | |
322 | if lvals and i == lnum: |
|
322 | if lvals and i == lnum: | |
323 | res.append(lvals + '\n') |
|
323 | res.append(lvals + '\n') | |
324 | i = i + 1 |
|
324 | i = i + 1 | |
325 | return res |
|
325 | return res | |
326 |
|
326 | |||
327 |
|
327 | |||
328 | #--------------------------------------------------------------------------- |
|
328 | #--------------------------------------------------------------------------- | |
329 | # Module classes |
|
329 | # Module classes | |
330 | class TBTools(object): |
|
330 | class TBTools(object): | |
331 | """Basic tools used by all traceback printer classes.""" |
|
331 | """Basic tools used by all traceback printer classes.""" | |
332 |
|
332 | |||
333 | # Number of frames to skip when reporting tracebacks |
|
333 | # Number of frames to skip when reporting tracebacks | |
334 | tb_offset = 0 |
|
334 | tb_offset = 0 | |
335 |
|
335 | |||
336 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): |
|
336 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): | |
337 | # Whether to call the interactive pdb debugger after printing |
|
337 | # Whether to call the interactive pdb debugger after printing | |
338 | # tracebacks or not |
|
338 | # tracebacks or not | |
339 | self.call_pdb = call_pdb |
|
339 | self.call_pdb = call_pdb | |
340 |
|
340 | |||
341 | # Output stream to write to. Note that we store the original value in |
|
341 | # Output stream to write to. Note that we store the original value in | |
342 | # a private attribute and then make the public ostream a property, so |
|
342 | # a private attribute and then make the public ostream a property, so | |
343 | # that we can delay accessing io.stdout until runtime. The way |
|
343 | # that we can delay accessing io.stdout until runtime. The way | |
344 | # things are written now, the io.stdout object is dynamically managed |
|
344 | # things are written now, the io.stdout object is dynamically managed | |
345 | # so a reference to it should NEVER be stored statically. This |
|
345 | # so a reference to it should NEVER be stored statically. This | |
346 | # property approach confines this detail to a single location, and all |
|
346 | # property approach confines this detail to a single location, and all | |
347 | # subclasses can simply access self.ostream for writing. |
|
347 | # subclasses can simply access self.ostream for writing. | |
348 | self._ostream = ostream |
|
348 | self._ostream = ostream | |
349 |
|
349 | |||
350 | # Create color table |
|
350 | # Create color table | |
351 | self.color_scheme_table = exception_colors() |
|
351 | self.color_scheme_table = exception_colors() | |
352 |
|
352 | |||
353 | self.set_colors(color_scheme) |
|
353 | self.set_colors(color_scheme) | |
354 | self.old_scheme = color_scheme # save initial value for toggles |
|
354 | self.old_scheme = color_scheme # save initial value for toggles | |
355 |
|
355 | |||
356 | if call_pdb: |
|
356 | if call_pdb: | |
357 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
357 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) | |
358 | else: |
|
358 | else: | |
359 | self.pdb = None |
|
359 | self.pdb = None | |
360 |
|
360 | |||
361 | def _get_ostream(self): |
|
361 | def _get_ostream(self): | |
362 | """Output stream that exceptions are written to. |
|
362 | """Output stream that exceptions are written to. | |
363 |
|
363 | |||
364 | Valid values are: |
|
364 | Valid values are: | |
365 |
|
365 | |||
366 | - None: the default, which means that IPython will dynamically resolve |
|
366 | - None: the default, which means that IPython will dynamically resolve | |
367 | to io.stdout. This ensures compatibility with most tools, including |
|
367 | to io.stdout. This ensures compatibility with most tools, including | |
368 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
368 | Windows (where plain stdout doesn't recognize ANSI escapes). | |
369 |
|
369 | |||
370 | - Any object with 'write' and 'flush' attributes. |
|
370 | - Any object with 'write' and 'flush' attributes. | |
371 | """ |
|
371 | """ | |
372 | return io.stdout if self._ostream is None else self._ostream |
|
372 | return io.stdout if self._ostream is None else self._ostream | |
373 |
|
373 | |||
374 | def _set_ostream(self, val): |
|
374 | def _set_ostream(self, val): | |
375 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
375 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) | |
376 | self._ostream = val |
|
376 | self._ostream = val | |
377 |
|
377 | |||
378 | ostream = property(_get_ostream, _set_ostream) |
|
378 | ostream = property(_get_ostream, _set_ostream) | |
379 |
|
379 | |||
380 | def set_colors(self,*args,**kw): |
|
380 | def set_colors(self,*args,**kw): | |
381 | """Shorthand access to the color table scheme selector method.""" |
|
381 | """Shorthand access to the color table scheme selector method.""" | |
382 |
|
382 | |||
383 | # Set own color table |
|
383 | # Set own color table | |
384 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
384 | self.color_scheme_table.set_active_scheme(*args,**kw) | |
385 | # for convenience, set Colors to the active scheme |
|
385 | # for convenience, set Colors to the active scheme | |
386 | self.Colors = self.color_scheme_table.active_colors |
|
386 | self.Colors = self.color_scheme_table.active_colors | |
387 | # Also set colors of debugger |
|
387 | # Also set colors of debugger | |
388 | if hasattr(self,'pdb') and self.pdb is not None: |
|
388 | if hasattr(self,'pdb') and self.pdb is not None: | |
389 | self.pdb.set_colors(*args,**kw) |
|
389 | self.pdb.set_colors(*args,**kw) | |
390 |
|
390 | |||
391 | def color_toggle(self): |
|
391 | def color_toggle(self): | |
392 | """Toggle between the currently active color scheme and NoColor.""" |
|
392 | """Toggle between the currently active color scheme and NoColor.""" | |
393 |
|
393 | |||
394 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
394 | if self.color_scheme_table.active_scheme_name == 'NoColor': | |
395 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
395 | self.color_scheme_table.set_active_scheme(self.old_scheme) | |
396 | self.Colors = self.color_scheme_table.active_colors |
|
396 | self.Colors = self.color_scheme_table.active_colors | |
397 | else: |
|
397 | else: | |
398 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
398 | self.old_scheme = self.color_scheme_table.active_scheme_name | |
399 | self.color_scheme_table.set_active_scheme('NoColor') |
|
399 | self.color_scheme_table.set_active_scheme('NoColor') | |
400 | self.Colors = self.color_scheme_table.active_colors |
|
400 | self.Colors = self.color_scheme_table.active_colors | |
401 |
|
401 | |||
402 | def stb2text(self, stb): |
|
402 | def stb2text(self, stb): | |
403 | """Convert a structured traceback (a list) to a string.""" |
|
403 | """Convert a structured traceback (a list) to a string.""" | |
404 | return '\n'.join(stb) |
|
404 | return '\n'.join(stb) | |
405 |
|
405 | |||
406 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
406 | def text(self, etype, value, tb, tb_offset=None, context=5): | |
407 | """Return formatted traceback. |
|
407 | """Return formatted traceback. | |
408 |
|
408 | |||
409 | Subclasses may override this if they add extra arguments. |
|
409 | Subclasses may override this if they add extra arguments. | |
410 | """ |
|
410 | """ | |
411 | tb_list = self.structured_traceback(etype, value, tb, |
|
411 | tb_list = self.structured_traceback(etype, value, tb, | |
412 | tb_offset, context) |
|
412 | tb_offset, context) | |
413 | return self.stb2text(tb_list) |
|
413 | return self.stb2text(tb_list) | |
414 |
|
414 | |||
415 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
415 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, | |
416 | context=5, mode=None): |
|
416 | context=5, mode=None): | |
417 | """Return a list of traceback frames. |
|
417 | """Return a list of traceback frames. | |
418 |
|
418 | |||
419 | Must be implemented by each class. |
|
419 | Must be implemented by each class. | |
420 | """ |
|
420 | """ | |
421 | raise NotImplementedError() |
|
421 | raise NotImplementedError() | |
422 |
|
422 | |||
423 |
|
423 | |||
424 | #--------------------------------------------------------------------------- |
|
424 | #--------------------------------------------------------------------------- | |
425 | class ListTB(TBTools): |
|
425 | class ListTB(TBTools): | |
426 | """Print traceback information from a traceback list, with optional color. |
|
426 | """Print traceback information from a traceback list, with optional color. | |
427 |
|
427 | |||
428 | Calling: requires 3 arguments: |
|
428 | Calling: requires 3 arguments: | |
429 | (etype, evalue, elist) |
|
429 | (etype, evalue, elist) | |
430 | as would be obtained by: |
|
430 | as would be obtained by: | |
431 | etype, evalue, tb = sys.exc_info() |
|
431 | etype, evalue, tb = sys.exc_info() | |
432 | if tb: |
|
432 | if tb: | |
433 | elist = traceback.extract_tb(tb) |
|
433 | elist = traceback.extract_tb(tb) | |
434 | else: |
|
434 | else: | |
435 | elist = None |
|
435 | elist = None | |
436 |
|
436 | |||
437 | It can thus be used by programs which need to process the traceback before |
|
437 | It can thus be used by programs which need to process the traceback before | |
438 | printing (such as console replacements based on the code module from the |
|
438 | printing (such as console replacements based on the code module from the | |
439 | standard library). |
|
439 | standard library). | |
440 |
|
440 | |||
441 | Because they are meant to be called without a full traceback (only a |
|
441 | Because they are meant to be called without a full traceback (only a | |
442 | list), instances of this class can't call the interactive pdb debugger.""" |
|
442 | list), instances of this class can't call the interactive pdb debugger.""" | |
443 |
|
443 | |||
444 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): |
|
444 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): | |
445 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
445 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
446 | ostream=ostream) |
|
446 | ostream=ostream) | |
447 |
|
447 | |||
448 | def __call__(self, etype, value, elist): |
|
448 | def __call__(self, etype, value, elist): | |
449 | self.ostream.flush() |
|
449 | self.ostream.flush() | |
450 | self.ostream.write(self.text(etype, value, elist)) |
|
450 | self.ostream.write(self.text(etype, value, elist)) | |
451 | self.ostream.write('\n') |
|
451 | self.ostream.write('\n') | |
452 |
|
452 | |||
453 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
453 | def structured_traceback(self, etype, value, elist, tb_offset=None, | |
454 | context=5): |
|
454 | context=5): | |
455 | """Return a color formatted string with the traceback info. |
|
455 | """Return a color formatted string with the traceback info. | |
456 |
|
456 | |||
457 | Parameters |
|
457 | Parameters | |
458 | ---------- |
|
458 | ---------- | |
459 | etype : exception type |
|
459 | etype : exception type | |
460 | Type of the exception raised. |
|
460 | Type of the exception raised. | |
461 |
|
461 | |||
462 | value : object |
|
462 | value : object | |
463 | Data stored in the exception |
|
463 | Data stored in the exception | |
464 |
|
464 | |||
465 | elist : list |
|
465 | elist : list | |
466 | List of frames, see class docstring for details. |
|
466 | List of frames, see class docstring for details. | |
467 |
|
467 | |||
468 | tb_offset : int, optional |
|
468 | tb_offset : int, optional | |
469 | Number of frames in the traceback to skip. If not given, the |
|
469 | Number of frames in the traceback to skip. If not given, the | |
470 | instance value is used (set in constructor). |
|
470 | instance value is used (set in constructor). | |
471 |
|
471 | |||
472 | context : int, optional |
|
472 | context : int, optional | |
473 | Number of lines of context information to print. |
|
473 | Number of lines of context information to print. | |
474 |
|
474 | |||
475 | Returns |
|
475 | Returns | |
476 | ------- |
|
476 | ------- | |
477 | String with formatted exception. |
|
477 | String with formatted exception. | |
478 | """ |
|
478 | """ | |
479 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
479 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
480 | Colors = self.Colors |
|
480 | Colors = self.Colors | |
481 | out_list = [] |
|
481 | out_list = [] | |
482 | if elist: |
|
482 | if elist: | |
483 |
|
483 | |||
484 | if tb_offset and len(elist) > tb_offset: |
|
484 | if tb_offset and len(elist) > tb_offset: | |
485 | elist = elist[tb_offset:] |
|
485 | elist = elist[tb_offset:] | |
486 |
|
486 | |||
487 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
487 | out_list.append('Traceback %s(most recent call last)%s:' % | |
488 | (Colors.normalEm, Colors.Normal) + '\n') |
|
488 | (Colors.normalEm, Colors.Normal) + '\n') | |
489 | out_list.extend(self._format_list(elist)) |
|
489 | out_list.extend(self._format_list(elist)) | |
490 | # The exception info should be a single entry in the list. |
|
490 | # The exception info should be a single entry in the list. | |
491 | lines = ''.join(self._format_exception_only(etype, value)) |
|
491 | lines = ''.join(self._format_exception_only(etype, value)) | |
492 | out_list.append(lines) |
|
492 | out_list.append(lines) | |
493 |
|
493 | |||
494 | # Note: this code originally read: |
|
494 | # Note: this code originally read: | |
495 |
|
495 | |||
496 | ## for line in lines[:-1]: |
|
496 | ## for line in lines[:-1]: | |
497 | ## out_list.append(" "+line) |
|
497 | ## out_list.append(" "+line) | |
498 | ## out_list.append(lines[-1]) |
|
498 | ## out_list.append(lines[-1]) | |
499 |
|
499 | |||
500 | # This means it was indenting everything but the last line by a little |
|
500 | # This means it was indenting everything but the last line by a little | |
501 | # bit. I've disabled this for now, but if we see ugliness somewhre we |
|
501 | # bit. I've disabled this for now, but if we see ugliness somewhre we | |
502 | # can restore it. |
|
502 | # can restore it. | |
503 |
|
503 | |||
504 | return out_list |
|
504 | return out_list | |
505 |
|
505 | |||
506 | def _format_list(self, extracted_list): |
|
506 | def _format_list(self, extracted_list): | |
507 | """Format a list of traceback entry tuples for printing. |
|
507 | """Format a list of traceback entry tuples for printing. | |
508 |
|
508 | |||
509 | Given a list of tuples as returned by extract_tb() or |
|
509 | Given a list of tuples as returned by extract_tb() or | |
510 | extract_stack(), return a list of strings ready for printing. |
|
510 | extract_stack(), return a list of strings ready for printing. | |
511 | Each string in the resulting list corresponds to the item with the |
|
511 | Each string in the resulting list corresponds to the item with the | |
512 | same index in the argument list. Each string ends in a newline; |
|
512 | same index in the argument list. Each string ends in a newline; | |
513 | the strings may contain internal newlines as well, for those items |
|
513 | the strings may contain internal newlines as well, for those items | |
514 | whose source text line is not None. |
|
514 | whose source text line is not None. | |
515 |
|
515 | |||
516 | Lifted almost verbatim from traceback.py |
|
516 | Lifted almost verbatim from traceback.py | |
517 | """ |
|
517 | """ | |
518 |
|
518 | |||
519 | Colors = self.Colors |
|
519 | Colors = self.Colors | |
520 | list = [] |
|
520 | list = [] | |
521 | for filename, lineno, name, line in extracted_list[:-1]: |
|
521 | for filename, lineno, name, line in extracted_list[:-1]: | |
522 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
522 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ | |
523 | (Colors.filename, filename, Colors.Normal, |
|
523 | (Colors.filename, filename, Colors.Normal, | |
524 | Colors.lineno, lineno, Colors.Normal, |
|
524 | Colors.lineno, lineno, Colors.Normal, | |
525 | Colors.name, name, Colors.Normal) |
|
525 | Colors.name, name, Colors.Normal) | |
526 | if line: |
|
526 | if line: | |
527 | item += ' %s\n' % line.strip() |
|
527 | item += ' %s\n' % line.strip() | |
528 | list.append(item) |
|
528 | list.append(item) | |
529 | # Emphasize the last entry |
|
529 | # Emphasize the last entry | |
530 | filename, lineno, name, line = extracted_list[-1] |
|
530 | filename, lineno, name, line = extracted_list[-1] | |
531 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
531 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ | |
532 | (Colors.normalEm, |
|
532 | (Colors.normalEm, | |
533 | Colors.filenameEm, filename, Colors.normalEm, |
|
533 | Colors.filenameEm, filename, Colors.normalEm, | |
534 | Colors.linenoEm, lineno, Colors.normalEm, |
|
534 | Colors.linenoEm, lineno, Colors.normalEm, | |
535 | Colors.nameEm, name, Colors.normalEm, |
|
535 | Colors.nameEm, name, Colors.normalEm, | |
536 | Colors.Normal) |
|
536 | Colors.Normal) | |
537 | if line: |
|
537 | if line: | |
538 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
538 | item += '%s %s%s\n' % (Colors.line, line.strip(), | |
539 | Colors.Normal) |
|
539 | Colors.Normal) | |
540 | list.append(item) |
|
540 | list.append(item) | |
541 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg |
|
541 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg | |
542 | return list |
|
542 | return list | |
543 |
|
543 | |||
544 | def _format_exception_only(self, etype, value): |
|
544 | def _format_exception_only(self, etype, value): | |
545 | """Format the exception part of a traceback. |
|
545 | """Format the exception part of a traceback. | |
546 |
|
546 | |||
547 | The arguments are the exception type and value such as given by |
|
547 | The arguments are the exception type and value such as given by | |
548 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
548 | sys.exc_info()[:2]. The return value is a list of strings, each ending | |
549 | in a newline. Normally, the list contains a single string; however, |
|
549 | in a newline. Normally, the list contains a single string; however, | |
550 | for SyntaxError exceptions, it contains several lines that (when |
|
550 | for SyntaxError exceptions, it contains several lines that (when | |
551 | printed) display detailed information about where the syntax error |
|
551 | printed) display detailed information about where the syntax error | |
552 | occurred. The message indicating which exception occurred is the |
|
552 | occurred. The message indicating which exception occurred is the | |
553 | always last string in the list. |
|
553 | always last string in the list. | |
554 |
|
554 | |||
555 | Also lifted nearly verbatim from traceback.py |
|
555 | Also lifted nearly verbatim from traceback.py | |
556 | """ |
|
556 | """ | |
557 |
|
557 | |||
558 | have_filedata = False |
|
558 | have_filedata = False | |
559 | Colors = self.Colors |
|
559 | Colors = self.Colors | |
560 | list = [] |
|
560 | list = [] | |
561 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
561 | stype = Colors.excName + etype.__name__ + Colors.Normal | |
562 | if value is None: |
|
562 | if value is None: | |
563 | # Not sure if this can still happen in Python 2.6 and above |
|
563 | # Not sure if this can still happen in Python 2.6 and above | |
564 | list.append( str(stype) + '\n') |
|
564 | list.append( str(stype) + '\n') | |
565 | else: |
|
565 | else: | |
566 | if etype is SyntaxError: |
|
566 | if etype is SyntaxError: | |
567 | have_filedata = True |
|
567 | have_filedata = True | |
568 | #print 'filename is',filename # dbg |
|
568 | #print 'filename is',filename # dbg | |
569 | if not value.filename: value.filename = "<string>" |
|
569 | if not value.filename: value.filename = "<string>" | |
570 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
570 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ | |
571 | (Colors.normalEm, |
|
571 | (Colors.normalEm, | |
572 | Colors.filenameEm, value.filename, Colors.normalEm, |
|
572 | Colors.filenameEm, value.filename, Colors.normalEm, | |
573 | Colors.linenoEm, value.lineno, Colors.Normal )) |
|
573 | Colors.linenoEm, value.lineno, Colors.Normal )) | |
574 | if value.text is not None: |
|
574 | if value.text is not None: | |
575 | i = 0 |
|
575 | i = 0 | |
576 | while i < len(value.text) and value.text[i].isspace(): |
|
576 | while i < len(value.text) and value.text[i].isspace(): | |
577 | i += 1 |
|
577 | i += 1 | |
578 | list.append('%s %s%s\n' % (Colors.line, |
|
578 | list.append('%s %s%s\n' % (Colors.line, | |
579 | value.text.strip(), |
|
579 | value.text.strip(), | |
580 | Colors.Normal)) |
|
580 | Colors.Normal)) | |
581 | if value.offset is not None: |
|
581 | if value.offset is not None: | |
582 | s = ' ' |
|
582 | s = ' ' | |
583 | for c in value.text[i:value.offset-1]: |
|
583 | for c in value.text[i:value.offset-1]: | |
584 | if c.isspace(): |
|
584 | if c.isspace(): | |
585 | s += c |
|
585 | s += c | |
586 | else: |
|
586 | else: | |
587 | s += ' ' |
|
587 | s += ' ' | |
588 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
588 | list.append('%s%s^%s\n' % (Colors.caret, s, | |
589 | Colors.Normal) ) |
|
589 | Colors.Normal) ) | |
590 |
|
590 | |||
591 | try: |
|
591 | try: | |
592 | s = value.msg |
|
592 | s = value.msg | |
593 | except Exception: |
|
593 | except Exception: | |
594 | s = self._some_str(value) |
|
594 | s = self._some_str(value) | |
595 | if s: |
|
595 | if s: | |
596 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
596 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, | |
597 | Colors.Normal, s)) |
|
597 | Colors.Normal, s)) | |
598 | else: |
|
598 | else: | |
599 | list.append('%s\n' % str(stype)) |
|
599 | list.append('%s\n' % str(stype)) | |
600 |
|
600 | |||
601 | # sync with user hooks |
|
601 | # sync with user hooks | |
602 | if have_filedata: |
|
602 | if have_filedata: | |
603 | ipinst = ipapi.get() |
|
603 | ipinst = ipapi.get() | |
604 | if ipinst is not None: |
|
604 | if ipinst is not None: | |
605 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
605 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) | |
606 |
|
606 | |||
607 | return list |
|
607 | return list | |
608 |
|
608 | |||
609 | def get_exception_only(self, etype, value): |
|
609 | def get_exception_only(self, etype, value): | |
610 | """Only print the exception type and message, without a traceback. |
|
610 | """Only print the exception type and message, without a traceback. | |
611 |
|
611 | |||
612 | Parameters |
|
612 | Parameters | |
613 | ---------- |
|
613 | ---------- | |
614 | etype : exception type |
|
614 | etype : exception type | |
615 | value : exception value |
|
615 | value : exception value | |
616 | """ |
|
616 | """ | |
617 | return ListTB.structured_traceback(self, etype, value, []) |
|
617 | return ListTB.structured_traceback(self, etype, value, []) | |
618 |
|
618 | |||
619 |
|
619 | |||
620 | def show_exception_only(self, etype, evalue): |
|
620 | def show_exception_only(self, etype, evalue): | |
621 | """Only print the exception type and message, without a traceback. |
|
621 | """Only print the exception type and message, without a traceback. | |
622 |
|
622 | |||
623 | Parameters |
|
623 | Parameters | |
624 | ---------- |
|
624 | ---------- | |
625 | etype : exception type |
|
625 | etype : exception type | |
626 | value : exception value |
|
626 | value : exception value | |
627 | """ |
|
627 | """ | |
628 | # This method needs to use __call__ from *this* class, not the one from |
|
628 | # This method needs to use __call__ from *this* class, not the one from | |
629 | # a subclass whose signature or behavior may be different |
|
629 | # a subclass whose signature or behavior may be different | |
630 | ostream = self.ostream |
|
630 | ostream = self.ostream | |
631 | ostream.flush() |
|
631 | ostream.flush() | |
632 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
632 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) | |
633 | ostream.flush() |
|
633 | ostream.flush() | |
634 |
|
634 | |||
635 | def _some_str(self, value): |
|
635 | def _some_str(self, value): | |
636 | # Lifted from traceback.py |
|
636 | # Lifted from traceback.py | |
637 | try: |
|
637 | try: | |
638 | return str(value) |
|
638 | return str(value) | |
639 | except: |
|
639 | except: | |
640 | return '<unprintable %s object>' % type(value).__name__ |
|
640 | return '<unprintable %s object>' % type(value).__name__ | |
641 |
|
641 | |||
642 | #---------------------------------------------------------------------------- |
|
642 | #---------------------------------------------------------------------------- | |
643 | class VerboseTB(TBTools): |
|
643 | class VerboseTB(TBTools): | |
644 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
644 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | |
645 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
645 | of HTML. Requires inspect and pydoc. Crazy, man. | |
646 |
|
646 | |||
647 | Modified version which optionally strips the topmost entries from the |
|
647 | Modified version which optionally strips the topmost entries from the | |
648 | traceback, to be used with alternate interpreters (because their own code |
|
648 | traceback, to be used with alternate interpreters (because their own code | |
649 | would appear in the traceback).""" |
|
649 | would appear in the traceback).""" | |
650 |
|
650 | |||
651 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, |
|
651 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, | |
652 | tb_offset=0, long_header=False, include_vars=True, |
|
652 | tb_offset=0, long_header=False, include_vars=True, | |
653 | check_cache=None): |
|
653 | check_cache=None): | |
654 | """Specify traceback offset, headers and color scheme. |
|
654 | """Specify traceback offset, headers and color scheme. | |
655 |
|
655 | |||
656 | Define how many frames to drop from the tracebacks. Calling it with |
|
656 | Define how many frames to drop from the tracebacks. Calling it with | |
657 | tb_offset=1 allows use of this handler in interpreters which will have |
|
657 | tb_offset=1 allows use of this handler in interpreters which will have | |
658 | their own code at the top of the traceback (VerboseTB will first |
|
658 | their own code at the top of the traceback (VerboseTB will first | |
659 | remove that frame before printing the traceback info).""" |
|
659 | remove that frame before printing the traceback info).""" | |
660 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
660 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
661 | ostream=ostream) |
|
661 | ostream=ostream) | |
662 | self.tb_offset = tb_offset |
|
662 | self.tb_offset = tb_offset | |
663 | self.long_header = long_header |
|
663 | self.long_header = long_header | |
664 | self.include_vars = include_vars |
|
664 | self.include_vars = include_vars | |
665 | # By default we use linecache.checkcache, but the user can provide a |
|
665 | # By default we use linecache.checkcache, but the user can provide a | |
666 | # different check_cache implementation. This is used by the IPython |
|
666 | # different check_cache implementation. This is used by the IPython | |
667 | # kernel to provide tracebacks for interactive code that is cached, |
|
667 | # kernel to provide tracebacks for interactive code that is cached, | |
668 | # by a compiler instance that flushes the linecache but preserves its |
|
668 | # by a compiler instance that flushes the linecache but preserves its | |
669 | # own code cache. |
|
669 | # own code cache. | |
670 | if check_cache is None: |
|
670 | if check_cache is None: | |
671 | check_cache = linecache.checkcache |
|
671 | check_cache = linecache.checkcache | |
672 | self.check_cache = check_cache |
|
672 | self.check_cache = check_cache | |
673 |
|
673 | |||
674 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
674 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, | |
675 | context=5): |
|
675 | context=5): | |
676 | """Return a nice text document describing the traceback.""" |
|
676 | """Return a nice text document describing the traceback.""" | |
677 |
|
677 | |||
678 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
678 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
679 |
|
679 | |||
680 | # some locals |
|
680 | # some locals | |
681 | try: |
|
681 | try: | |
682 | etype = etype.__name__ |
|
682 | etype = etype.__name__ | |
683 | except AttributeError: |
|
683 | except AttributeError: | |
684 | pass |
|
684 | pass | |
685 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
685 | Colors = self.Colors # just a shorthand + quicker name lookup | |
686 | ColorsNormal = Colors.Normal # used a lot |
|
686 | ColorsNormal = Colors.Normal # used a lot | |
687 | col_scheme = self.color_scheme_table.active_scheme_name |
|
687 | col_scheme = self.color_scheme_table.active_scheme_name | |
688 | indent = ' '*INDENT_SIZE |
|
688 | indent = ' '*INDENT_SIZE | |
689 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
689 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) | |
690 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
690 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) | |
691 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
691 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) | |
692 |
|
692 | |||
693 | # some internal-use functions |
|
693 | # some internal-use functions | |
694 | def text_repr(value): |
|
694 | def text_repr(value): | |
695 | """Hopefully pretty robust repr equivalent.""" |
|
695 | """Hopefully pretty robust repr equivalent.""" | |
696 | # this is pretty horrible but should always return *something* |
|
696 | # this is pretty horrible but should always return *something* | |
697 | try: |
|
697 | try: | |
698 | return pydoc.text.repr(value) |
|
698 | return pydoc.text.repr(value) | |
699 | except KeyboardInterrupt: |
|
699 | except KeyboardInterrupt: | |
700 | raise |
|
700 | raise | |
701 | except: |
|
701 | except: | |
702 | try: |
|
702 | try: | |
703 | return repr(value) |
|
703 | return repr(value) | |
704 | except KeyboardInterrupt: |
|
704 | except KeyboardInterrupt: | |
705 | raise |
|
705 | raise | |
706 | except: |
|
706 | except: | |
707 | try: |
|
707 | try: | |
708 | # all still in an except block so we catch |
|
708 | # all still in an except block so we catch | |
709 | # getattr raising |
|
709 | # getattr raising | |
710 | name = getattr(value, '__name__', None) |
|
710 | name = getattr(value, '__name__', None) | |
711 | if name: |
|
711 | if name: | |
712 | # ick, recursion |
|
712 | # ick, recursion | |
713 | return text_repr(name) |
|
713 | return text_repr(name) | |
714 | klass = getattr(value, '__class__', None) |
|
714 | klass = getattr(value, '__class__', None) | |
715 | if klass: |
|
715 | if klass: | |
716 | return '%s instance' % text_repr(klass) |
|
716 | return '%s instance' % text_repr(klass) | |
717 | except KeyboardInterrupt: |
|
717 | except KeyboardInterrupt: | |
718 | raise |
|
718 | raise | |
719 | except: |
|
719 | except: | |
720 | return 'UNRECOVERABLE REPR FAILURE' |
|
720 | return 'UNRECOVERABLE REPR FAILURE' | |
721 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
721 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) | |
722 | def nullrepr(value, repr=text_repr): return '' |
|
722 | def nullrepr(value, repr=text_repr): return '' | |
723 |
|
723 | |||
724 | # meat of the code begins |
|
724 | # meat of the code begins | |
725 | try: |
|
725 | try: | |
726 | etype = etype.__name__ |
|
726 | etype = etype.__name__ | |
727 | except AttributeError: |
|
727 | except AttributeError: | |
728 | pass |
|
728 | pass | |
729 |
|
729 | |||
730 | if self.long_header: |
|
730 | if self.long_header: | |
731 | # Header with the exception type, python version, and date |
|
731 | # Header with the exception type, python version, and date | |
732 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
732 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable | |
733 | date = time.ctime(time.time()) |
|
733 | date = time.ctime(time.time()) | |
734 |
|
734 | |||
735 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
735 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, | |
736 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
736 | exc, ' '*(75-len(str(etype))-len(pyver)), | |
737 | pyver, date.rjust(75) ) |
|
737 | pyver, date.rjust(75) ) | |
738 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
738 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ | |
739 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
739 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
740 | else: |
|
740 | else: | |
741 | # Simplified header |
|
741 | # Simplified header | |
742 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
742 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, | |
743 | 'Traceback (most recent call last)'.\ |
|
743 | 'Traceback (most recent call last)'.\ | |
744 | rjust(75 - len(str(etype)) ) ) |
|
744 | rjust(75 - len(str(etype)) ) ) | |
745 | frames = [] |
|
745 | frames = [] | |
746 | # Flush cache before calling inspect. This helps alleviate some of the |
|
746 | # Flush cache before calling inspect. This helps alleviate some of the | |
747 | # problems with python 2.3's inspect.py. |
|
747 | # problems with python 2.3's inspect.py. | |
748 | ##self.check_cache() |
|
748 | ##self.check_cache() | |
749 | # Drop topmost frames if requested |
|
749 | # Drop topmost frames if requested | |
750 | try: |
|
750 | try: | |
751 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
751 | # Try the default getinnerframes and Alex's: Alex's fixes some | |
752 | # problems, but it generates empty tracebacks for console errors |
|
752 | # problems, but it generates empty tracebacks for console errors | |
753 | # (5 blanks lines) where none should be returned. |
|
753 | # (5 blanks lines) where none should be returned. | |
754 | #records = inspect.getinnerframes(etb, context)[tb_offset:] |
|
754 | #records = inspect.getinnerframes(etb, context)[tb_offset:] | |
755 | #print 'python records:', records # dbg |
|
755 | #print 'python records:', records # dbg | |
756 | records = _fixed_getinnerframes(etb, context, tb_offset) |
|
756 | records = _fixed_getinnerframes(etb, context, tb_offset) | |
757 | #print 'alex records:', records # dbg |
|
757 | #print 'alex records:', records # dbg | |
758 | except: |
|
758 | except: | |
759 |
|
759 | |||
760 | # FIXME: I've been getting many crash reports from python 2.3 |
|
760 | # FIXME: I've been getting many crash reports from python 2.3 | |
761 | # users, traceable to inspect.py. If I can find a small test-case |
|
761 | # users, traceable to inspect.py. If I can find a small test-case | |
762 | # to reproduce this, I should either write a better workaround or |
|
762 | # to reproduce this, I should either write a better workaround or | |
763 | # file a bug report against inspect (if that's the real problem). |
|
763 | # file a bug report against inspect (if that's the real problem). | |
764 | # So far, I haven't been able to find an isolated example to |
|
764 | # So far, I haven't been able to find an isolated example to | |
765 | # reproduce the problem. |
|
765 | # reproduce the problem. | |
766 | inspect_error() |
|
766 | inspect_error() | |
767 | traceback.print_exc(file=self.ostream) |
|
767 | traceback.print_exc(file=self.ostream) | |
768 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
768 | info('\nUnfortunately, your original traceback can not be constructed.\n') | |
769 | return '' |
|
769 | return '' | |
770 |
|
770 | |||
771 | # build some color string templates outside these nested loops |
|
771 | # build some color string templates outside these nested loops | |
772 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
772 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) | |
773 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
773 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, | |
774 | ColorsNormal) |
|
774 | ColorsNormal) | |
775 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
775 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ | |
776 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
776 | (Colors.vName, Colors.valEm, ColorsNormal) | |
777 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
777 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) | |
778 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
778 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, | |
779 | Colors.vName, ColorsNormal) |
|
779 | Colors.vName, ColorsNormal) | |
780 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
780 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) | |
781 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
781 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) | |
782 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
782 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, | |
783 | ColorsNormal) |
|
783 | ColorsNormal) | |
784 |
|
784 | |||
785 | # now, loop over all records printing context and info |
|
785 | # now, loop over all records printing context and info | |
786 | abspath = os.path.abspath |
|
786 | abspath = os.path.abspath | |
787 | for frame, file, lnum, func, lines, index in records: |
|
787 | for frame, file, lnum, func, lines, index in records: | |
788 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
788 | #print '*** record:',file,lnum,func,lines,index # dbg | |
789 |
|
789 | |||
790 | if not file: |
|
790 | if not file: | |
791 | file = '?' |
|
791 | file = '?' | |
792 | elif not(file.startswith("<") and file.endswith(">")): |
|
792 | elif not(file.startswith("<") and file.endswith(">")): | |
793 | # Guess that filenames like <string> aren't real filenames, so |
|
793 | # Guess that filenames like <string> aren't real filenames, so | |
794 | # don't call abspath on them. |
|
794 | # don't call abspath on them. | |
795 | try: |
|
795 | try: | |
796 | file = abspath(file) |
|
796 | file = abspath(file) | |
797 | except OSError: |
|
797 | except OSError: | |
798 | # Not sure if this can still happen: abspath now works with |
|
798 | # Not sure if this can still happen: abspath now works with | |
799 | # file names like <string> |
|
799 | # file names like <string> | |
800 | pass |
|
800 | pass | |
801 |
|
801 | |||
802 | link = tpl_link % file |
|
802 | link = tpl_link % file | |
803 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
803 | args, varargs, varkw, locals = inspect.getargvalues(frame) | |
804 |
|
804 | |||
805 | if func == '?': |
|
805 | if func == '?': | |
806 | call = '' |
|
806 | call = '' | |
807 | else: |
|
807 | else: | |
808 | # Decide whether to include variable details or not |
|
808 | # Decide whether to include variable details or not | |
809 | var_repr = self.include_vars and eqrepr or nullrepr |
|
809 | var_repr = self.include_vars and eqrepr or nullrepr | |
810 | try: |
|
810 | try: | |
811 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
811 | call = tpl_call % (func,inspect.formatargvalues(args, | |
812 | varargs, varkw, |
|
812 | varargs, varkw, | |
813 | locals,formatvalue=var_repr)) |
|
813 | locals,formatvalue=var_repr)) | |
814 | except KeyError: |
|
814 | except KeyError: | |
815 | # This happens in situations like errors inside generator |
|
815 | # This happens in situations like errors inside generator | |
816 | # expressions, where local variables are listed in the |
|
816 | # expressions, where local variables are listed in the | |
817 | # line, but can't be extracted from the frame. I'm not |
|
817 | # line, but can't be extracted from the frame. I'm not | |
818 | # 100% sure this isn't actually a bug in inspect itself, |
|
818 | # 100% sure this isn't actually a bug in inspect itself, | |
819 | # but since there's no info for us to compute with, the |
|
819 | # but since there's no info for us to compute with, the | |
820 | # best we can do is report the failure and move on. Here |
|
820 | # best we can do is report the failure and move on. Here | |
821 | # we must *not* call any traceback construction again, |
|
821 | # we must *not* call any traceback construction again, | |
822 | # because that would mess up use of %debug later on. So we |
|
822 | # because that would mess up use of %debug later on. So we | |
823 | # simply report the failure and move on. The only |
|
823 | # simply report the failure and move on. The only | |
824 | # limitation will be that this frame won't have locals |
|
824 | # limitation will be that this frame won't have locals | |
825 | # listed in the call signature. Quite subtle problem... |
|
825 | # listed in the call signature. Quite subtle problem... | |
826 | # I can't think of a good way to validate this in a unit |
|
826 | # I can't think of a good way to validate this in a unit | |
827 | # test, but running a script consisting of: |
|
827 | # test, but running a script consisting of: | |
828 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
828 | # dict( (k,v.strip()) for (k,v) in range(10) ) | |
829 | # will illustrate the error, if this exception catch is |
|
829 | # will illustrate the error, if this exception catch is | |
830 | # disabled. |
|
830 | # disabled. | |
831 | call = tpl_call_fail % func |
|
831 | call = tpl_call_fail % func | |
832 |
|
832 | |||
833 | # Don't attempt to tokenize binary files. |
|
833 | # Don't attempt to tokenize binary files. | |
834 | if file.endswith(('.so', '.pyd', '.dll')): |
|
834 | if file.endswith(('.so', '.pyd', '.dll')): | |
835 | frames.append('%s %s\n' % (link,call)) |
|
835 | frames.append('%s %s\n' % (link,call)) | |
836 | continue |
|
836 | continue | |
837 | elif file.endswith(('.pyc','.pyo')): |
|
837 | elif file.endswith(('.pyc','.pyo')): | |
838 | # Look up the corresponding source file. |
|
838 | # Look up the corresponding source file. | |
839 | file = pyfile.source_from_cache(file) |
|
839 | file = pyfile.source_from_cache(file) | |
840 |
|
840 | |||
841 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
841 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): | |
842 | line = getline(file, lnum[0]) |
|
842 | line = getline(file, lnum[0]) | |
843 | lnum[0] += 1 |
|
843 | lnum[0] += 1 | |
844 | return line |
|
844 | return line | |
845 |
|
845 | |||
846 | # Build the list of names on this line of code where the exception |
|
846 | # Build the list of names on this line of code where the exception | |
847 | # occurred. |
|
847 | # occurred. | |
848 | try: |
|
848 | try: | |
849 | names = [] |
|
849 | names = [] | |
850 | name_cont = False |
|
850 | name_cont = False | |
851 |
|
851 | |||
852 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
852 | for token_type, token, start, end, line in generate_tokens(linereader): | |
853 | # build composite names |
|
853 | # build composite names | |
854 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
854 | if token_type == tokenize.NAME and token not in keyword.kwlist: | |
855 | if name_cont: |
|
855 | if name_cont: | |
856 | # Continuation of a dotted name |
|
856 | # Continuation of a dotted name | |
857 | try: |
|
857 | try: | |
858 | names[-1].append(token) |
|
858 | names[-1].append(token) | |
859 | except IndexError: |
|
859 | except IndexError: | |
860 | names.append([token]) |
|
860 | names.append([token]) | |
861 | name_cont = False |
|
861 | name_cont = False | |
862 | else: |
|
862 | else: | |
863 | # Regular new names. We append everything, the caller |
|
863 | # Regular new names. We append everything, the caller | |
864 | # will be responsible for pruning the list later. It's |
|
864 | # will be responsible for pruning the list later. It's | |
865 | # very tricky to try to prune as we go, b/c composite |
|
865 | # very tricky to try to prune as we go, b/c composite | |
866 | # names can fool us. The pruning at the end is easy |
|
866 | # names can fool us. The pruning at the end is easy | |
867 | # to do (or the caller can print a list with repeated |
|
867 | # to do (or the caller can print a list with repeated | |
868 | # names if so desired. |
|
868 | # names if so desired. | |
869 | names.append([token]) |
|
869 | names.append([token]) | |
870 | elif token == '.': |
|
870 | elif token == '.': | |
871 | name_cont = True |
|
871 | name_cont = True | |
872 | elif token_type == tokenize.NEWLINE: |
|
872 | elif token_type == tokenize.NEWLINE: | |
873 | break |
|
873 | break | |
874 |
|
874 | |||
875 | except (IndexError, UnicodeDecodeError): |
|
875 | except (IndexError, UnicodeDecodeError): | |
876 | # signals exit of tokenizer |
|
876 | # signals exit of tokenizer | |
877 | pass |
|
877 | pass | |
878 | except tokenize.TokenError as msg: |
|
878 | except tokenize.TokenError as msg: | |
879 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
879 | _m = ("An unexpected error occurred while tokenizing input\n" | |
880 | "The following traceback may be corrupted or invalid\n" |
|
880 | "The following traceback may be corrupted or invalid\n" | |
881 | "The error message is: %s\n" % msg) |
|
881 | "The error message is: %s\n" % msg) | |
882 | error(_m) |
|
882 | error(_m) | |
883 |
|
883 | |||
884 | # Join composite names (e.g. "dict.fromkeys") |
|
884 | # Join composite names (e.g. "dict.fromkeys") | |
885 | names = ['.'.join(n) for n in names] |
|
885 | names = ['.'.join(n) for n in names] | |
886 | # prune names list of duplicates, but keep the right order |
|
886 | # prune names list of duplicates, but keep the right order | |
887 | unique_names = uniq_stable(names) |
|
887 | unique_names = uniq_stable(names) | |
888 |
|
888 | |||
889 | # Start loop over vars |
|
889 | # Start loop over vars | |
890 | lvals = [] |
|
890 | lvals = [] | |
891 | if self.include_vars: |
|
891 | if self.include_vars: | |
892 | for name_full in unique_names: |
|
892 | for name_full in unique_names: | |
893 | name_base = name_full.split('.',1)[0] |
|
893 | name_base = name_full.split('.',1)[0] | |
894 | if name_base in frame.f_code.co_varnames: |
|
894 | if name_base in frame.f_code.co_varnames: | |
895 | if locals.has_key(name_base): |
|
895 | if locals.has_key(name_base): | |
896 | try: |
|
896 | try: | |
897 | value = repr(eval(name_full,locals)) |
|
897 | value = repr(eval(name_full,locals)) | |
898 | except: |
|
898 | except: | |
899 | value = undefined |
|
899 | value = undefined | |
900 | else: |
|
900 | else: | |
901 | value = undefined |
|
901 | value = undefined | |
902 | name = tpl_local_var % name_full |
|
902 | name = tpl_local_var % name_full | |
903 | else: |
|
903 | else: | |
904 | if frame.f_globals.has_key(name_base): |
|
904 | if frame.f_globals.has_key(name_base): | |
905 | try: |
|
905 | try: | |
906 | value = repr(eval(name_full,frame.f_globals)) |
|
906 | value = repr(eval(name_full,frame.f_globals)) | |
907 | except: |
|
907 | except: | |
908 | value = undefined |
|
908 | value = undefined | |
909 | else: |
|
909 | else: | |
910 | value = undefined |
|
910 | value = undefined | |
911 | name = tpl_global_var % name_full |
|
911 | name = tpl_global_var % name_full | |
912 | lvals.append(tpl_name_val % (name,value)) |
|
912 | lvals.append(tpl_name_val % (name,value)) | |
913 | if lvals: |
|
913 | if lvals: | |
914 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
914 | lvals = '%s%s' % (indent,em_normal.join(lvals)) | |
915 | else: |
|
915 | else: | |
916 | lvals = '' |
|
916 | lvals = '' | |
917 |
|
917 | |||
918 | level = '%s %s\n' % (link,call) |
|
918 | level = '%s %s\n' % (link,call) | |
919 |
|
919 | |||
920 | if index is None: |
|
920 | if index is None: | |
921 | frames.append(level) |
|
921 | frames.append(level) | |
922 | else: |
|
922 | else: | |
923 | frames.append('%s%s' % (level,''.join( |
|
923 | frames.append('%s%s' % (level,''.join( | |
924 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
924 | _format_traceback_lines(lnum,index,lines,Colors,lvals, | |
925 | col_scheme)))) |
|
925 | col_scheme)))) | |
926 |
|
926 | |||
927 | # Get (safely) a string form of the exception info |
|
927 | # Get (safely) a string form of the exception info | |
928 | try: |
|
928 | try: | |
929 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
929 | etype_str,evalue_str = map(str,(etype,evalue)) | |
930 | except: |
|
930 | except: | |
931 | # User exception is improperly defined. |
|
931 | # User exception is improperly defined. | |
932 | etype,evalue = str,sys.exc_info()[:2] |
|
932 | etype,evalue = str,sys.exc_info()[:2] | |
933 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
933 | etype_str,evalue_str = map(str,(etype,evalue)) | |
934 | # ... and format it |
|
934 | # ... and format it | |
935 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
935 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, | |
936 | ColorsNormal, evalue_str)] |
|
936 | ColorsNormal, evalue_str)] | |
937 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
937 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: | |
938 | try: |
|
938 | try: | |
939 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
939 | names = [w for w in dir(evalue) if isinstance(w, basestring)] | |
940 | except: |
|
940 | except: | |
941 | # Every now and then, an object with funny inernals blows up |
|
941 | # Every now and then, an object with funny inernals blows up | |
942 | # when dir() is called on it. We do the best we can to report |
|
942 | # when dir() is called on it. We do the best we can to report | |
943 | # the problem and continue |
|
943 | # the problem and continue | |
944 | _m = '%sException reporting error (object with broken dir())%s:' |
|
944 | _m = '%sException reporting error (object with broken dir())%s:' | |
945 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
945 | exception.append(_m % (Colors.excName,ColorsNormal)) | |
946 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
946 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) | |
947 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
947 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, | |
948 | ColorsNormal, evalue_str)) |
|
948 | ColorsNormal, evalue_str)) | |
949 | names = [] |
|
949 | names = [] | |
950 | for name in names: |
|
950 | for name in names: | |
951 | value = text_repr(getattr(evalue, name)) |
|
951 | value = text_repr(getattr(evalue, name)) | |
952 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
952 | exception.append('\n%s%s = %s' % (indent, name, value)) | |
953 |
|
953 | |||
954 | # vds: >> |
|
954 | # vds: >> | |
955 | if records: |
|
955 | if records: | |
956 | filepath, lnum = records[-1][1:3] |
|
956 | filepath, lnum = records[-1][1:3] | |
957 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
957 | #print "file:", str(file), "linenb", str(lnum) # dbg | |
958 | filepath = os.path.abspath(filepath) |
|
958 | filepath = os.path.abspath(filepath) | |
959 | ipinst = ipapi.get() |
|
959 | ipinst = ipapi.get() | |
960 | if ipinst is not None: |
|
960 | if ipinst is not None: | |
961 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
961 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) | |
962 | # vds: << |
|
962 | # vds: << | |
963 |
|
963 | |||
964 | # return all our info assembled as a single string |
|
964 | # return all our info assembled as a single string | |
965 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
965 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) | |
966 | return [head] + frames + [''.join(exception[0])] |
|
966 | return [head] + frames + [''.join(exception[0])] | |
967 |
|
967 | |||
968 | def debugger(self,force=False): |
|
968 | def debugger(self,force=False): | |
969 | """Call up the pdb debugger if desired, always clean up the tb |
|
969 | """Call up the pdb debugger if desired, always clean up the tb | |
970 | reference. |
|
970 | reference. | |
971 |
|
971 | |||
972 | Keywords: |
|
972 | Keywords: | |
973 |
|
973 | |||
974 | - force(False): by default, this routine checks the instance call_pdb |
|
974 | - force(False): by default, this routine checks the instance call_pdb | |
975 | flag and does not actually invoke the debugger if the flag is false. |
|
975 | flag and does not actually invoke the debugger if the flag is false. | |
976 | The 'force' option forces the debugger to activate even if the flag |
|
976 | The 'force' option forces the debugger to activate even if the flag | |
977 | is false. |
|
977 | is false. | |
978 |
|
978 | |||
979 | If the call_pdb flag is set, the pdb interactive debugger is |
|
979 | If the call_pdb flag is set, the pdb interactive debugger is | |
980 | invoked. In all cases, the self.tb reference to the current traceback |
|
980 | invoked. In all cases, the self.tb reference to the current traceback | |
981 | is deleted to prevent lingering references which hamper memory |
|
981 | is deleted to prevent lingering references which hamper memory | |
982 | management. |
|
982 | management. | |
983 |
|
983 | |||
984 | Note that each call to pdb() does an 'import readline', so if your app |
|
984 | Note that each call to pdb() does an 'import readline', so if your app | |
985 | requires a special setup for the readline completers, you'll have to |
|
985 | requires a special setup for the readline completers, you'll have to | |
986 | fix that by hand after invoking the exception handler.""" |
|
986 | fix that by hand after invoking the exception handler.""" | |
987 |
|
987 | |||
988 | if force or self.call_pdb: |
|
988 | if force or self.call_pdb: | |
989 | if self.pdb is None: |
|
989 | if self.pdb is None: | |
990 | self.pdb = debugger.Pdb( |
|
990 | self.pdb = debugger.Pdb( | |
991 | self.color_scheme_table.active_scheme_name) |
|
991 | self.color_scheme_table.active_scheme_name) | |
992 | # the system displayhook may have changed, restore the original |
|
992 | # the system displayhook may have changed, restore the original | |
993 | # for pdb |
|
993 | # for pdb | |
994 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
994 | display_trap = DisplayTrap(hook=sys.__displayhook__) | |
995 | with display_trap: |
|
995 | with display_trap: | |
996 | self.pdb.reset() |
|
996 | self.pdb.reset() | |
997 | # Find the right frame so we don't pop up inside ipython itself |
|
997 | # Find the right frame so we don't pop up inside ipython itself | |
998 | if hasattr(self,'tb') and self.tb is not None: |
|
998 | if hasattr(self,'tb') and self.tb is not None: | |
999 | etb = self.tb |
|
999 | etb = self.tb | |
1000 | else: |
|
1000 | else: | |
1001 | etb = self.tb = sys.last_traceback |
|
1001 | etb = self.tb = sys.last_traceback | |
1002 | while self.tb is not None and self.tb.tb_next is not None: |
|
1002 | while self.tb is not None and self.tb.tb_next is not None: | |
1003 | self.tb = self.tb.tb_next |
|
1003 | self.tb = self.tb.tb_next | |
1004 | if etb and etb.tb_next: |
|
1004 | if etb and etb.tb_next: | |
1005 | etb = etb.tb_next |
|
1005 | etb = etb.tb_next | |
1006 | self.pdb.botframe = etb.tb_frame |
|
1006 | self.pdb.botframe = etb.tb_frame | |
1007 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1007 | self.pdb.interaction(self.tb.tb_frame, self.tb) | |
1008 |
|
1008 | |||
1009 | if hasattr(self,'tb'): |
|
1009 | if hasattr(self,'tb'): | |
1010 | del self.tb |
|
1010 | del self.tb | |
1011 |
|
1011 | |||
1012 | def handler(self, info=None): |
|
1012 | def handler(self, info=None): | |
1013 | (etype, evalue, etb) = info or sys.exc_info() |
|
1013 | (etype, evalue, etb) = info or sys.exc_info() | |
1014 | self.tb = etb |
|
1014 | self.tb = etb | |
1015 | ostream = self.ostream |
|
1015 | ostream = self.ostream | |
1016 | ostream.flush() |
|
1016 | ostream.flush() | |
1017 | ostream.write(self.text(etype, evalue, etb)) |
|
1017 | ostream.write(self.text(etype, evalue, etb)) | |
1018 | ostream.write('\n') |
|
1018 | ostream.write('\n') | |
1019 | ostream.flush() |
|
1019 | ostream.flush() | |
1020 |
|
1020 | |||
1021 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1021 | # Changed so an instance can just be called as VerboseTB_inst() and print | |
1022 | # out the right info on its own. |
|
1022 | # out the right info on its own. | |
1023 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1023 | def __call__(self, etype=None, evalue=None, etb=None): | |
1024 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1024 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" | |
1025 | if etb is None: |
|
1025 | if etb is None: | |
1026 | self.handler() |
|
1026 | self.handler() | |
1027 | else: |
|
1027 | else: | |
1028 | self.handler((etype, evalue, etb)) |
|
1028 | self.handler((etype, evalue, etb)) | |
1029 | try: |
|
1029 | try: | |
1030 | self.debugger() |
|
1030 | self.debugger() | |
1031 | except KeyboardInterrupt: |
|
1031 | except KeyboardInterrupt: | |
1032 | print "\nKeyboardInterrupt" |
|
1032 | print "\nKeyboardInterrupt" | |
1033 |
|
1033 | |||
1034 | #---------------------------------------------------------------------------- |
|
1034 | #---------------------------------------------------------------------------- | |
1035 | class FormattedTB(VerboseTB, ListTB): |
|
1035 | class FormattedTB(VerboseTB, ListTB): | |
1036 | """Subclass ListTB but allow calling with a traceback. |
|
1036 | """Subclass ListTB but allow calling with a traceback. | |
1037 |
|
1037 | |||
1038 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1038 | It can thus be used as a sys.excepthook for Python > 2.1. | |
1039 |
|
1039 | |||
1040 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1040 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. | |
1041 |
|
1041 | |||
1042 | Allows a tb_offset to be specified. This is useful for situations where |
|
1042 | Allows a tb_offset to be specified. This is useful for situations where | |
1043 | one needs to remove a number of topmost frames from the traceback (such as |
|
1043 | one needs to remove a number of topmost frames from the traceback (such as | |
1044 | occurs with python programs that themselves execute other python code, |
|
1044 | occurs with python programs that themselves execute other python code, | |
1045 | like Python shells). """ |
|
1045 | like Python shells). """ | |
1046 |
|
1046 | |||
1047 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1047 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, | |
1048 | ostream=None, |
|
1048 | ostream=None, | |
1049 | tb_offset=0, long_header=False, include_vars=False, |
|
1049 | tb_offset=0, long_header=False, include_vars=False, | |
1050 | check_cache=None): |
|
1050 | check_cache=None): | |
1051 |
|
1051 | |||
1052 | # NEVER change the order of this list. Put new modes at the end: |
|
1052 | # NEVER change the order of this list. Put new modes at the end: | |
1053 | self.valid_modes = ['Plain','Context','Verbose'] |
|
1053 | self.valid_modes = ['Plain','Context','Verbose'] | |
1054 | self.verbose_modes = self.valid_modes[1:3] |
|
1054 | self.verbose_modes = self.valid_modes[1:3] | |
1055 |
|
1055 | |||
1056 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1056 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | |
1057 | ostream=ostream, tb_offset=tb_offset, |
|
1057 | ostream=ostream, tb_offset=tb_offset, | |
1058 | long_header=long_header, include_vars=include_vars, |
|
1058 | long_header=long_header, include_vars=include_vars, | |
1059 | check_cache=check_cache) |
|
1059 | check_cache=check_cache) | |
1060 |
|
1060 | |||
1061 | # Different types of tracebacks are joined with different separators to |
|
1061 | # Different types of tracebacks are joined with different separators to | |
1062 | # form a single string. They are taken from this dict |
|
1062 | # form a single string. They are taken from this dict | |
1063 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1063 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') | |
1064 | # set_mode also sets the tb_join_char attribute |
|
1064 | # set_mode also sets the tb_join_char attribute | |
1065 | self.set_mode(mode) |
|
1065 | self.set_mode(mode) | |
1066 |
|
1066 | |||
1067 | def _extract_tb(self,tb): |
|
1067 | def _extract_tb(self,tb): | |
1068 | if tb: |
|
1068 | if tb: | |
1069 | return traceback.extract_tb(tb) |
|
1069 | return traceback.extract_tb(tb) | |
1070 | else: |
|
1070 | else: | |
1071 | return None |
|
1071 | return None | |
1072 |
|
1072 | |||
1073 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): |
|
1073 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): | |
1074 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1074 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | |
1075 | mode = self.mode |
|
1075 | mode = self.mode | |
1076 | if mode in self.verbose_modes: |
|
1076 | if mode in self.verbose_modes: | |
1077 | # Verbose modes need a full traceback |
|
1077 | # Verbose modes need a full traceback | |
1078 | return VerboseTB.structured_traceback( |
|
1078 | return VerboseTB.structured_traceback( | |
1079 | self, etype, value, tb, tb_offset, context |
|
1079 | self, etype, value, tb, tb_offset, context | |
1080 | ) |
|
1080 | ) | |
1081 | else: |
|
1081 | else: | |
1082 | # We must check the source cache because otherwise we can print |
|
1082 | # We must check the source cache because otherwise we can print | |
1083 | # out-of-date source code. |
|
1083 | # out-of-date source code. | |
1084 | self.check_cache() |
|
1084 | self.check_cache() | |
1085 | # Now we can extract and format the exception |
|
1085 | # Now we can extract and format the exception | |
1086 | elist = self._extract_tb(tb) |
|
1086 | elist = self._extract_tb(tb) | |
1087 | return ListTB.structured_traceback( |
|
1087 | return ListTB.structured_traceback( | |
1088 | self, etype, value, elist, tb_offset, context |
|
1088 | self, etype, value, elist, tb_offset, context | |
1089 | ) |
|
1089 | ) | |
1090 |
|
1090 | |||
1091 | def stb2text(self, stb): |
|
1091 | def stb2text(self, stb): | |
1092 | """Convert a structured traceback (a list) to a string.""" |
|
1092 | """Convert a structured traceback (a list) to a string.""" | |
1093 | return self.tb_join_char.join(stb) |
|
1093 | return self.tb_join_char.join(stb) | |
1094 |
|
1094 | |||
1095 |
|
1095 | |||
1096 | def set_mode(self,mode=None): |
|
1096 | def set_mode(self,mode=None): | |
1097 | """Switch to the desired mode. |
|
1097 | """Switch to the desired mode. | |
1098 |
|
1098 | |||
1099 | If mode is not specified, cycles through the available modes.""" |
|
1099 | If mode is not specified, cycles through the available modes.""" | |
1100 |
|
1100 | |||
1101 | if not mode: |
|
1101 | if not mode: | |
1102 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
1102 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ | |
1103 | len(self.valid_modes) |
|
1103 | len(self.valid_modes) | |
1104 | self.mode = self.valid_modes[new_idx] |
|
1104 | self.mode = self.valid_modes[new_idx] | |
1105 | elif mode not in self.valid_modes: |
|
1105 | elif mode not in self.valid_modes: | |
1106 |
raise ValueError |
|
1106 | raise ValueError('Unrecognized mode in FormattedTB: <'+mode+'>\n' | |
1107 | 'Valid modes: '+str(self.valid_modes) |
|
1107 | 'Valid modes: '+str(self.valid_modes)) | |
1108 | else: |
|
1108 | else: | |
1109 | self.mode = mode |
|
1109 | self.mode = mode | |
1110 | # include variable details only in 'Verbose' mode |
|
1110 | # include variable details only in 'Verbose' mode | |
1111 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1111 | self.include_vars = (self.mode == self.valid_modes[2]) | |
1112 | # Set the join character for generating text tracebacks |
|
1112 | # Set the join character for generating text tracebacks | |
1113 | self.tb_join_char = self._join_chars[self.mode] |
|
1113 | self.tb_join_char = self._join_chars[self.mode] | |
1114 |
|
1114 | |||
1115 | # some convenient shorcuts |
|
1115 | # some convenient shorcuts | |
1116 | def plain(self): |
|
1116 | def plain(self): | |
1117 | self.set_mode(self.valid_modes[0]) |
|
1117 | self.set_mode(self.valid_modes[0]) | |
1118 |
|
1118 | |||
1119 | def context(self): |
|
1119 | def context(self): | |
1120 | self.set_mode(self.valid_modes[1]) |
|
1120 | self.set_mode(self.valid_modes[1]) | |
1121 |
|
1121 | |||
1122 | def verbose(self): |
|
1122 | def verbose(self): | |
1123 | self.set_mode(self.valid_modes[2]) |
|
1123 | self.set_mode(self.valid_modes[2]) | |
1124 |
|
1124 | |||
1125 | #---------------------------------------------------------------------------- |
|
1125 | #---------------------------------------------------------------------------- | |
1126 | class AutoFormattedTB(FormattedTB): |
|
1126 | class AutoFormattedTB(FormattedTB): | |
1127 | """A traceback printer which can be called on the fly. |
|
1127 | """A traceback printer which can be called on the fly. | |
1128 |
|
1128 | |||
1129 | It will find out about exceptions by itself. |
|
1129 | It will find out about exceptions by itself. | |
1130 |
|
1130 | |||
1131 | A brief example: |
|
1131 | A brief example: | |
1132 |
|
1132 | |||
1133 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1133 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | |
1134 | try: |
|
1134 | try: | |
1135 | ... |
|
1135 | ... | |
1136 | except: |
|
1136 | except: | |
1137 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1137 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | |
1138 | """ |
|
1138 | """ | |
1139 |
|
1139 | |||
1140 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1140 | def __call__(self,etype=None,evalue=None,etb=None, | |
1141 | out=None,tb_offset=None): |
|
1141 | out=None,tb_offset=None): | |
1142 | """Print out a formatted exception traceback. |
|
1142 | """Print out a formatted exception traceback. | |
1143 |
|
1143 | |||
1144 | Optional arguments: |
|
1144 | Optional arguments: | |
1145 | - out: an open file-like object to direct output to. |
|
1145 | - out: an open file-like object to direct output to. | |
1146 |
|
1146 | |||
1147 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1147 | - tb_offset: the number of frames to skip over in the stack, on a | |
1148 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1148 | per-call basis (this overrides temporarily the instance's tb_offset | |
1149 | given at initialization time. """ |
|
1149 | given at initialization time. """ | |
1150 |
|
1150 | |||
1151 |
|
1151 | |||
1152 | if out is None: |
|
1152 | if out is None: | |
1153 | out = self.ostream |
|
1153 | out = self.ostream | |
1154 | out.flush() |
|
1154 | out.flush() | |
1155 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1155 | out.write(self.text(etype, evalue, etb, tb_offset)) | |
1156 | out.write('\n') |
|
1156 | out.write('\n') | |
1157 | out.flush() |
|
1157 | out.flush() | |
1158 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1158 | # FIXME: we should remove the auto pdb behavior from here and leave | |
1159 | # that to the clients. |
|
1159 | # that to the clients. | |
1160 | try: |
|
1160 | try: | |
1161 | self.debugger() |
|
1161 | self.debugger() | |
1162 | except KeyboardInterrupt: |
|
1162 | except KeyboardInterrupt: | |
1163 | print "\nKeyboardInterrupt" |
|
1163 | print "\nKeyboardInterrupt" | |
1164 |
|
1164 | |||
1165 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1165 | def structured_traceback(self, etype=None, value=None, tb=None, | |
1166 | tb_offset=None, context=5): |
|
1166 | tb_offset=None, context=5): | |
1167 | if etype is None: |
|
1167 | if etype is None: | |
1168 | etype,value,tb = sys.exc_info() |
|
1168 | etype,value,tb = sys.exc_info() | |
1169 | self.tb = tb |
|
1169 | self.tb = tb | |
1170 | return FormattedTB.structured_traceback( |
|
1170 | return FormattedTB.structured_traceback( | |
1171 | self, etype, value, tb, tb_offset, context) |
|
1171 | self, etype, value, tb, tb_offset, context) | |
1172 |
|
1172 | |||
1173 | #--------------------------------------------------------------------------- |
|
1173 | #--------------------------------------------------------------------------- | |
1174 |
|
1174 | |||
1175 | # A simple class to preserve Nathan's original functionality. |
|
1175 | # A simple class to preserve Nathan's original functionality. | |
1176 | class ColorTB(FormattedTB): |
|
1176 | class ColorTB(FormattedTB): | |
1177 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1177 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" | |
1178 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1178 | def __init__(self,color_scheme='Linux',call_pdb=0): | |
1179 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1179 | FormattedTB.__init__(self,color_scheme=color_scheme, | |
1180 | call_pdb=call_pdb) |
|
1180 | call_pdb=call_pdb) | |
1181 |
|
1181 | |||
1182 |
|
1182 | |||
1183 | class SyntaxTB(ListTB): |
|
1183 | class SyntaxTB(ListTB): | |
1184 | """Extension which holds some state: the last exception value""" |
|
1184 | """Extension which holds some state: the last exception value""" | |
1185 |
|
1185 | |||
1186 | def __init__(self,color_scheme = 'NoColor'): |
|
1186 | def __init__(self,color_scheme = 'NoColor'): | |
1187 | ListTB.__init__(self,color_scheme) |
|
1187 | ListTB.__init__(self,color_scheme) | |
1188 | self.last_syntax_error = None |
|
1188 | self.last_syntax_error = None | |
1189 |
|
1189 | |||
1190 | def __call__(self, etype, value, elist): |
|
1190 | def __call__(self, etype, value, elist): | |
1191 | self.last_syntax_error = value |
|
1191 | self.last_syntax_error = value | |
1192 | ListTB.__call__(self,etype,value,elist) |
|
1192 | ListTB.__call__(self,etype,value,elist) | |
1193 |
|
1193 | |||
1194 | def clear_err_state(self): |
|
1194 | def clear_err_state(self): | |
1195 | """Return the current error state and clear it""" |
|
1195 | """Return the current error state and clear it""" | |
1196 | e = self.last_syntax_error |
|
1196 | e = self.last_syntax_error | |
1197 | self.last_syntax_error = None |
|
1197 | self.last_syntax_error = None | |
1198 | return e |
|
1198 | return e | |
1199 |
|
1199 | |||
1200 | def stb2text(self, stb): |
|
1200 | def stb2text(self, stb): | |
1201 | """Convert a structured traceback (a list) to a string.""" |
|
1201 | """Convert a structured traceback (a list) to a string.""" | |
1202 | return ''.join(stb) |
|
1202 | return ''.join(stb) | |
1203 |
|
1203 | |||
1204 |
|
1204 | |||
1205 | #---------------------------------------------------------------------------- |
|
1205 | #---------------------------------------------------------------------------- | |
1206 | # module testing (minimal) |
|
1206 | # module testing (minimal) | |
1207 | if __name__ == "__main__": |
|
1207 | if __name__ == "__main__": | |
1208 | def spam(c, (d, e)): |
|
1208 | def spam(c, (d, e)): | |
1209 | x = c + d |
|
1209 | x = c + d | |
1210 | y = c * d |
|
1210 | y = c * d | |
1211 | foo(x, y) |
|
1211 | foo(x, y) | |
1212 |
|
1212 | |||
1213 | def foo(a, b, bar=1): |
|
1213 | def foo(a, b, bar=1): | |
1214 | eggs(a, b + bar) |
|
1214 | eggs(a, b + bar) | |
1215 |
|
1215 | |||
1216 | def eggs(f, g, z=globals()): |
|
1216 | def eggs(f, g, z=globals()): | |
1217 | h = f + g |
|
1217 | h = f + g | |
1218 | i = f - g |
|
1218 | i = f - g | |
1219 | return h / i |
|
1219 | return h / i | |
1220 |
|
1220 | |||
1221 | print '' |
|
1221 | print '' | |
1222 | print '*** Before ***' |
|
1222 | print '*** Before ***' | |
1223 | try: |
|
1223 | try: | |
1224 | print spam(1, (2, 3)) |
|
1224 | print spam(1, (2, 3)) | |
1225 | except: |
|
1225 | except: | |
1226 | traceback.print_exc() |
|
1226 | traceback.print_exc() | |
1227 | print '' |
|
1227 | print '' | |
1228 |
|
1228 | |||
1229 | handler = ColorTB() |
|
1229 | handler = ColorTB() | |
1230 | print '*** ColorTB ***' |
|
1230 | print '*** ColorTB ***' | |
1231 | try: |
|
1231 | try: | |
1232 | print spam(1, (2, 3)) |
|
1232 | print spam(1, (2, 3)) | |
1233 | except: |
|
1233 | except: | |
1234 | handler(*sys.exc_info()) |
|
1234 | handler(*sys.exc_info()) | |
1235 | print '' |
|
1235 | print '' | |
1236 |
|
1236 | |||
1237 | handler = VerboseTB() |
|
1237 | handler = VerboseTB() | |
1238 | print '*** VerboseTB ***' |
|
1238 | print '*** VerboseTB ***' | |
1239 | try: |
|
1239 | try: | |
1240 | print spam(1, (2, 3)) |
|
1240 | print spam(1, (2, 3)) | |
1241 | except: |
|
1241 | except: | |
1242 | handler(*sys.exc_info()) |
|
1242 | handler(*sys.exc_info()) | |
1243 | print '' |
|
1243 | print '' | |
1244 |
|
1244 |
@@ -1,281 +1,281 b'' | |||||
1 | """ |
|
1 | """ | |
2 | Decorators for labeling and modifying behavior of test objects. |
|
2 | Decorators for labeling and modifying behavior of test objects. | |
3 |
|
3 | |||
4 | Decorators that merely return a modified version of the original |
|
4 | Decorators that merely return a modified version of the original | |
5 | function object are straightforward. Decorators that return a new |
|
5 | function object are straightforward. Decorators that return a new | |
6 | function object need to use |
|
6 | function object need to use | |
7 | :: |
|
7 | :: | |
8 |
|
8 | |||
9 | nose.tools.make_decorator(original_function)(decorator) |
|
9 | nose.tools.make_decorator(original_function)(decorator) | |
10 |
|
10 | |||
11 | in returning the decorator, in order to preserve meta-data such as |
|
11 | in returning the decorator, in order to preserve meta-data such as | |
12 | function name, setup and teardown functions and so on - see |
|
12 | function name, setup and teardown functions and so on - see | |
13 | ``nose.tools`` for more information. |
|
13 | ``nose.tools`` for more information. | |
14 |
|
14 | |||
15 | """ |
|
15 | """ | |
16 | import warnings |
|
16 | import warnings | |
17 |
|
17 | |||
18 | # IPython changes: make this work if numpy not available |
|
18 | # IPython changes: make this work if numpy not available | |
19 | # Original code: |
|
19 | # Original code: | |
20 | #from numpy.testing.utils import \ |
|
20 | #from numpy.testing.utils import \ | |
21 | # WarningManager, WarningMessage |
|
21 | # WarningManager, WarningMessage | |
22 | # Our version: |
|
22 | # Our version: | |
23 | from _numpy_testing_utils import WarningManager |
|
23 | from _numpy_testing_utils import WarningManager | |
24 | try: |
|
24 | try: | |
25 | from _numpy_testing_noseclasses import KnownFailureTest |
|
25 | from _numpy_testing_noseclasses import KnownFailureTest | |
26 | except: |
|
26 | except: | |
27 | pass |
|
27 | pass | |
28 |
|
28 | |||
29 | # End IPython changes |
|
29 | # End IPython changes | |
30 |
|
30 | |||
31 | def slow(t): |
|
31 | def slow(t): | |
32 | """ |
|
32 | """ | |
33 | Label a test as 'slow'. |
|
33 | Label a test as 'slow'. | |
34 |
|
34 | |||
35 | The exact definition of a slow test is obviously both subjective and |
|
35 | The exact definition of a slow test is obviously both subjective and | |
36 | hardware-dependent, but in general any individual test that requires more |
|
36 | hardware-dependent, but in general any individual test that requires more | |
37 | than a second or two should be labeled as slow (the whole suite consists of |
|
37 | than a second or two should be labeled as slow (the whole suite consists of | |
38 | thousands of tests, so even a second is significant). |
|
38 | thousands of tests, so even a second is significant). | |
39 |
|
39 | |||
40 | Parameters |
|
40 | Parameters | |
41 | ---------- |
|
41 | ---------- | |
42 | t : callable |
|
42 | t : callable | |
43 | The test to label as slow. |
|
43 | The test to label as slow. | |
44 |
|
44 | |||
45 | Returns |
|
45 | Returns | |
46 | ------- |
|
46 | ------- | |
47 | t : callable |
|
47 | t : callable | |
48 | The decorated test `t`. |
|
48 | The decorated test `t`. | |
49 |
|
49 | |||
50 | Examples |
|
50 | Examples | |
51 | -------- |
|
51 | -------- | |
52 | The `numpy.testing` module includes ``import decorators as dec``. |
|
52 | The `numpy.testing` module includes ``import decorators as dec``. | |
53 | A test can be decorated as slow like this:: |
|
53 | A test can be decorated as slow like this:: | |
54 |
|
54 | |||
55 | from numpy.testing import * |
|
55 | from numpy.testing import * | |
56 |
|
56 | |||
57 | @dec.slow |
|
57 | @dec.slow | |
58 | def test_big(self): |
|
58 | def test_big(self): | |
59 | print 'Big, slow test' |
|
59 | print 'Big, slow test' | |
60 |
|
60 | |||
61 | """ |
|
61 | """ | |
62 |
|
62 | |||
63 | t.slow = True |
|
63 | t.slow = True | |
64 | return t |
|
64 | return t | |
65 |
|
65 | |||
66 | def setastest(tf=True): |
|
66 | def setastest(tf=True): | |
67 | """ |
|
67 | """ | |
68 | Signals to nose that this function is or is not a test. |
|
68 | Signals to nose that this function is or is not a test. | |
69 |
|
69 | |||
70 | Parameters |
|
70 | Parameters | |
71 | ---------- |
|
71 | ---------- | |
72 | tf : bool |
|
72 | tf : bool | |
73 | If True, specifies that the decorated callable is a test. |
|
73 | If True, specifies that the decorated callable is a test. | |
74 | If False, specifies that the decorated callable is not a test. |
|
74 | If False, specifies that the decorated callable is not a test. | |
75 | Default is True. |
|
75 | Default is True. | |
76 |
|
76 | |||
77 | Notes |
|
77 | Notes | |
78 | ----- |
|
78 | ----- | |
79 | This decorator can't use the nose namespace, because it can be |
|
79 | This decorator can't use the nose namespace, because it can be | |
80 | called from a non-test module. See also ``istest`` and ``nottest`` in |
|
80 | called from a non-test module. See also ``istest`` and ``nottest`` in | |
81 | ``nose.tools``. |
|
81 | ``nose.tools``. | |
82 |
|
82 | |||
83 | Examples |
|
83 | Examples | |
84 | -------- |
|
84 | -------- | |
85 | `setastest` can be used in the following way:: |
|
85 | `setastest` can be used in the following way:: | |
86 |
|
86 | |||
87 | from numpy.testing.decorators import setastest |
|
87 | from numpy.testing.decorators import setastest | |
88 |
|
88 | |||
89 | @setastest(False) |
|
89 | @setastest(False) | |
90 | def func_with_test_in_name(arg1, arg2): |
|
90 | def func_with_test_in_name(arg1, arg2): | |
91 | pass |
|
91 | pass | |
92 |
|
92 | |||
93 | """ |
|
93 | """ | |
94 | def set_test(t): |
|
94 | def set_test(t): | |
95 | t.__test__ = tf |
|
95 | t.__test__ = tf | |
96 | return t |
|
96 | return t | |
97 | return set_test |
|
97 | return set_test | |
98 |
|
98 | |||
99 | def skipif(skip_condition, msg=None): |
|
99 | def skipif(skip_condition, msg=None): | |
100 | """ |
|
100 | """ | |
101 | Make function raise SkipTest exception if a given condition is true. |
|
101 | Make function raise SkipTest exception if a given condition is true. | |
102 |
|
102 | |||
103 | If the condition is a callable, it is used at runtime to dynamically |
|
103 | If the condition is a callable, it is used at runtime to dynamically | |
104 | make the decision. This is useful for tests that may require costly |
|
104 | make the decision. This is useful for tests that may require costly | |
105 | imports, to delay the cost until the test suite is actually executed. |
|
105 | imports, to delay the cost until the test suite is actually executed. | |
106 |
|
106 | |||
107 | Parameters |
|
107 | Parameters | |
108 | ---------- |
|
108 | ---------- | |
109 | skip_condition : bool or callable |
|
109 | skip_condition : bool or callable | |
110 | Flag to determine whether to skip the decorated test. |
|
110 | Flag to determine whether to skip the decorated test. | |
111 | msg : str, optional |
|
111 | msg : str, optional | |
112 | Message to give on raising a SkipTest exception. Default is None. |
|
112 | Message to give on raising a SkipTest exception. Default is None. | |
113 |
|
113 | |||
114 | Returns |
|
114 | Returns | |
115 | ------- |
|
115 | ------- | |
116 | decorator : function |
|
116 | decorator : function | |
117 | Decorator which, when applied to a function, causes SkipTest |
|
117 | Decorator which, when applied to a function, causes SkipTest | |
118 | to be raised when `skip_condition` is True, and the function |
|
118 | to be raised when `skip_condition` is True, and the function | |
119 | to be called normally otherwise. |
|
119 | to be called normally otherwise. | |
120 |
|
120 | |||
121 | Notes |
|
121 | Notes | |
122 | ----- |
|
122 | ----- | |
123 | The decorator itself is decorated with the ``nose.tools.make_decorator`` |
|
123 | The decorator itself is decorated with the ``nose.tools.make_decorator`` | |
124 | function in order to transmit function name, and various other metadata. |
|
124 | function in order to transmit function name, and various other metadata. | |
125 |
|
125 | |||
126 | """ |
|
126 | """ | |
127 |
|
127 | |||
128 | def skip_decorator(f): |
|
128 | def skip_decorator(f): | |
129 | # Local import to avoid a hard nose dependency and only incur the |
|
129 | # Local import to avoid a hard nose dependency and only incur the | |
130 | # import time overhead at actual test-time. |
|
130 | # import time overhead at actual test-time. | |
131 | import nose |
|
131 | import nose | |
132 |
|
132 | |||
133 | # Allow for both boolean or callable skip conditions. |
|
133 | # Allow for both boolean or callable skip conditions. | |
134 | if callable(skip_condition): |
|
134 | if callable(skip_condition): | |
135 | skip_val = lambda : skip_condition() |
|
135 | skip_val = lambda : skip_condition() | |
136 | else: |
|
136 | else: | |
137 | skip_val = lambda : skip_condition |
|
137 | skip_val = lambda : skip_condition | |
138 |
|
138 | |||
139 | def get_msg(func,msg=None): |
|
139 | def get_msg(func,msg=None): | |
140 | """Skip message with information about function being skipped.""" |
|
140 | """Skip message with information about function being skipped.""" | |
141 | if msg is None: |
|
141 | if msg is None: | |
142 | out = 'Test skipped due to test condition' |
|
142 | out = 'Test skipped due to test condition' | |
143 | else: |
|
143 | else: | |
144 | out = '\n'+msg |
|
144 | out = '\n'+msg | |
145 |
|
145 | |||
146 | return "Skipping test: %s%s" % (func.__name__,out) |
|
146 | return "Skipping test: %s%s" % (func.__name__,out) | |
147 |
|
147 | |||
148 | # We need to define *two* skippers because Python doesn't allow both |
|
148 | # We need to define *two* skippers because Python doesn't allow both | |
149 | # return with value and yield inside the same function. |
|
149 | # return with value and yield inside the same function. | |
150 | def skipper_func(*args, **kwargs): |
|
150 | def skipper_func(*args, **kwargs): | |
151 | """Skipper for normal test functions.""" |
|
151 | """Skipper for normal test functions.""" | |
152 | if skip_val(): |
|
152 | if skip_val(): | |
153 | raise nose.SkipTest(get_msg(f,msg)) |
|
153 | raise nose.SkipTest(get_msg(f,msg)) | |
154 | else: |
|
154 | else: | |
155 | return f(*args, **kwargs) |
|
155 | return f(*args, **kwargs) | |
156 |
|
156 | |||
157 | def skipper_gen(*args, **kwargs): |
|
157 | def skipper_gen(*args, **kwargs): | |
158 | """Skipper for test generators.""" |
|
158 | """Skipper for test generators.""" | |
159 | if skip_val(): |
|
159 | if skip_val(): | |
160 | raise nose.SkipTest(get_msg(f,msg)) |
|
160 | raise nose.SkipTest(get_msg(f,msg)) | |
161 | else: |
|
161 | else: | |
162 | for x in f(*args, **kwargs): |
|
162 | for x in f(*args, **kwargs): | |
163 | yield x |
|
163 | yield x | |
164 |
|
164 | |||
165 | # Choose the right skipper to use when building the actual decorator. |
|
165 | # Choose the right skipper to use when building the actual decorator. | |
166 | if nose.util.isgenerator(f): |
|
166 | if nose.util.isgenerator(f): | |
167 | skipper = skipper_gen |
|
167 | skipper = skipper_gen | |
168 | else: |
|
168 | else: | |
169 | skipper = skipper_func |
|
169 | skipper = skipper_func | |
170 |
|
170 | |||
171 | return nose.tools.make_decorator(f)(skipper) |
|
171 | return nose.tools.make_decorator(f)(skipper) | |
172 |
|
172 | |||
173 | return skip_decorator |
|
173 | return skip_decorator | |
174 |
|
174 | |||
175 | def knownfailureif(fail_condition, msg=None): |
|
175 | def knownfailureif(fail_condition, msg=None): | |
176 | """ |
|
176 | """ | |
177 | Make function raise KnownFailureTest exception if given condition is true. |
|
177 | Make function raise KnownFailureTest exception if given condition is true. | |
178 |
|
178 | |||
179 | If the condition is a callable, it is used at runtime to dynamically |
|
179 | If the condition is a callable, it is used at runtime to dynamically | |
180 | make the decision. This is useful for tests that may require costly |
|
180 | make the decision. This is useful for tests that may require costly | |
181 | imports, to delay the cost until the test suite is actually executed. |
|
181 | imports, to delay the cost until the test suite is actually executed. | |
182 |
|
182 | |||
183 | Parameters |
|
183 | Parameters | |
184 | ---------- |
|
184 | ---------- | |
185 | fail_condition : bool or callable |
|
185 | fail_condition : bool or callable | |
186 | Flag to determine whether to mark the decorated test as a known |
|
186 | Flag to determine whether to mark the decorated test as a known | |
187 | failure (if True) or not (if False). |
|
187 | failure (if True) or not (if False). | |
188 | msg : str, optional |
|
188 | msg : str, optional | |
189 | Message to give on raising a KnownFailureTest exception. |
|
189 | Message to give on raising a KnownFailureTest exception. | |
190 | Default is None. |
|
190 | Default is None. | |
191 |
|
191 | |||
192 | Returns |
|
192 | Returns | |
193 | ------- |
|
193 | ------- | |
194 | decorator : function |
|
194 | decorator : function | |
195 | Decorator, which, when applied to a function, causes SkipTest |
|
195 | Decorator, which, when applied to a function, causes SkipTest | |
196 | to be raised when `skip_condition` is True, and the function |
|
196 | to be raised when `skip_condition` is True, and the function | |
197 | to be called normally otherwise. |
|
197 | to be called normally otherwise. | |
198 |
|
198 | |||
199 | Notes |
|
199 | Notes | |
200 | ----- |
|
200 | ----- | |
201 | The decorator itself is decorated with the ``nose.tools.make_decorator`` |
|
201 | The decorator itself is decorated with the ``nose.tools.make_decorator`` | |
202 | function in order to transmit function name, and various other metadata. |
|
202 | function in order to transmit function name, and various other metadata. | |
203 |
|
203 | |||
204 | """ |
|
204 | """ | |
205 | if msg is None: |
|
205 | if msg is None: | |
206 | msg = 'Test skipped due to known failure' |
|
206 | msg = 'Test skipped due to known failure' | |
207 |
|
207 | |||
208 | # Allow for both boolean or callable known failure conditions. |
|
208 | # Allow for both boolean or callable known failure conditions. | |
209 | if callable(fail_condition): |
|
209 | if callable(fail_condition): | |
210 | fail_val = lambda : fail_condition() |
|
210 | fail_val = lambda : fail_condition() | |
211 | else: |
|
211 | else: | |
212 | fail_val = lambda : fail_condition |
|
212 | fail_val = lambda : fail_condition | |
213 |
|
213 | |||
214 | def knownfail_decorator(f): |
|
214 | def knownfail_decorator(f): | |
215 | # Local import to avoid a hard nose dependency and only incur the |
|
215 | # Local import to avoid a hard nose dependency and only incur the | |
216 | # import time overhead at actual test-time. |
|
216 | # import time overhead at actual test-time. | |
217 | import nose |
|
217 | import nose | |
218 | def knownfailer(*args, **kwargs): |
|
218 | def knownfailer(*args, **kwargs): | |
219 | if fail_val(): |
|
219 | if fail_val(): | |
220 |
raise KnownFailureTest |
|
220 | raise KnownFailureTest(msg) | |
221 | else: |
|
221 | else: | |
222 | return f(*args, **kwargs) |
|
222 | return f(*args, **kwargs) | |
223 | return nose.tools.make_decorator(f)(knownfailer) |
|
223 | return nose.tools.make_decorator(f)(knownfailer) | |
224 |
|
224 | |||
225 | return knownfail_decorator |
|
225 | return knownfail_decorator | |
226 |
|
226 | |||
227 | def deprecated(conditional=True): |
|
227 | def deprecated(conditional=True): | |
228 | """ |
|
228 | """ | |
229 | Filter deprecation warnings while running the test suite. |
|
229 | Filter deprecation warnings while running the test suite. | |
230 |
|
230 | |||
231 | This decorator can be used to filter DeprecationWarning's, to avoid |
|
231 | This decorator can be used to filter DeprecationWarning's, to avoid | |
232 | printing them during the test suite run, while checking that the test |
|
232 | printing them during the test suite run, while checking that the test | |
233 | actually raises a DeprecationWarning. |
|
233 | actually raises a DeprecationWarning. | |
234 |
|
234 | |||
235 | Parameters |
|
235 | Parameters | |
236 | ---------- |
|
236 | ---------- | |
237 | conditional : bool or callable, optional |
|
237 | conditional : bool or callable, optional | |
238 | Flag to determine whether to mark test as deprecated or not. If the |
|
238 | Flag to determine whether to mark test as deprecated or not. If the | |
239 | condition is a callable, it is used at runtime to dynamically make the |
|
239 | condition is a callable, it is used at runtime to dynamically make the | |
240 | decision. Default is True. |
|
240 | decision. Default is True. | |
241 |
|
241 | |||
242 | Returns |
|
242 | Returns | |
243 | ------- |
|
243 | ------- | |
244 | decorator : function |
|
244 | decorator : function | |
245 | The `deprecated` decorator itself. |
|
245 | The `deprecated` decorator itself. | |
246 |
|
246 | |||
247 | Notes |
|
247 | Notes | |
248 | ----- |
|
248 | ----- | |
249 | .. versionadded:: 1.4.0 |
|
249 | .. versionadded:: 1.4.0 | |
250 |
|
250 | |||
251 | """ |
|
251 | """ | |
252 | def deprecate_decorator(f): |
|
252 | def deprecate_decorator(f): | |
253 | # Local import to avoid a hard nose dependency and only incur the |
|
253 | # Local import to avoid a hard nose dependency and only incur the | |
254 | # import time overhead at actual test-time. |
|
254 | # import time overhead at actual test-time. | |
255 | import nose |
|
255 | import nose | |
256 |
|
256 | |||
257 | def _deprecated_imp(*args, **kwargs): |
|
257 | def _deprecated_imp(*args, **kwargs): | |
258 | # Poor man's replacement for the with statement |
|
258 | # Poor man's replacement for the with statement | |
259 | ctx = WarningManager(record=True) |
|
259 | ctx = WarningManager(record=True) | |
260 | l = ctx.__enter__() |
|
260 | l = ctx.__enter__() | |
261 | warnings.simplefilter('always') |
|
261 | warnings.simplefilter('always') | |
262 | try: |
|
262 | try: | |
263 | f(*args, **kwargs) |
|
263 | f(*args, **kwargs) | |
264 | if not len(l) > 0: |
|
264 | if not len(l) > 0: | |
265 | raise AssertionError("No warning raised when calling %s" |
|
265 | raise AssertionError("No warning raised when calling %s" | |
266 | % f.__name__) |
|
266 | % f.__name__) | |
267 | if not l[0].category is DeprecationWarning: |
|
267 | if not l[0].category is DeprecationWarning: | |
268 | raise AssertionError("First warning for %s is not a " \ |
|
268 | raise AssertionError("First warning for %s is not a " \ | |
269 | "DeprecationWarning( is %s)" % (f.__name__, l[0])) |
|
269 | "DeprecationWarning( is %s)" % (f.__name__, l[0])) | |
270 | finally: |
|
270 | finally: | |
271 | ctx.__exit__() |
|
271 | ctx.__exit__() | |
272 |
|
272 | |||
273 | if callable(conditional): |
|
273 | if callable(conditional): | |
274 | cond = conditional() |
|
274 | cond = conditional() | |
275 | else: |
|
275 | else: | |
276 | cond = conditional |
|
276 | cond = conditional | |
277 | if cond: |
|
277 | if cond: | |
278 | return nose.tools.make_decorator(f)(_deprecated_imp) |
|
278 | return nose.tools.make_decorator(f)(_deprecated_imp) | |
279 | else: |
|
279 | else: | |
280 | return f |
|
280 | return f | |
281 | return deprecate_decorator |
|
281 | return deprecate_decorator |
@@ -1,1900 +1,1900 b'' | |||||
1 | """Pexpect is a Python module for spawning child applications and controlling |
|
1 | """Pexpect is a Python module for spawning child applications and controlling | |
2 | them automatically. Pexpect can be used for automating interactive applications |
|
2 | them automatically. Pexpect can be used for automating interactive applications | |
3 | such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup |
|
3 | such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup | |
4 | scripts for duplicating software package installations on different servers. It |
|
4 | scripts for duplicating software package installations on different servers. It | |
5 | can be used for automated software testing. Pexpect is in the spirit of Don |
|
5 | can be used for automated software testing. Pexpect is in the spirit of Don | |
6 | Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python |
|
6 | Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python | |
7 | require TCL and Expect or require C extensions to be compiled. Pexpect does not |
|
7 | require TCL and Expect or require C extensions to be compiled. Pexpect does not | |
8 | use C, Expect, or TCL extensions. It should work on any platform that supports |
|
8 | use C, Expect, or TCL extensions. It should work on any platform that supports | |
9 | the standard Python pty module. The Pexpect interface focuses on ease of use so |
|
9 | the standard Python pty module. The Pexpect interface focuses on ease of use so | |
10 | that simple tasks are easy. |
|
10 | that simple tasks are easy. | |
11 |
|
11 | |||
12 | There are two main interfaces to the Pexpect system; these are the function, |
|
12 | There are two main interfaces to the Pexpect system; these are the function, | |
13 | run() and the class, spawn. The spawn class is more powerful. The run() |
|
13 | run() and the class, spawn. The spawn class is more powerful. The run() | |
14 | function is simpler than spawn, and is good for quickly calling program. When |
|
14 | function is simpler than spawn, and is good for quickly calling program. When | |
15 | you call the run() function it executes a given program and then returns the |
|
15 | you call the run() function it executes a given program and then returns the | |
16 | output. This is a handy replacement for os.system(). |
|
16 | output. This is a handy replacement for os.system(). | |
17 |
|
17 | |||
18 | For example:: |
|
18 | For example:: | |
19 |
|
19 | |||
20 | pexpect.run('ls -la') |
|
20 | pexpect.run('ls -la') | |
21 |
|
21 | |||
22 | The spawn class is the more powerful interface to the Pexpect system. You can |
|
22 | The spawn class is the more powerful interface to the Pexpect system. You can | |
23 | use this to spawn a child program then interact with it by sending input and |
|
23 | use this to spawn a child program then interact with it by sending input and | |
24 | expecting responses (waiting for patterns in the child's output). |
|
24 | expecting responses (waiting for patterns in the child's output). | |
25 |
|
25 | |||
26 | For example:: |
|
26 | For example:: | |
27 |
|
27 | |||
28 | child = pexpect.spawn('scp foo myname@host.example.com:.') |
|
28 | child = pexpect.spawn('scp foo myname@host.example.com:.') | |
29 | child.expect ('Password:') |
|
29 | child.expect ('Password:') | |
30 | child.sendline (mypassword) |
|
30 | child.sendline (mypassword) | |
31 |
|
31 | |||
32 | This works even for commands that ask for passwords or other input outside of |
|
32 | This works even for commands that ask for passwords or other input outside of | |
33 | the normal stdio streams. For example, ssh reads input directly from the TTY |
|
33 | the normal stdio streams. For example, ssh reads input directly from the TTY | |
34 | device which bypasses stdin. |
|
34 | device which bypasses stdin. | |
35 |
|
35 | |||
36 | Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, |
|
36 | Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett, | |
37 | Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids |
|
37 | Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids | |
38 | vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin, |
|
38 | vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin, | |
39 | Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey, |
|
39 | Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey, | |
40 | Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume |
|
40 | Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume | |
41 | Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John |
|
41 | Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John | |
42 | Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone. |
|
42 | Spiegel, Jan Grant, Shane Kerr and Thomas Kluyver. Let me know if I forgot anyone. | |
43 |
|
43 | |||
44 | Pexpect is free, open source, and all that good stuff. |
|
44 | Pexpect is free, open source, and all that good stuff. | |
45 |
|
45 | |||
46 | Permission is hereby granted, free of charge, to any person obtaining a copy of |
|
46 | Permission is hereby granted, free of charge, to any person obtaining a copy of | |
47 | this software and associated documentation files (the "Software"), to deal in |
|
47 | this software and associated documentation files (the "Software"), to deal in | |
48 | the Software without restriction, including without limitation the rights to |
|
48 | the Software without restriction, including without limitation the rights to | |
49 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies |
|
49 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies | |
50 | of the Software, and to permit persons to whom the Software is furnished to do |
|
50 | of the Software, and to permit persons to whom the Software is furnished to do | |
51 | so, subject to the following conditions: |
|
51 | so, subject to the following conditions: | |
52 |
|
52 | |||
53 | The above copyright notice and this permission notice shall be included in all |
|
53 | The above copyright notice and this permission notice shall be included in all | |
54 | copies or substantial portions of the Software. |
|
54 | copies or substantial portions of the Software. | |
55 |
|
55 | |||
56 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
|
56 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
57 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
|
57 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
58 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
|
58 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
59 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
|
59 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
60 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
|
60 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
61 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
|
61 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
62 | SOFTWARE. |
|
62 | SOFTWARE. | |
63 |
|
63 | |||
64 | Pexpect Copyright (c) 2008-2011 Noah Spurrier |
|
64 | Pexpect Copyright (c) 2008-2011 Noah Spurrier | |
65 | http://pexpect.sourceforge.net/ |
|
65 | http://pexpect.sourceforge.net/ | |
66 | """ |
|
66 | """ | |
67 |
|
67 | |||
68 | try: |
|
68 | try: | |
69 | import os, sys, time |
|
69 | import os, sys, time | |
70 | import select |
|
70 | import select | |
71 | import re |
|
71 | import re | |
72 | import struct |
|
72 | import struct | |
73 | import resource |
|
73 | import resource | |
74 | import types |
|
74 | import types | |
75 | import pty |
|
75 | import pty | |
76 | import tty |
|
76 | import tty | |
77 | import termios |
|
77 | import termios | |
78 | import fcntl |
|
78 | import fcntl | |
79 | import errno |
|
79 | import errno | |
80 | import traceback |
|
80 | import traceback | |
81 | import signal |
|
81 | import signal | |
82 | except ImportError as e: |
|
82 | except ImportError as e: | |
83 | raise ImportError (str(e) + """ |
|
83 | raise ImportError (str(e) + """ | |
84 |
|
84 | |||
85 | A critical module was not found. Probably this operating system does not |
|
85 | A critical module was not found. Probably this operating system does not | |
86 | support it. Pexpect is intended for UNIX-like operating systems.""") |
|
86 | support it. Pexpect is intended for UNIX-like operating systems.""") | |
87 |
|
87 | |||
88 | __version__ = '2.6.dev' |
|
88 | __version__ = '2.6.dev' | |
89 | version = __version__ |
|
89 | version = __version__ | |
90 | version_info = (2,6,'dev') |
|
90 | version_info = (2,6,'dev') | |
91 | __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which', |
|
91 | __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnb', 'run', 'which', | |
92 | 'split_command_line', '__version__'] |
|
92 | 'split_command_line', '__version__'] | |
93 |
|
93 | |||
94 | # Exception classes used by this module. |
|
94 | # Exception classes used by this module. | |
95 | class ExceptionPexpect(Exception): |
|
95 | class ExceptionPexpect(Exception): | |
96 |
|
96 | |||
97 | """Base class for all exceptions raised by this module. |
|
97 | """Base class for all exceptions raised by this module. | |
98 | """ |
|
98 | """ | |
99 |
|
99 | |||
100 | def __init__(self, value): |
|
100 | def __init__(self, value): | |
101 |
|
101 | |||
102 | self.value = value |
|
102 | self.value = value | |
103 |
|
103 | |||
104 | def __str__(self): |
|
104 | def __str__(self): | |
105 |
|
105 | |||
106 | return str(self.value) |
|
106 | return str(self.value) | |
107 |
|
107 | |||
108 | def get_trace(self): |
|
108 | def get_trace(self): | |
109 |
|
109 | |||
110 | """This returns an abbreviated stack trace with lines that only concern |
|
110 | """This returns an abbreviated stack trace with lines that only concern | |
111 | the caller. In other words, the stack trace inside the Pexpect module |
|
111 | the caller. In other words, the stack trace inside the Pexpect module | |
112 | is not included. """ |
|
112 | is not included. """ | |
113 |
|
113 | |||
114 | tblist = traceback.extract_tb(sys.exc_info()[2]) |
|
114 | tblist = traceback.extract_tb(sys.exc_info()[2]) | |
115 | #tblist = filter(self.__filter_not_pexpect, tblist) |
|
115 | #tblist = filter(self.__filter_not_pexpect, tblist) | |
116 | tblist = [item for item in tblist if self.__filter_not_pexpect(item)] |
|
116 | tblist = [item for item in tblist if self.__filter_not_pexpect(item)] | |
117 | tblist = traceback.format_list(tblist) |
|
117 | tblist = traceback.format_list(tblist) | |
118 | return ''.join(tblist) |
|
118 | return ''.join(tblist) | |
119 |
|
119 | |||
120 | def __filter_not_pexpect(self, trace_list_item): |
|
120 | def __filter_not_pexpect(self, trace_list_item): | |
121 |
|
121 | |||
122 | """This returns True if list item 0 the string 'pexpect.py' in it. """ |
|
122 | """This returns True if list item 0 the string 'pexpect.py' in it. """ | |
123 |
|
123 | |||
124 | if trace_list_item[0].find('pexpect.py') == -1: |
|
124 | if trace_list_item[0].find('pexpect.py') == -1: | |
125 | return True |
|
125 | return True | |
126 | else: |
|
126 | else: | |
127 | return False |
|
127 | return False | |
128 |
|
128 | |||
129 | class EOF(ExceptionPexpect): |
|
129 | class EOF(ExceptionPexpect): | |
130 |
|
130 | |||
131 | """Raised when EOF is read from a child. This usually means the child has exited.""" |
|
131 | """Raised when EOF is read from a child. This usually means the child has exited.""" | |
132 |
|
132 | |||
133 | class TIMEOUT(ExceptionPexpect): |
|
133 | class TIMEOUT(ExceptionPexpect): | |
134 |
|
134 | |||
135 | """Raised when a read time exceeds the timeout. """ |
|
135 | """Raised when a read time exceeds the timeout. """ | |
136 |
|
136 | |||
137 | ##class TIMEOUT_PATTERN(TIMEOUT): |
|
137 | ##class TIMEOUT_PATTERN(TIMEOUT): | |
138 | ## """Raised when the pattern match time exceeds the timeout. |
|
138 | ## """Raised when the pattern match time exceeds the timeout. | |
139 | ## This is different than a read TIMEOUT because the child process may |
|
139 | ## This is different than a read TIMEOUT because the child process may | |
140 | ## give output, thus never give a TIMEOUT, but the output |
|
140 | ## give output, thus never give a TIMEOUT, but the output | |
141 | ## may never match a pattern. |
|
141 | ## may never match a pattern. | |
142 | ## """ |
|
142 | ## """ | |
143 | ##class MAXBUFFER(ExceptionPexpect): |
|
143 | ##class MAXBUFFER(ExceptionPexpect): | |
144 | ## """Raised when a scan buffer fills before matching an expected pattern.""" |
|
144 | ## """Raised when a scan buffer fills before matching an expected pattern.""" | |
145 |
|
145 | |||
146 | PY3 = (sys.version_info[0] >= 3) |
|
146 | PY3 = (sys.version_info[0] >= 3) | |
147 |
|
147 | |||
148 | def _cast_bytes(s, enc): |
|
148 | def _cast_bytes(s, enc): | |
149 | if isinstance(s, unicode): |
|
149 | if isinstance(s, unicode): | |
150 | return s.encode(enc) |
|
150 | return s.encode(enc) | |
151 | return s |
|
151 | return s | |
152 |
|
152 | |||
153 | def _cast_unicode(s, enc): |
|
153 | def _cast_unicode(s, enc): | |
154 | if isinstance(s, bytes): |
|
154 | if isinstance(s, bytes): | |
155 | return s.decode(enc) |
|
155 | return s.decode(enc) | |
156 | return s |
|
156 | return s | |
157 |
|
157 | |||
158 | re_type = type(re.compile('')) |
|
158 | re_type = type(re.compile('')) | |
159 |
|
159 | |||
160 | def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, |
|
160 | def run (command, timeout=-1, withexitstatus=False, events=None, extra_args=None, | |
161 | logfile=None, cwd=None, env=None, encoding='utf-8'): |
|
161 | logfile=None, cwd=None, env=None, encoding='utf-8'): | |
162 |
|
162 | |||
163 | """ |
|
163 | """ | |
164 | This function runs the given command; waits for it to finish; then |
|
164 | This function runs the given command; waits for it to finish; then | |
165 | returns all output as a string. STDERR is included in output. If the full |
|
165 | returns all output as a string. STDERR is included in output. If the full | |
166 | path to the command is not given then the path is searched. |
|
166 | path to the command is not given then the path is searched. | |
167 |
|
167 | |||
168 | Note that lines are terminated by CR/LF (\\r\\n) combination even on |
|
168 | Note that lines are terminated by CR/LF (\\r\\n) combination even on | |
169 | UNIX-like systems because this is the standard for pseudo ttys. If you set |
|
169 | UNIX-like systems because this is the standard for pseudo ttys. If you set | |
170 | 'withexitstatus' to true, then run will return a tuple of (command_output, |
|
170 | 'withexitstatus' to true, then run will return a tuple of (command_output, | |
171 | exitstatus). If 'withexitstatus' is false then this returns just |
|
171 | exitstatus). If 'withexitstatus' is false then this returns just | |
172 | command_output. |
|
172 | command_output. | |
173 |
|
173 | |||
174 | The run() function can often be used instead of creating a spawn instance. |
|
174 | The run() function can often be used instead of creating a spawn instance. | |
175 | For example, the following code uses spawn:: |
|
175 | For example, the following code uses spawn:: | |
176 |
|
176 | |||
177 | from pexpect import * |
|
177 | from pexpect import * | |
178 | child = spawn('scp foo myname@host.example.com:.') |
|
178 | child = spawn('scp foo myname@host.example.com:.') | |
179 | child.expect ('(?i)password') |
|
179 | child.expect ('(?i)password') | |
180 | child.sendline (mypassword) |
|
180 | child.sendline (mypassword) | |
181 |
|
181 | |||
182 | The previous code can be replace with the following:: |
|
182 | The previous code can be replace with the following:: | |
183 |
|
183 | |||
184 | from pexpect import * |
|
184 | from pexpect import * | |
185 | run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) |
|
185 | run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword}) | |
186 |
|
186 | |||
187 | Examples |
|
187 | Examples | |
188 | ======== |
|
188 | ======== | |
189 |
|
189 | |||
190 | Start the apache daemon on the local machine:: |
|
190 | Start the apache daemon on the local machine:: | |
191 |
|
191 | |||
192 | from pexpect import * |
|
192 | from pexpect import * | |
193 | run ("/usr/local/apache/bin/apachectl start") |
|
193 | run ("/usr/local/apache/bin/apachectl start") | |
194 |
|
194 | |||
195 | Check in a file using SVN:: |
|
195 | Check in a file using SVN:: | |
196 |
|
196 | |||
197 | from pexpect import * |
|
197 | from pexpect import * | |
198 | run ("svn ci -m 'automatic commit' my_file.py") |
|
198 | run ("svn ci -m 'automatic commit' my_file.py") | |
199 |
|
199 | |||
200 | Run a command and capture exit status:: |
|
200 | Run a command and capture exit status:: | |
201 |
|
201 | |||
202 | from pexpect import * |
|
202 | from pexpect import * | |
203 | (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) |
|
203 | (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) | |
204 |
|
204 | |||
205 | Tricky Examples |
|
205 | Tricky Examples | |
206 | =============== |
|
206 | =============== | |
207 |
|
207 | |||
208 | The following will run SSH and execute 'ls -l' on the remote machine. The |
|
208 | The following will run SSH and execute 'ls -l' on the remote machine. The | |
209 | password 'secret' will be sent if the '(?i)password' pattern is ever seen:: |
|
209 | password 'secret' will be sent if the '(?i)password' pattern is ever seen:: | |
210 |
|
210 | |||
211 | run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) |
|
211 | run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\\n'}) | |
212 |
|
212 | |||
213 | This will start mencoder to rip a video from DVD. This will also display |
|
213 | This will start mencoder to rip a video from DVD. This will also display | |
214 | progress ticks every 5 seconds as it runs. For example:: |
|
214 | progress ticks every 5 seconds as it runs. For example:: | |
215 |
|
215 | |||
216 | from pexpect import * |
|
216 | from pexpect import * | |
217 | def print_ticks(d): |
|
217 | def print_ticks(d): | |
218 | print d['event_count'], |
|
218 | print d['event_count'], | |
219 | run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) |
|
219 | run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) | |
220 |
|
220 | |||
221 | The 'events' argument should be a dictionary of patterns and responses. |
|
221 | The 'events' argument should be a dictionary of patterns and responses. | |
222 | Whenever one of the patterns is seen in the command out run() will send the |
|
222 | Whenever one of the patterns is seen in the command out run() will send the | |
223 | associated response string. Note that you should put newlines in your |
|
223 | associated response string. Note that you should put newlines in your | |
224 | string if Enter is necessary. The responses may also contain callback |
|
224 | string if Enter is necessary. The responses may also contain callback | |
225 | functions. Any callback is function that takes a dictionary as an argument. |
|
225 | functions. Any callback is function that takes a dictionary as an argument. | |
226 | The dictionary contains all the locals from the run() function, so you can |
|
226 | The dictionary contains all the locals from the run() function, so you can | |
227 | access the child spawn object or any other variable defined in run() |
|
227 | access the child spawn object or any other variable defined in run() | |
228 | (event_count, child, and extra_args are the most useful). A callback may |
|
228 | (event_count, child, and extra_args are the most useful). A callback may | |
229 | return True to stop the current run process otherwise run() continues until |
|
229 | return True to stop the current run process otherwise run() continues until | |
230 | the next event. A callback may also return a string which will be sent to |
|
230 | the next event. A callback may also return a string which will be sent to | |
231 | the child. 'extra_args' is not used by directly run(). It provides a way to |
|
231 | the child. 'extra_args' is not used by directly run(). It provides a way to | |
232 | pass data to a callback function through run() through the locals |
|
232 | pass data to a callback function through run() through the locals | |
233 | dictionary passed to a callback.""" |
|
233 | dictionary passed to a callback.""" | |
234 |
|
234 | |||
235 | if timeout == -1: |
|
235 | if timeout == -1: | |
236 | child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env, |
|
236 | child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env, | |
237 | encoding=encoding) |
|
237 | encoding=encoding) | |
238 | else: |
|
238 | else: | |
239 | child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, |
|
239 | child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile, | |
240 | cwd=cwd, env=env, encoding=encoding) |
|
240 | cwd=cwd, env=env, encoding=encoding) | |
241 | if events is not None: |
|
241 | if events is not None: | |
242 | patterns = events.keys() |
|
242 | patterns = events.keys() | |
243 | responses = events.values() |
|
243 | responses = events.values() | |
244 | else: |
|
244 | else: | |
245 | patterns=None # We assume that EOF or TIMEOUT will save us. |
|
245 | patterns=None # We assume that EOF or TIMEOUT will save us. | |
246 | responses=None |
|
246 | responses=None | |
247 | child_result_list = [] |
|
247 | child_result_list = [] | |
248 | event_count = 0 |
|
248 | event_count = 0 | |
249 | while 1: |
|
249 | while 1: | |
250 | try: |
|
250 | try: | |
251 | index = child.expect (patterns) |
|
251 | index = child.expect (patterns) | |
252 | if isinstance(child.after, basestring): |
|
252 | if isinstance(child.after, basestring): | |
253 | child_result_list.append(child.before + child.after) |
|
253 | child_result_list.append(child.before + child.after) | |
254 | else: # child.after may have been a TIMEOUT or EOF, so don't cat those. |
|
254 | else: # child.after may have been a TIMEOUT or EOF, so don't cat those. | |
255 | child_result_list.append(child.before) |
|
255 | child_result_list.append(child.before) | |
256 | if isinstance(responses[index], basestring): |
|
256 | if isinstance(responses[index], basestring): | |
257 | child.send(responses[index]) |
|
257 | child.send(responses[index]) | |
258 | elif type(responses[index]) is types.FunctionType: |
|
258 | elif type(responses[index]) is types.FunctionType: | |
259 | callback_result = responses[index](locals()) |
|
259 | callback_result = responses[index](locals()) | |
260 | sys.stdout.flush() |
|
260 | sys.stdout.flush() | |
261 | if isinstance(callback_result, basestring): |
|
261 | if isinstance(callback_result, basestring): | |
262 | child.send(callback_result) |
|
262 | child.send(callback_result) | |
263 | elif callback_result: |
|
263 | elif callback_result: | |
264 | break |
|
264 | break | |
265 | else: |
|
265 | else: | |
266 | raise TypeError ('The callback must be a string or function type.') |
|
266 | raise TypeError ('The callback must be a string or function type.') | |
267 | event_count = event_count + 1 |
|
267 | event_count = event_count + 1 | |
268 | except TIMEOUT as e: |
|
268 | except TIMEOUT as e: | |
269 | child_result_list.append(child.before) |
|
269 | child_result_list.append(child.before) | |
270 | break |
|
270 | break | |
271 | except EOF as e: |
|
271 | except EOF as e: | |
272 | child_result_list.append(child.before) |
|
272 | child_result_list.append(child.before) | |
273 | break |
|
273 | break | |
274 | child_result = child._empty_buffer.join(child_result_list) |
|
274 | child_result = child._empty_buffer.join(child_result_list) | |
275 | if withexitstatus: |
|
275 | if withexitstatus: | |
276 | child.close() |
|
276 | child.close() | |
277 | return (child_result, child.exitstatus) |
|
277 | return (child_result, child.exitstatus) | |
278 | else: |
|
278 | else: | |
279 | return child_result |
|
279 | return child_result | |
280 |
|
280 | |||
281 | class spawnb(object): |
|
281 | class spawnb(object): | |
282 | """Use this class to start and control child applications with a pure-bytes |
|
282 | """Use this class to start and control child applications with a pure-bytes | |
283 | interface.""" |
|
283 | interface.""" | |
284 |
|
284 | |||
285 | _buffer_type = bytes |
|
285 | _buffer_type = bytes | |
286 | def _cast_buffer_type(self, s): |
|
286 | def _cast_buffer_type(self, s): | |
287 | return _cast_bytes(s, self.encoding) |
|
287 | return _cast_bytes(s, self.encoding) | |
288 | _empty_buffer = b'' |
|
288 | _empty_buffer = b'' | |
289 | _pty_newline = b'\r\n' |
|
289 | _pty_newline = b'\r\n' | |
290 |
|
290 | |||
291 | # Some code needs this to exist, but it's mainly for the spawn subclass. |
|
291 | # Some code needs this to exist, but it's mainly for the spawn subclass. | |
292 | encoding = 'utf-8' |
|
292 | encoding = 'utf-8' | |
293 |
|
293 | |||
294 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, |
|
294 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, | |
295 | logfile=None, cwd=None, env=None): |
|
295 | logfile=None, cwd=None, env=None): | |
296 |
|
296 | |||
297 | """This is the constructor. The command parameter may be a string that |
|
297 | """This is the constructor. The command parameter may be a string that | |
298 | includes a command and any arguments to the command. For example:: |
|
298 | includes a command and any arguments to the command. For example:: | |
299 |
|
299 | |||
300 | child = pexpect.spawn ('/usr/bin/ftp') |
|
300 | child = pexpect.spawn ('/usr/bin/ftp') | |
301 | child = pexpect.spawn ('/usr/bin/ssh user@example.com') |
|
301 | child = pexpect.spawn ('/usr/bin/ssh user@example.com') | |
302 | child = pexpect.spawn ('ls -latr /tmp') |
|
302 | child = pexpect.spawn ('ls -latr /tmp') | |
303 |
|
303 | |||
304 | You may also construct it with a list of arguments like so:: |
|
304 | You may also construct it with a list of arguments like so:: | |
305 |
|
305 | |||
306 | child = pexpect.spawn ('/usr/bin/ftp', []) |
|
306 | child = pexpect.spawn ('/usr/bin/ftp', []) | |
307 | child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) |
|
307 | child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) | |
308 | child = pexpect.spawn ('ls', ['-latr', '/tmp']) |
|
308 | child = pexpect.spawn ('ls', ['-latr', '/tmp']) | |
309 |
|
309 | |||
310 | After this the child application will be created and will be ready to |
|
310 | After this the child application will be created and will be ready to | |
311 | talk to. For normal use, see expect() and send() and sendline(). |
|
311 | talk to. For normal use, see expect() and send() and sendline(). | |
312 |
|
312 | |||
313 | Remember that Pexpect does NOT interpret shell meta characters such as |
|
313 | Remember that Pexpect does NOT interpret shell meta characters such as | |
314 | redirect, pipe, or wild cards (>, |, or *). This is a common mistake. |
|
314 | redirect, pipe, or wild cards (>, |, or *). This is a common mistake. | |
315 | If you want to run a command and pipe it through another command then |
|
315 | If you want to run a command and pipe it through another command then | |
316 | you must also start a shell. For example:: |
|
316 | you must also start a shell. For example:: | |
317 |
|
317 | |||
318 | child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') |
|
318 | child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"') | |
319 | child.expect(pexpect.EOF) |
|
319 | child.expect(pexpect.EOF) | |
320 |
|
320 | |||
321 | The second form of spawn (where you pass a list of arguments) is useful |
|
321 | The second form of spawn (where you pass a list of arguments) is useful | |
322 | in situations where you wish to spawn a command and pass it its own |
|
322 | in situations where you wish to spawn a command and pass it its own | |
323 | argument list. This can make syntax more clear. For example, the |
|
323 | argument list. This can make syntax more clear. For example, the | |
324 | following is equivalent to the previous example:: |
|
324 | following is equivalent to the previous example:: | |
325 |
|
325 | |||
326 | shell_cmd = 'ls -l | grep LOG > log_list.txt' |
|
326 | shell_cmd = 'ls -l | grep LOG > log_list.txt' | |
327 | child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) |
|
327 | child = pexpect.spawn('/bin/bash', ['-c', shell_cmd]) | |
328 | child.expect(pexpect.EOF) |
|
328 | child.expect(pexpect.EOF) | |
329 |
|
329 | |||
330 | The maxread attribute sets the read buffer size. This is maximum number |
|
330 | The maxread attribute sets the read buffer size. This is maximum number | |
331 | of bytes that Pexpect will try to read from a TTY at one time. Setting |
|
331 | of bytes that Pexpect will try to read from a TTY at one time. Setting | |
332 | the maxread size to 1 will turn off buffering. Setting the maxread |
|
332 | the maxread size to 1 will turn off buffering. Setting the maxread | |
333 | value higher may help performance in cases where large amounts of |
|
333 | value higher may help performance in cases where large amounts of | |
334 | output are read back from the child. This feature is useful in |
|
334 | output are read back from the child. This feature is useful in | |
335 | conjunction with searchwindowsize. |
|
335 | conjunction with searchwindowsize. | |
336 |
|
336 | |||
337 | The searchwindowsize attribute sets the how far back in the incomming |
|
337 | The searchwindowsize attribute sets the how far back in the incomming | |
338 | seach buffer Pexpect will search for pattern matches. Every time |
|
338 | seach buffer Pexpect will search for pattern matches. Every time | |
339 | Pexpect reads some data from the child it will append the data to the |
|
339 | Pexpect reads some data from the child it will append the data to the | |
340 | incomming buffer. The default is to search from the beginning of the |
|
340 | incomming buffer. The default is to search from the beginning of the | |
341 | imcomming buffer each time new data is read from the child. But this is |
|
341 | imcomming buffer each time new data is read from the child. But this is | |
342 | very inefficient if you are running a command that generates a large |
|
342 | very inefficient if you are running a command that generates a large | |
343 | amount of data where you want to match The searchwindowsize does not |
|
343 | amount of data where you want to match The searchwindowsize does not | |
344 | effect the size of the incomming data buffer. You will still have |
|
344 | effect the size of the incomming data buffer. You will still have | |
345 | access to the full buffer after expect() returns. |
|
345 | access to the full buffer after expect() returns. | |
346 |
|
346 | |||
347 | The logfile member turns on or off logging. All input and output will |
|
347 | The logfile member turns on or off logging. All input and output will | |
348 | be copied to the given file object. Set logfile to None to stop |
|
348 | be copied to the given file object. Set logfile to None to stop | |
349 | logging. This is the default. Set logfile to sys.stdout to echo |
|
349 | logging. This is the default. Set logfile to sys.stdout to echo | |
350 | everything to standard output. The logfile is flushed after each write. |
|
350 | everything to standard output. The logfile is flushed after each write. | |
351 |
|
351 | |||
352 | Example log input and output to a file:: |
|
352 | Example log input and output to a file:: | |
353 |
|
353 | |||
354 | child = pexpect.spawn('some_command') |
|
354 | child = pexpect.spawn('some_command') | |
355 | fout = open('mylog.txt','w') |
|
355 | fout = open('mylog.txt','w') | |
356 | child.logfile = fout |
|
356 | child.logfile = fout | |
357 |
|
357 | |||
358 | Example log to stdout:: |
|
358 | Example log to stdout:: | |
359 |
|
359 | |||
360 | child = pexpect.spawn('some_command') |
|
360 | child = pexpect.spawn('some_command') | |
361 | child.logfile = sys.stdout |
|
361 | child.logfile = sys.stdout | |
362 |
|
362 | |||
363 | The logfile_read and logfile_send members can be used to separately log |
|
363 | The logfile_read and logfile_send members can be used to separately log | |
364 | the input from the child and output sent to the child. Sometimes you |
|
364 | the input from the child and output sent to the child. Sometimes you | |
365 | don't want to see everything you write to the child. You only want to |
|
365 | don't want to see everything you write to the child. You only want to | |
366 | log what the child sends back. For example:: |
|
366 | log what the child sends back. For example:: | |
367 |
|
367 | |||
368 | child = pexpect.spawn('some_command') |
|
368 | child = pexpect.spawn('some_command') | |
369 | child.logfile_read = sys.stdout |
|
369 | child.logfile_read = sys.stdout | |
370 |
|
370 | |||
371 | To separately log output sent to the child use logfile_send:: |
|
371 | To separately log output sent to the child use logfile_send:: | |
372 |
|
372 | |||
373 | self.logfile_send = fout |
|
373 | self.logfile_send = fout | |
374 |
|
374 | |||
375 | The delaybeforesend helps overcome a weird behavior that many users |
|
375 | The delaybeforesend helps overcome a weird behavior that many users | |
376 | were experiencing. The typical problem was that a user would expect() a |
|
376 | were experiencing. The typical problem was that a user would expect() a | |
377 | "Password:" prompt and then immediately call sendline() to send the |
|
377 | "Password:" prompt and then immediately call sendline() to send the | |
378 | password. The user would then see that their password was echoed back |
|
378 | password. The user would then see that their password was echoed back | |
379 | to them. Passwords don't normally echo. The problem is caused by the |
|
379 | to them. Passwords don't normally echo. The problem is caused by the | |
380 | fact that most applications print out the "Password" prompt and then |
|
380 | fact that most applications print out the "Password" prompt and then | |
381 | turn off stdin echo, but if you send your password before the |
|
381 | turn off stdin echo, but if you send your password before the | |
382 | application turned off echo, then you get your password echoed. |
|
382 | application turned off echo, then you get your password echoed. | |
383 | Normally this wouldn't be a problem when interacting with a human at a |
|
383 | Normally this wouldn't be a problem when interacting with a human at a | |
384 | real keyboard. If you introduce a slight delay just before writing then |
|
384 | real keyboard. If you introduce a slight delay just before writing then | |
385 | this seems to clear up the problem. This was such a common problem for |
|
385 | this seems to clear up the problem. This was such a common problem for | |
386 | many users that I decided that the default pexpect behavior should be |
|
386 | many users that I decided that the default pexpect behavior should be | |
387 | to sleep just before writing to the child application. 1/20th of a |
|
387 | to sleep just before writing to the child application. 1/20th of a | |
388 | second (50 ms) seems to be enough to clear up the problem. You can set |
|
388 | second (50 ms) seems to be enough to clear up the problem. You can set | |
389 | delaybeforesend to 0 to return to the old behavior. Most Linux machines |
|
389 | delaybeforesend to 0 to return to the old behavior. Most Linux machines | |
390 | don't like this to be below 0.03. I don't know why. |
|
390 | don't like this to be below 0.03. I don't know why. | |
391 |
|
391 | |||
392 | Note that spawn is clever about finding commands on your path. |
|
392 | Note that spawn is clever about finding commands on your path. | |
393 | It uses the same logic that "which" uses to find executables. |
|
393 | It uses the same logic that "which" uses to find executables. | |
394 |
|
394 | |||
395 | If you wish to get the exit status of the child you must call the |
|
395 | If you wish to get the exit status of the child you must call the | |
396 | close() method. The exit or signal status of the child will be stored |
|
396 | close() method. The exit or signal status of the child will be stored | |
397 | in self.exitstatus or self.signalstatus. If the child exited normally |
|
397 | in self.exitstatus or self.signalstatus. If the child exited normally | |
398 | then exitstatus will store the exit return code and signalstatus will |
|
398 | then exitstatus will store the exit return code and signalstatus will | |
399 | be None. If the child was terminated abnormally with a signal then |
|
399 | be None. If the child was terminated abnormally with a signal then | |
400 | signalstatus will store the signal value and exitstatus will be None. |
|
400 | signalstatus will store the signal value and exitstatus will be None. | |
401 | If you need more detail you can also read the self.status member which |
|
401 | If you need more detail you can also read the self.status member which | |
402 | stores the status returned by os.waitpid. You can interpret this using |
|
402 | stores the status returned by os.waitpid. You can interpret this using | |
403 | os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """ |
|
403 | os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """ | |
404 |
|
404 | |||
405 | self.STDIN_FILENO = pty.STDIN_FILENO |
|
405 | self.STDIN_FILENO = pty.STDIN_FILENO | |
406 | self.STDOUT_FILENO = pty.STDOUT_FILENO |
|
406 | self.STDOUT_FILENO = pty.STDOUT_FILENO | |
407 | self.STDERR_FILENO = pty.STDERR_FILENO |
|
407 | self.STDERR_FILENO = pty.STDERR_FILENO | |
408 | self.stdin = sys.stdin |
|
408 | self.stdin = sys.stdin | |
409 | self.stdout = sys.stdout |
|
409 | self.stdout = sys.stdout | |
410 | self.stderr = sys.stderr |
|
410 | self.stderr = sys.stderr | |
411 |
|
411 | |||
412 | self.searcher = None |
|
412 | self.searcher = None | |
413 | self.ignorecase = False |
|
413 | self.ignorecase = False | |
414 | self.before = None |
|
414 | self.before = None | |
415 | self.after = None |
|
415 | self.after = None | |
416 | self.match = None |
|
416 | self.match = None | |
417 | self.match_index = None |
|
417 | self.match_index = None | |
418 | self.terminated = True |
|
418 | self.terminated = True | |
419 | self.exitstatus = None |
|
419 | self.exitstatus = None | |
420 | self.signalstatus = None |
|
420 | self.signalstatus = None | |
421 | self.status = None # status returned by os.waitpid |
|
421 | self.status = None # status returned by os.waitpid | |
422 | self.flag_eof = False |
|
422 | self.flag_eof = False | |
423 | self.pid = None |
|
423 | self.pid = None | |
424 | self.child_fd = -1 # initially closed |
|
424 | self.child_fd = -1 # initially closed | |
425 | self.timeout = timeout |
|
425 | self.timeout = timeout | |
426 | self.delimiter = EOF |
|
426 | self.delimiter = EOF | |
427 | self.logfile = logfile |
|
427 | self.logfile = logfile | |
428 | self.logfile_read = None # input from child (read_nonblocking) |
|
428 | self.logfile_read = None # input from child (read_nonblocking) | |
429 | self.logfile_send = None # output to send (send, sendline) |
|
429 | self.logfile_send = None # output to send (send, sendline) | |
430 | self.maxread = maxread # max bytes to read at one time into buffer |
|
430 | self.maxread = maxread # max bytes to read at one time into buffer | |
431 | self.buffer = self._empty_buffer # This is the read buffer. See maxread. |
|
431 | self.buffer = self._empty_buffer # This is the read buffer. See maxread. | |
432 | self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. |
|
432 | self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. | |
433 | # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms). |
|
433 | # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms). | |
434 | self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. |
|
434 | self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. | |
435 | self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. |
|
435 | self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. | |
436 | self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. |
|
436 | self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. | |
437 | self.softspace = False # File-like object. |
|
437 | self.softspace = False # File-like object. | |
438 | self.name = '<' + repr(self) + '>' # File-like object. |
|
438 | self.name = '<' + repr(self) + '>' # File-like object. | |
439 | self.closed = True # File-like object. |
|
439 | self.closed = True # File-like object. | |
440 | self.cwd = cwd |
|
440 | self.cwd = cwd | |
441 | self.env = env |
|
441 | self.env = env | |
442 | self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix |
|
442 | self.__irix_hack = (sys.platform.lower().find('irix')>=0) # This flags if we are running on irix | |
443 | # Solaris uses internal __fork_pty(). All others use pty.fork(). |
|
443 | # Solaris uses internal __fork_pty(). All others use pty.fork(). | |
444 | if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower(): |
|
444 | if 'solaris' in sys.platform.lower() or 'sunos5' in sys.platform.lower(): | |
445 | self.use_native_pty_fork = False |
|
445 | self.use_native_pty_fork = False | |
446 | else: |
|
446 | else: | |
447 | self.use_native_pty_fork = True |
|
447 | self.use_native_pty_fork = True | |
448 |
|
448 | |||
449 |
|
449 | |||
450 | # allow dummy instances for subclasses that may not use command or args. |
|
450 | # allow dummy instances for subclasses that may not use command or args. | |
451 | if command is None: |
|
451 | if command is None: | |
452 | self.command = None |
|
452 | self.command = None | |
453 | self.args = None |
|
453 | self.args = None | |
454 | self.name = '<pexpect factory incomplete>' |
|
454 | self.name = '<pexpect factory incomplete>' | |
455 | else: |
|
455 | else: | |
456 | self._spawn (command, args) |
|
456 | self._spawn (command, args) | |
457 |
|
457 | |||
458 | def __del__(self): |
|
458 | def __del__(self): | |
459 |
|
459 | |||
460 | """This makes sure that no system resources are left open. Python only |
|
460 | """This makes sure that no system resources are left open. Python only | |
461 | garbage collects Python objects. OS file descriptors are not Python |
|
461 | garbage collects Python objects. OS file descriptors are not Python | |
462 | objects, so they must be handled explicitly. If the child file |
|
462 | objects, so they must be handled explicitly. If the child file | |
463 | descriptor was opened outside of this class (passed to the constructor) |
|
463 | descriptor was opened outside of this class (passed to the constructor) | |
464 | then this does not close it. """ |
|
464 | then this does not close it. """ | |
465 |
|
465 | |||
466 | if not self.closed: |
|
466 | if not self.closed: | |
467 | # It is possible for __del__ methods to execute during the |
|
467 | # It is possible for __del__ methods to execute during the | |
468 | # teardown of the Python VM itself. Thus self.close() may |
|
468 | # teardown of the Python VM itself. Thus self.close() may | |
469 | # trigger an exception because os.close may be None. |
|
469 | # trigger an exception because os.close may be None. | |
470 | # -- Fernando Perez |
|
470 | # -- Fernando Perez | |
471 | try: |
|
471 | try: | |
472 | self.close() |
|
472 | self.close() | |
473 | except: |
|
473 | except: | |
474 | pass |
|
474 | pass | |
475 |
|
475 | |||
476 | def __str__(self): |
|
476 | def __str__(self): | |
477 |
|
477 | |||
478 | """This returns a human-readable string that represents the state of |
|
478 | """This returns a human-readable string that represents the state of | |
479 | the object. """ |
|
479 | the object. """ | |
480 |
|
480 | |||
481 | s = [] |
|
481 | s = [] | |
482 | s.append(repr(self)) |
|
482 | s.append(repr(self)) | |
483 | s.append('version: ' + __version__) |
|
483 | s.append('version: ' + __version__) | |
484 | s.append('command: ' + str(self.command)) |
|
484 | s.append('command: ' + str(self.command)) | |
485 | s.append('args: ' + str(self.args)) |
|
485 | s.append('args: ' + str(self.args)) | |
486 | s.append('searcher: ' + str(self.searcher)) |
|
486 | s.append('searcher: ' + str(self.searcher)) | |
487 | s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:]) |
|
487 | s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:]) | |
488 | s.append('before (last 100 chars): ' + str(self.before)[-100:]) |
|
488 | s.append('before (last 100 chars): ' + str(self.before)[-100:]) | |
489 | s.append('after: ' + str(self.after)) |
|
489 | s.append('after: ' + str(self.after)) | |
490 | s.append('match: ' + str(self.match)) |
|
490 | s.append('match: ' + str(self.match)) | |
491 | s.append('match_index: ' + str(self.match_index)) |
|
491 | s.append('match_index: ' + str(self.match_index)) | |
492 | s.append('exitstatus: ' + str(self.exitstatus)) |
|
492 | s.append('exitstatus: ' + str(self.exitstatus)) | |
493 | s.append('flag_eof: ' + str(self.flag_eof)) |
|
493 | s.append('flag_eof: ' + str(self.flag_eof)) | |
494 | s.append('pid: ' + str(self.pid)) |
|
494 | s.append('pid: ' + str(self.pid)) | |
495 | s.append('child_fd: ' + str(self.child_fd)) |
|
495 | s.append('child_fd: ' + str(self.child_fd)) | |
496 | s.append('closed: ' + str(self.closed)) |
|
496 | s.append('closed: ' + str(self.closed)) | |
497 | s.append('timeout: ' + str(self.timeout)) |
|
497 | s.append('timeout: ' + str(self.timeout)) | |
498 | s.append('delimiter: ' + str(self.delimiter)) |
|
498 | s.append('delimiter: ' + str(self.delimiter)) | |
499 | s.append('logfile: ' + str(self.logfile)) |
|
499 | s.append('logfile: ' + str(self.logfile)) | |
500 | s.append('logfile_read: ' + str(self.logfile_read)) |
|
500 | s.append('logfile_read: ' + str(self.logfile_read)) | |
501 | s.append('logfile_send: ' + str(self.logfile_send)) |
|
501 | s.append('logfile_send: ' + str(self.logfile_send)) | |
502 | s.append('maxread: ' + str(self.maxread)) |
|
502 | s.append('maxread: ' + str(self.maxread)) | |
503 | s.append('ignorecase: ' + str(self.ignorecase)) |
|
503 | s.append('ignorecase: ' + str(self.ignorecase)) | |
504 | s.append('searchwindowsize: ' + str(self.searchwindowsize)) |
|
504 | s.append('searchwindowsize: ' + str(self.searchwindowsize)) | |
505 | s.append('delaybeforesend: ' + str(self.delaybeforesend)) |
|
505 | s.append('delaybeforesend: ' + str(self.delaybeforesend)) | |
506 | s.append('delayafterclose: ' + str(self.delayafterclose)) |
|
506 | s.append('delayafterclose: ' + str(self.delayafterclose)) | |
507 | s.append('delayafterterminate: ' + str(self.delayafterterminate)) |
|
507 | s.append('delayafterterminate: ' + str(self.delayafterterminate)) | |
508 | return '\n'.join(s) |
|
508 | return '\n'.join(s) | |
509 |
|
509 | |||
510 | def _spawn(self,command,args=[]): |
|
510 | def _spawn(self,command,args=[]): | |
511 |
|
511 | |||
512 | """This starts the given command in a child process. This does all the |
|
512 | """This starts the given command in a child process. This does all the | |
513 | fork/exec type of stuff for a pty. This is called by __init__. If args |
|
513 | fork/exec type of stuff for a pty. This is called by __init__. If args | |
514 | is empty then command will be parsed (split on spaces) and args will be |
|
514 | is empty then command will be parsed (split on spaces) and args will be | |
515 | set to parsed arguments. """ |
|
515 | set to parsed arguments. """ | |
516 |
|
516 | |||
517 | # The pid and child_fd of this object get set by this method. |
|
517 | # The pid and child_fd of this object get set by this method. | |
518 | # Note that it is difficult for this method to fail. |
|
518 | # Note that it is difficult for this method to fail. | |
519 | # You cannot detect if the child process cannot start. |
|
519 | # You cannot detect if the child process cannot start. | |
520 | # So the only way you can tell if the child process started |
|
520 | # So the only way you can tell if the child process started | |
521 | # or not is to try to read from the file descriptor. If you get |
|
521 | # or not is to try to read from the file descriptor. If you get | |
522 | # EOF immediately then it means that the child is already dead. |
|
522 | # EOF immediately then it means that the child is already dead. | |
523 | # That may not necessarily be bad because you may haved spawned a child |
|
523 | # That may not necessarily be bad because you may haved spawned a child | |
524 | # that performs some task; creates no stdout output; and then dies. |
|
524 | # that performs some task; creates no stdout output; and then dies. | |
525 |
|
525 | |||
526 | # If command is an int type then it may represent a file descriptor. |
|
526 | # If command is an int type then it may represent a file descriptor. | |
527 | if type(command) == type(0): |
|
527 | if type(command) == type(0): | |
528 | raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') |
|
528 | raise ExceptionPexpect ('Command is an int type. If this is a file descriptor then maybe you want to use fdpexpect.fdspawn which takes an existing file descriptor instead of a command string.') | |
529 |
|
529 | |||
530 | if type (args) != type([]): |
|
530 | if type (args) != type([]): | |
531 | raise TypeError ('The argument, args, must be a list.') |
|
531 | raise TypeError ('The argument, args, must be a list.') | |
532 |
|
532 | |||
533 | if args == []: |
|
533 | if args == []: | |
534 | self.args = split_command_line(command) |
|
534 | self.args = split_command_line(command) | |
535 | self.command = self.args[0] |
|
535 | self.command = self.args[0] | |
536 | else: |
|
536 | else: | |
537 | self.args = args[:] # work with a copy |
|
537 | self.args = args[:] # work with a copy | |
538 | self.args.insert (0, command) |
|
538 | self.args.insert (0, command) | |
539 | self.command = command |
|
539 | self.command = command | |
540 |
|
540 | |||
541 | command_with_path = which(self.command) |
|
541 | command_with_path = which(self.command) | |
542 | if command_with_path is None: |
|
542 | if command_with_path is None: | |
543 | raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) |
|
543 | raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) | |
544 | self.command = command_with_path |
|
544 | self.command = command_with_path | |
545 | self.args[0] = self.command |
|
545 | self.args[0] = self.command | |
546 |
|
546 | |||
547 | self.name = '<' + ' '.join (self.args) + '>' |
|
547 | self.name = '<' + ' '.join (self.args) + '>' | |
548 |
|
548 | |||
549 | assert self.pid is None, 'The pid member should be None.' |
|
549 | assert self.pid is None, 'The pid member should be None.' | |
550 | assert self.command is not None, 'The command member should not be None.' |
|
550 | assert self.command is not None, 'The command member should not be None.' | |
551 |
|
551 | |||
552 | if self.use_native_pty_fork: |
|
552 | if self.use_native_pty_fork: | |
553 | try: |
|
553 | try: | |
554 | self.pid, self.child_fd = pty.fork() |
|
554 | self.pid, self.child_fd = pty.fork() | |
555 | except OSError as e: |
|
555 | except OSError as e: | |
556 | raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) |
|
556 | raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e)) | |
557 | else: # Use internal __fork_pty |
|
557 | else: # Use internal __fork_pty | |
558 | self.pid, self.child_fd = self.__fork_pty() |
|
558 | self.pid, self.child_fd = self.__fork_pty() | |
559 |
|
559 | |||
560 | if self.pid == 0: # Child |
|
560 | if self.pid == 0: # Child | |
561 | try: |
|
561 | try: | |
562 | self.child_fd = sys.stdout.fileno() # used by setwinsize() |
|
562 | self.child_fd = sys.stdout.fileno() # used by setwinsize() | |
563 | self.setwinsize(24, 80) |
|
563 | self.setwinsize(24, 80) | |
564 | except: |
|
564 | except: | |
565 | # Some platforms do not like setwinsize (Cygwin). |
|
565 | # Some platforms do not like setwinsize (Cygwin). | |
566 | # This will cause problem when running applications that |
|
566 | # This will cause problem when running applications that | |
567 | # are very picky about window size. |
|
567 | # are very picky about window size. | |
568 | # This is a serious limitation, but not a show stopper. |
|
568 | # This is a serious limitation, but not a show stopper. | |
569 | pass |
|
569 | pass | |
570 | # Do not allow child to inherit open file descriptors from parent. |
|
570 | # Do not allow child to inherit open file descriptors from parent. | |
571 | max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] |
|
571 | max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] | |
572 | for i in range (3, max_fd): |
|
572 | for i in range (3, max_fd): | |
573 | try: |
|
573 | try: | |
574 | os.close (i) |
|
574 | os.close (i) | |
575 | except OSError: |
|
575 | except OSError: | |
576 | pass |
|
576 | pass | |
577 |
|
577 | |||
578 | # I don't know why this works, but ignoring SIGHUP fixes a |
|
578 | # I don't know why this works, but ignoring SIGHUP fixes a | |
579 | # problem when trying to start a Java daemon with sudo |
|
579 | # problem when trying to start a Java daemon with sudo | |
580 | # (specifically, Tomcat). |
|
580 | # (specifically, Tomcat). | |
581 | signal.signal(signal.SIGHUP, signal.SIG_IGN) |
|
581 | signal.signal(signal.SIGHUP, signal.SIG_IGN) | |
582 |
|
582 | |||
583 | if self.cwd is not None: |
|
583 | if self.cwd is not None: | |
584 | os.chdir(self.cwd) |
|
584 | os.chdir(self.cwd) | |
585 | if self.env is None: |
|
585 | if self.env is None: | |
586 | os.execv(self.command, self.args) |
|
586 | os.execv(self.command, self.args) | |
587 | else: |
|
587 | else: | |
588 | os.execvpe(self.command, self.args, self.env) |
|
588 | os.execvpe(self.command, self.args, self.env) | |
589 |
|
589 | |||
590 | # Parent |
|
590 | # Parent | |
591 | self.terminated = False |
|
591 | self.terminated = False | |
592 | self.closed = False |
|
592 | self.closed = False | |
593 |
|
593 | |||
594 | def __fork_pty(self): |
|
594 | def __fork_pty(self): | |
595 |
|
595 | |||
596 | """This implements a substitute for the forkpty system call. This |
|
596 | """This implements a substitute for the forkpty system call. This | |
597 | should be more portable than the pty.fork() function. Specifically, |
|
597 | should be more portable than the pty.fork() function. Specifically, | |
598 | this should work on Solaris. |
|
598 | this should work on Solaris. | |
599 |
|
599 | |||
600 | Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to |
|
600 | Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to | |
601 | resolve the issue with Python's pty.fork() not supporting Solaris, |
|
601 | resolve the issue with Python's pty.fork() not supporting Solaris, | |
602 | particularly ssh. Based on patch to posixmodule.c authored by Noah |
|
602 | particularly ssh. Based on patch to posixmodule.c authored by Noah | |
603 | Spurrier:: |
|
603 | Spurrier:: | |
604 |
|
604 | |||
605 | http://mail.python.org/pipermail/python-dev/2003-May/035281.html |
|
605 | http://mail.python.org/pipermail/python-dev/2003-May/035281.html | |
606 |
|
606 | |||
607 | """ |
|
607 | """ | |
608 |
|
608 | |||
609 | parent_fd, child_fd = os.openpty() |
|
609 | parent_fd, child_fd = os.openpty() | |
610 | if parent_fd < 0 or child_fd < 0: |
|
610 | if parent_fd < 0 or child_fd < 0: | |
611 |
raise ExceptionPexpect |
|
611 | raise ExceptionPexpect("Error! Could not open pty with os.openpty().") | |
612 |
|
612 | |||
613 | pid = os.fork() |
|
613 | pid = os.fork() | |
614 | if pid < 0: |
|
614 | if pid < 0: | |
615 |
raise ExceptionPexpect |
|
615 | raise ExceptionPexpect("Error! Failed os.fork().") | |
616 | elif pid == 0: |
|
616 | elif pid == 0: | |
617 | # Child. |
|
617 | # Child. | |
618 | os.close(parent_fd) |
|
618 | os.close(parent_fd) | |
619 | self.__pty_make_controlling_tty(child_fd) |
|
619 | self.__pty_make_controlling_tty(child_fd) | |
620 |
|
620 | |||
621 | os.dup2(child_fd, 0) |
|
621 | os.dup2(child_fd, 0) | |
622 | os.dup2(child_fd, 1) |
|
622 | os.dup2(child_fd, 1) | |
623 | os.dup2(child_fd, 2) |
|
623 | os.dup2(child_fd, 2) | |
624 |
|
624 | |||
625 | if child_fd > 2: |
|
625 | if child_fd > 2: | |
626 | os.close(child_fd) |
|
626 | os.close(child_fd) | |
627 | else: |
|
627 | else: | |
628 | # Parent. |
|
628 | # Parent. | |
629 | os.close(child_fd) |
|
629 | os.close(child_fd) | |
630 |
|
630 | |||
631 | return pid, parent_fd |
|
631 | return pid, parent_fd | |
632 |
|
632 | |||
633 | def __pty_make_controlling_tty(self, tty_fd): |
|
633 | def __pty_make_controlling_tty(self, tty_fd): | |
634 |
|
634 | |||
635 | """This makes the pseudo-terminal the controlling tty. This should be |
|
635 | """This makes the pseudo-terminal the controlling tty. This should be | |
636 | more portable than the pty.fork() function. Specifically, this should |
|
636 | more portable than the pty.fork() function. Specifically, this should | |
637 | work on Solaris. """ |
|
637 | work on Solaris. """ | |
638 |
|
638 | |||
639 | child_name = os.ttyname(tty_fd) |
|
639 | child_name = os.ttyname(tty_fd) | |
640 |
|
640 | |||
641 | # Disconnect from controlling tty. Harmless if not already connected. |
|
641 | # Disconnect from controlling tty. Harmless if not already connected. | |
642 | try: |
|
642 | try: | |
643 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); |
|
643 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); | |
644 | if fd >= 0: |
|
644 | if fd >= 0: | |
645 | os.close(fd) |
|
645 | os.close(fd) | |
646 | except: |
|
646 | except: | |
647 | # Already disconnected. This happens if running inside cron. |
|
647 | # Already disconnected. This happens if running inside cron. | |
648 | pass |
|
648 | pass | |
649 |
|
649 | |||
650 | os.setsid() |
|
650 | os.setsid() | |
651 |
|
651 | |||
652 | # Verify we are disconnected from controlling tty |
|
652 | # Verify we are disconnected from controlling tty | |
653 | # by attempting to open it again. |
|
653 | # by attempting to open it again. | |
654 | try: |
|
654 | try: | |
655 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); |
|
655 | fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY); | |
656 | if fd >= 0: |
|
656 | if fd >= 0: | |
657 | os.close(fd) |
|
657 | os.close(fd) | |
658 |
raise ExceptionPexpect |
|
658 | raise ExceptionPexpect("Error! Failed to disconnect from controlling tty. It is still possible to open /dev/tty.") | |
659 | except: |
|
659 | except: | |
660 | # Good! We are disconnected from a controlling tty. |
|
660 | # Good! We are disconnected from a controlling tty. | |
661 | pass |
|
661 | pass | |
662 |
|
662 | |||
663 | # Verify we can open child pty. |
|
663 | # Verify we can open child pty. | |
664 | fd = os.open(child_name, os.O_RDWR); |
|
664 | fd = os.open(child_name, os.O_RDWR); | |
665 | if fd < 0: |
|
665 | if fd < 0: | |
666 |
raise ExceptionPexpect |
|
666 | raise ExceptionPexpect("Error! Could not open child pty, " + child_name) | |
667 | else: |
|
667 | else: | |
668 | os.close(fd) |
|
668 | os.close(fd) | |
669 |
|
669 | |||
670 | # Verify we now have a controlling tty. |
|
670 | # Verify we now have a controlling tty. | |
671 | fd = os.open("/dev/tty", os.O_WRONLY) |
|
671 | fd = os.open("/dev/tty", os.O_WRONLY) | |
672 | if fd < 0: |
|
672 | if fd < 0: | |
673 |
raise ExceptionPexpect |
|
673 | raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty") | |
674 | else: |
|
674 | else: | |
675 | os.close(fd) |
|
675 | os.close(fd) | |
676 |
|
676 | |||
677 | def fileno (self): # File-like object. |
|
677 | def fileno (self): # File-like object. | |
678 |
|
678 | |||
679 | """This returns the file descriptor of the pty for the child. |
|
679 | """This returns the file descriptor of the pty for the child. | |
680 | """ |
|
680 | """ | |
681 |
|
681 | |||
682 | return self.child_fd |
|
682 | return self.child_fd | |
683 |
|
683 | |||
684 | def close (self, force=True): # File-like object. |
|
684 | def close (self, force=True): # File-like object. | |
685 |
|
685 | |||
686 | """This closes the connection with the child application. Note that |
|
686 | """This closes the connection with the child application. Note that | |
687 | calling close() more than once is valid. This emulates standard Python |
|
687 | calling close() more than once is valid. This emulates standard Python | |
688 | behavior with files. Set force to True if you want to make sure that |
|
688 | behavior with files. Set force to True if you want to make sure that | |
689 | the child is terminated (SIGKILL is sent if the child ignores SIGHUP |
|
689 | the child is terminated (SIGKILL is sent if the child ignores SIGHUP | |
690 | and SIGINT). """ |
|
690 | and SIGINT). """ | |
691 |
|
691 | |||
692 | if not self.closed: |
|
692 | if not self.closed: | |
693 | self.flush() |
|
693 | self.flush() | |
694 | os.close (self.child_fd) |
|
694 | os.close (self.child_fd) | |
695 | time.sleep(self.delayafterclose) # Give kernel time to update process status. |
|
695 | time.sleep(self.delayafterclose) # Give kernel time to update process status. | |
696 | if self.isalive(): |
|
696 | if self.isalive(): | |
697 | if not self.terminate(force): |
|
697 | if not self.terminate(force): | |
698 | raise ExceptionPexpect ('close() could not terminate the child using terminate()') |
|
698 | raise ExceptionPexpect ('close() could not terminate the child using terminate()') | |
699 | self.child_fd = -1 |
|
699 | self.child_fd = -1 | |
700 | self.closed = True |
|
700 | self.closed = True | |
701 | #self.pid = None |
|
701 | #self.pid = None | |
702 |
|
702 | |||
703 | def flush (self): # File-like object. |
|
703 | def flush (self): # File-like object. | |
704 |
|
704 | |||
705 | """This does nothing. It is here to support the interface for a |
|
705 | """This does nothing. It is here to support the interface for a | |
706 | File-like object. """ |
|
706 | File-like object. """ | |
707 |
|
707 | |||
708 | pass |
|
708 | pass | |
709 |
|
709 | |||
710 | def isatty (self): # File-like object. |
|
710 | def isatty (self): # File-like object. | |
711 |
|
711 | |||
712 | """This returns True if the file descriptor is open and connected to a |
|
712 | """This returns True if the file descriptor is open and connected to a | |
713 | tty(-like) device, else False. """ |
|
713 | tty(-like) device, else False. """ | |
714 |
|
714 | |||
715 | return os.isatty(self.child_fd) |
|
715 | return os.isatty(self.child_fd) | |
716 |
|
716 | |||
717 | def waitnoecho (self, timeout=-1): |
|
717 | def waitnoecho (self, timeout=-1): | |
718 |
|
718 | |||
719 | """This waits until the terminal ECHO flag is set False. This returns |
|
719 | """This waits until the terminal ECHO flag is set False. This returns | |
720 | True if the echo mode is off. This returns False if the ECHO flag was |
|
720 | True if the echo mode is off. This returns False if the ECHO flag was | |
721 | not set False before the timeout. This can be used to detect when the |
|
721 | not set False before the timeout. This can be used to detect when the | |
722 | child is waiting for a password. Usually a child application will turn |
|
722 | child is waiting for a password. Usually a child application will turn | |
723 | off echo mode when it is waiting for the user to enter a password. For |
|
723 | off echo mode when it is waiting for the user to enter a password. For | |
724 | example, instead of expecting the "password:" prompt you can wait for |
|
724 | example, instead of expecting the "password:" prompt you can wait for | |
725 | the child to set ECHO off:: |
|
725 | the child to set ECHO off:: | |
726 |
|
726 | |||
727 | p = pexpect.spawn ('ssh user@example.com') |
|
727 | p = pexpect.spawn ('ssh user@example.com') | |
728 | p.waitnoecho() |
|
728 | p.waitnoecho() | |
729 | p.sendline(mypassword) |
|
729 | p.sendline(mypassword) | |
730 |
|
730 | |||
731 | If timeout==-1 then this method will use the value in self.timeout. |
|
731 | If timeout==-1 then this method will use the value in self.timeout. | |
732 | If timeout==None then this method to block until ECHO flag is False. |
|
732 | If timeout==None then this method to block until ECHO flag is False. | |
733 | """ |
|
733 | """ | |
734 |
|
734 | |||
735 | if timeout == -1: |
|
735 | if timeout == -1: | |
736 | timeout = self.timeout |
|
736 | timeout = self.timeout | |
737 | if timeout is not None: |
|
737 | if timeout is not None: | |
738 | end_time = time.time() + timeout |
|
738 | end_time = time.time() + timeout | |
739 | while True: |
|
739 | while True: | |
740 | if not self.getecho(): |
|
740 | if not self.getecho(): | |
741 | return True |
|
741 | return True | |
742 | if timeout < 0 and timeout is not None: |
|
742 | if timeout < 0 and timeout is not None: | |
743 | return False |
|
743 | return False | |
744 | if timeout is not None: |
|
744 | if timeout is not None: | |
745 | timeout = end_time - time.time() |
|
745 | timeout = end_time - time.time() | |
746 | time.sleep(0.1) |
|
746 | time.sleep(0.1) | |
747 |
|
747 | |||
748 | def getecho (self): |
|
748 | def getecho (self): | |
749 |
|
749 | |||
750 | """This returns the terminal echo mode. This returns True if echo is |
|
750 | """This returns the terminal echo mode. This returns True if echo is | |
751 | on or False if echo is off. Child applications that are expecting you |
|
751 | on or False if echo is off. Child applications that are expecting you | |
752 | to enter a password often set ECHO False. See waitnoecho(). """ |
|
752 | to enter a password often set ECHO False. See waitnoecho(). """ | |
753 |
|
753 | |||
754 | attr = termios.tcgetattr(self.child_fd) |
|
754 | attr = termios.tcgetattr(self.child_fd) | |
755 | if attr[3] & termios.ECHO: |
|
755 | if attr[3] & termios.ECHO: | |
756 | return True |
|
756 | return True | |
757 | return False |
|
757 | return False | |
758 |
|
758 | |||
759 | def setecho (self, state): |
|
759 | def setecho (self, state): | |
760 |
|
760 | |||
761 | """This sets the terminal echo mode on or off. Note that anything the |
|
761 | """This sets the terminal echo mode on or off. Note that anything the | |
762 | child sent before the echo will be lost, so you should be sure that |
|
762 | child sent before the echo will be lost, so you should be sure that | |
763 | your input buffer is empty before you call setecho(). For example, the |
|
763 | your input buffer is empty before you call setecho(). For example, the | |
764 | following will work as expected:: |
|
764 | following will work as expected:: | |
765 |
|
765 | |||
766 | p = pexpect.spawn('cat') |
|
766 | p = pexpect.spawn('cat') | |
767 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). |
|
767 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). | |
768 | p.expect (['1234']) |
|
768 | p.expect (['1234']) | |
769 | p.expect (['1234']) |
|
769 | p.expect (['1234']) | |
770 | p.setecho(False) # Turn off tty echo |
|
770 | p.setecho(False) # Turn off tty echo | |
771 | p.sendline ('abcd') # We will set this only once (echoed by cat). |
|
771 | p.sendline ('abcd') # We will set this only once (echoed by cat). | |
772 | p.sendline ('wxyz') # We will set this only once (echoed by cat) |
|
772 | p.sendline ('wxyz') # We will set this only once (echoed by cat) | |
773 | p.expect (['abcd']) |
|
773 | p.expect (['abcd']) | |
774 | p.expect (['wxyz']) |
|
774 | p.expect (['wxyz']) | |
775 |
|
775 | |||
776 | The following WILL NOT WORK because the lines sent before the setecho |
|
776 | The following WILL NOT WORK because the lines sent before the setecho | |
777 | will be lost:: |
|
777 | will be lost:: | |
778 |
|
778 | |||
779 | p = pexpect.spawn('cat') |
|
779 | p = pexpect.spawn('cat') | |
780 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). |
|
780 | p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). | |
781 | p.setecho(False) # Turn off tty echo |
|
781 | p.setecho(False) # Turn off tty echo | |
782 | p.sendline ('abcd') # We will set this only once (echoed by cat). |
|
782 | p.sendline ('abcd') # We will set this only once (echoed by cat). | |
783 | p.sendline ('wxyz') # We will set this only once (echoed by cat) |
|
783 | p.sendline ('wxyz') # We will set this only once (echoed by cat) | |
784 | p.expect (['1234']) |
|
784 | p.expect (['1234']) | |
785 | p.expect (['1234']) |
|
785 | p.expect (['1234']) | |
786 | p.expect (['abcd']) |
|
786 | p.expect (['abcd']) | |
787 | p.expect (['wxyz']) |
|
787 | p.expect (['wxyz']) | |
788 | """ |
|
788 | """ | |
789 |
|
789 | |||
790 | self.child_fd |
|
790 | self.child_fd | |
791 | attr = termios.tcgetattr(self.child_fd) |
|
791 | attr = termios.tcgetattr(self.child_fd) | |
792 | if state: |
|
792 | if state: | |
793 | attr[3] = attr[3] | termios.ECHO |
|
793 | attr[3] = attr[3] | termios.ECHO | |
794 | else: |
|
794 | else: | |
795 | attr[3] = attr[3] & ~termios.ECHO |
|
795 | attr[3] = attr[3] & ~termios.ECHO | |
796 | # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent |
|
796 | # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent | |
797 | # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. |
|
797 | # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. | |
798 | termios.tcsetattr(self.child_fd, termios.TCSANOW, attr) |
|
798 | termios.tcsetattr(self.child_fd, termios.TCSANOW, attr) | |
799 |
|
799 | |||
800 | def read_nonblocking (self, size = 1, timeout = -1): |
|
800 | def read_nonblocking (self, size = 1, timeout = -1): | |
801 |
|
801 | |||
802 | """This reads at most size bytes from the child application. It |
|
802 | """This reads at most size bytes from the child application. It | |
803 | includes a timeout. If the read does not complete within the timeout |
|
803 | includes a timeout. If the read does not complete within the timeout | |
804 | period then a TIMEOUT exception is raised. If the end of file is read |
|
804 | period then a TIMEOUT exception is raised. If the end of file is read | |
805 | then an EOF exception will be raised. If a log file was set using |
|
805 | then an EOF exception will be raised. If a log file was set using | |
806 | setlog() then all data will also be written to the log file. |
|
806 | setlog() then all data will also be written to the log file. | |
807 |
|
807 | |||
808 | If timeout is None then the read may block indefinitely. If timeout is -1 |
|
808 | If timeout is None then the read may block indefinitely. If timeout is -1 | |
809 | then the self.timeout value is used. If timeout is 0 then the child is |
|
809 | then the self.timeout value is used. If timeout is 0 then the child is | |
810 | polled and if there was no data immediately ready then this will raise |
|
810 | polled and if there was no data immediately ready then this will raise | |
811 | a TIMEOUT exception. |
|
811 | a TIMEOUT exception. | |
812 |
|
812 | |||
813 | The timeout refers only to the amount of time to read at least one |
|
813 | The timeout refers only to the amount of time to read at least one | |
814 | character. This is not effected by the 'size' parameter, so if you call |
|
814 | character. This is not effected by the 'size' parameter, so if you call | |
815 | read_nonblocking(size=100, timeout=30) and only one character is |
|
815 | read_nonblocking(size=100, timeout=30) and only one character is | |
816 | available right away then one character will be returned immediately. |
|
816 | available right away then one character will be returned immediately. | |
817 | It will not wait for 30 seconds for another 99 characters to come in. |
|
817 | It will not wait for 30 seconds for another 99 characters to come in. | |
818 |
|
818 | |||
819 | This is a wrapper around os.read(). It uses select.select() to |
|
819 | This is a wrapper around os.read(). It uses select.select() to | |
820 | implement the timeout. """ |
|
820 | implement the timeout. """ | |
821 |
|
821 | |||
822 | if self.closed: |
|
822 | if self.closed: | |
823 | raise ValueError ('I/O operation on closed file in read_nonblocking().') |
|
823 | raise ValueError ('I/O operation on closed file in read_nonblocking().') | |
824 |
|
824 | |||
825 | if timeout == -1: |
|
825 | if timeout == -1: | |
826 | timeout = self.timeout |
|
826 | timeout = self.timeout | |
827 |
|
827 | |||
828 | # Note that some systems such as Solaris do not give an EOF when |
|
828 | # Note that some systems such as Solaris do not give an EOF when | |
829 | # the child dies. In fact, you can still try to read |
|
829 | # the child dies. In fact, you can still try to read | |
830 | # from the child_fd -- it will block forever or until TIMEOUT. |
|
830 | # from the child_fd -- it will block forever or until TIMEOUT. | |
831 | # For this case, I test isalive() before doing any reading. |
|
831 | # For this case, I test isalive() before doing any reading. | |
832 | # If isalive() is false, then I pretend that this is the same as EOF. |
|
832 | # If isalive() is false, then I pretend that this is the same as EOF. | |
833 | if not self.isalive(): |
|
833 | if not self.isalive(): | |
834 | r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" |
|
834 | r,w,e = self.__select([self.child_fd], [], [], 0) # timeout of 0 means "poll" | |
835 | if not r: |
|
835 | if not r: | |
836 | self.flag_eof = True |
|
836 | self.flag_eof = True | |
837 | raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') |
|
837 | raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') | |
838 | elif self.__irix_hack: |
|
838 | elif self.__irix_hack: | |
839 | # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. |
|
839 | # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. | |
840 | # This adds a 2 second delay, but only when the child is terminated. |
|
840 | # This adds a 2 second delay, but only when the child is terminated. | |
841 | r, w, e = self.__select([self.child_fd], [], [], 2) |
|
841 | r, w, e = self.__select([self.child_fd], [], [], 2) | |
842 | if not r and not self.isalive(): |
|
842 | if not r and not self.isalive(): | |
843 | self.flag_eof = True |
|
843 | self.flag_eof = True | |
844 | raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') |
|
844 | raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') | |
845 |
|
845 | |||
846 | r,w,e = self.__select([self.child_fd], [], [], timeout) |
|
846 | r,w,e = self.__select([self.child_fd], [], [], timeout) | |
847 |
|
847 | |||
848 | if not r: |
|
848 | if not r: | |
849 | if not self.isalive(): |
|
849 | if not self.isalive(): | |
850 | # Some platforms, such as Irix, will claim that their processes are alive; |
|
850 | # Some platforms, such as Irix, will claim that their processes are alive; | |
851 | # then timeout on the select; and then finally admit that they are not alive. |
|
851 | # then timeout on the select; and then finally admit that they are not alive. | |
852 | self.flag_eof = True |
|
852 | self.flag_eof = True | |
853 | raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') |
|
853 | raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') | |
854 | else: |
|
854 | else: | |
855 | raise TIMEOUT ('Timeout exceeded in read_nonblocking().') |
|
855 | raise TIMEOUT ('Timeout exceeded in read_nonblocking().') | |
856 |
|
856 | |||
857 | if self.child_fd in r: |
|
857 | if self.child_fd in r: | |
858 | try: |
|
858 | try: | |
859 | s = os.read(self.child_fd, size) |
|
859 | s = os.read(self.child_fd, size) | |
860 | except OSError as e: # Linux does this |
|
860 | except OSError as e: # Linux does this | |
861 | self.flag_eof = True |
|
861 | self.flag_eof = True | |
862 | raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') |
|
862 | raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') | |
863 | if s == b'': # BSD style |
|
863 | if s == b'': # BSD style | |
864 | self.flag_eof = True |
|
864 | self.flag_eof = True | |
865 | raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') |
|
865 | raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') | |
866 |
|
866 | |||
867 | s2 = self._cast_buffer_type(s) |
|
867 | s2 = self._cast_buffer_type(s) | |
868 | if self.logfile is not None: |
|
868 | if self.logfile is not None: | |
869 | self.logfile.write(s2) |
|
869 | self.logfile.write(s2) | |
870 | self.logfile.flush() |
|
870 | self.logfile.flush() | |
871 | if self.logfile_read is not None: |
|
871 | if self.logfile_read is not None: | |
872 | self.logfile_read.write(s2) |
|
872 | self.logfile_read.write(s2) | |
873 | self.logfile_read.flush() |
|
873 | self.logfile_read.flush() | |
874 |
|
874 | |||
875 | return s |
|
875 | return s | |
876 |
|
876 | |||
877 | raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().') |
|
877 | raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().') | |
878 |
|
878 | |||
879 | def read (self, size = -1): # File-like object. |
|
879 | def read (self, size = -1): # File-like object. | |
880 | """This reads at most "size" bytes from the file (less if the read hits |
|
880 | """This reads at most "size" bytes from the file (less if the read hits | |
881 | EOF before obtaining size bytes). If the size argument is negative or |
|
881 | EOF before obtaining size bytes). If the size argument is negative or | |
882 | omitted, read all data until EOF is reached. The bytes are returned as |
|
882 | omitted, read all data until EOF is reached. The bytes are returned as | |
883 | a string object. An empty string is returned when EOF is encountered |
|
883 | a string object. An empty string is returned when EOF is encountered | |
884 | immediately. """ |
|
884 | immediately. """ | |
885 |
|
885 | |||
886 | if size == 0: |
|
886 | if size == 0: | |
887 | return self._empty_buffer |
|
887 | return self._empty_buffer | |
888 | if size < 0: |
|
888 | if size < 0: | |
889 | self.expect (self.delimiter) # delimiter default is EOF |
|
889 | self.expect (self.delimiter) # delimiter default is EOF | |
890 | return self.before |
|
890 | return self.before | |
891 |
|
891 | |||
892 | # I could have done this more directly by not using expect(), but |
|
892 | # I could have done this more directly by not using expect(), but | |
893 | # I deliberately decided to couple read() to expect() so that |
|
893 | # I deliberately decided to couple read() to expect() so that | |
894 | # I would catch any bugs early and ensure consistant behavior. |
|
894 | # I would catch any bugs early and ensure consistant behavior. | |
895 | # It's a little less efficient, but there is less for me to |
|
895 | # It's a little less efficient, but there is less for me to | |
896 | # worry about if I have to later modify read() or expect(). |
|
896 | # worry about if I have to later modify read() or expect(). | |
897 | # Note, it's OK if size==-1 in the regex. That just means it |
|
897 | # Note, it's OK if size==-1 in the regex. That just means it | |
898 | # will never match anything in which case we stop only on EOF. |
|
898 | # will never match anything in which case we stop only on EOF. | |
899 | if self._buffer_type is bytes: |
|
899 | if self._buffer_type is bytes: | |
900 | pat = (u'.{%d}' % size).encode('ascii') |
|
900 | pat = (u'.{%d}' % size).encode('ascii') | |
901 | else: |
|
901 | else: | |
902 | pat = u'.{%d}' % size |
|
902 | pat = u'.{%d}' % size | |
903 | cre = re.compile(pat, re.DOTALL) |
|
903 | cre = re.compile(pat, re.DOTALL) | |
904 | index = self.expect ([cre, self.delimiter]) # delimiter default is EOF |
|
904 | index = self.expect ([cre, self.delimiter]) # delimiter default is EOF | |
905 | if index == 0: |
|
905 | if index == 0: | |
906 | return self.after ### self.before should be ''. Should I assert this? |
|
906 | return self.after ### self.before should be ''. Should I assert this? | |
907 | return self.before |
|
907 | return self.before | |
908 |
|
908 | |||
909 | def readline(self, size = -1): |
|
909 | def readline(self, size = -1): | |
910 | """This reads and returns one entire line. A trailing newline is kept |
|
910 | """This reads and returns one entire line. A trailing newline is kept | |
911 | in the string, but may be absent when a file ends with an incomplete |
|
911 | in the string, but may be absent when a file ends with an incomplete | |
912 | line. Note: This readline() looks for a \\r\\n pair even on UNIX |
|
912 | line. Note: This readline() looks for a \\r\\n pair even on UNIX | |
913 | because this is what the pseudo tty device returns. So contrary to what |
|
913 | because this is what the pseudo tty device returns. So contrary to what | |
914 | you may expect you will receive the newline as \\r\\n. An empty string |
|
914 | you may expect you will receive the newline as \\r\\n. An empty string | |
915 | is returned when EOF is hit immediately. Currently, the size argument is |
|
915 | is returned when EOF is hit immediately. Currently, the size argument is | |
916 | mostly ignored, so this behavior is not standard for a file-like |
|
916 | mostly ignored, so this behavior is not standard for a file-like | |
917 | object. If size is 0 then an empty string is returned. """ |
|
917 | object. If size is 0 then an empty string is returned. """ | |
918 |
|
918 | |||
919 | if size == 0: |
|
919 | if size == 0: | |
920 | return self._empty_buffer |
|
920 | return self._empty_buffer | |
921 | index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF |
|
921 | index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF | |
922 | if index == 0: |
|
922 | if index == 0: | |
923 | return self.before + self._pty_newline |
|
923 | return self.before + self._pty_newline | |
924 | return self.before |
|
924 | return self.before | |
925 |
|
925 | |||
926 | def __iter__ (self): # File-like object. |
|
926 | def __iter__ (self): # File-like object. | |
927 |
|
927 | |||
928 | """This is to support iterators over a file-like object. |
|
928 | """This is to support iterators over a file-like object. | |
929 | """ |
|
929 | """ | |
930 |
|
930 | |||
931 | return self |
|
931 | return self | |
932 |
|
932 | |||
933 | def next (self): # File-like object. |
|
933 | def next (self): # File-like object. | |
934 |
|
934 | |||
935 | """This is to support iterators over a file-like object. |
|
935 | """This is to support iterators over a file-like object. | |
936 | """ |
|
936 | """ | |
937 |
|
937 | |||
938 | result = self.readline() |
|
938 | result = self.readline() | |
939 | if result == self._empty_buffer: |
|
939 | if result == self._empty_buffer: | |
940 | raise StopIteration |
|
940 | raise StopIteration | |
941 | return result |
|
941 | return result | |
942 |
|
942 | |||
943 | def readlines (self, sizehint = -1): # File-like object. |
|
943 | def readlines (self, sizehint = -1): # File-like object. | |
944 |
|
944 | |||
945 | """This reads until EOF using readline() and returns a list containing |
|
945 | """This reads until EOF using readline() and returns a list containing | |
946 | the lines thus read. The optional "sizehint" argument is ignored. """ |
|
946 | the lines thus read. The optional "sizehint" argument is ignored. """ | |
947 |
|
947 | |||
948 | lines = [] |
|
948 | lines = [] | |
949 | while True: |
|
949 | while True: | |
950 | line = self.readline() |
|
950 | line = self.readline() | |
951 | if not line: |
|
951 | if not line: | |
952 | break |
|
952 | break | |
953 | lines.append(line) |
|
953 | lines.append(line) | |
954 | return lines |
|
954 | return lines | |
955 |
|
955 | |||
956 | def write(self, s): # File-like object. |
|
956 | def write(self, s): # File-like object. | |
957 |
|
957 | |||
958 | """This is similar to send() except that there is no return value. |
|
958 | """This is similar to send() except that there is no return value. | |
959 | """ |
|
959 | """ | |
960 |
|
960 | |||
961 | self.send (s) |
|
961 | self.send (s) | |
962 |
|
962 | |||
963 | def writelines (self, sequence): # File-like object. |
|
963 | def writelines (self, sequence): # File-like object. | |
964 |
|
964 | |||
965 | """This calls write() for each element in the sequence. The sequence |
|
965 | """This calls write() for each element in the sequence. The sequence | |
966 | can be any iterable object producing strings, typically a list of |
|
966 | can be any iterable object producing strings, typically a list of | |
967 | strings. This does not add line separators There is no return value. |
|
967 | strings. This does not add line separators There is no return value. | |
968 | """ |
|
968 | """ | |
969 |
|
969 | |||
970 | for s in sequence: |
|
970 | for s in sequence: | |
971 | self.write (s) |
|
971 | self.write (s) | |
972 |
|
972 | |||
973 | def send(self, s): |
|
973 | def send(self, s): | |
974 |
|
974 | |||
975 | """This sends a string to the child process. This returns the number of |
|
975 | """This sends a string to the child process. This returns the number of | |
976 | bytes written. If a log file was set then the data is also written to |
|
976 | bytes written. If a log file was set then the data is also written to | |
977 | the log. """ |
|
977 | the log. """ | |
978 |
|
978 | |||
979 | time.sleep(self.delaybeforesend) |
|
979 | time.sleep(self.delaybeforesend) | |
980 |
|
980 | |||
981 | s2 = self._cast_buffer_type(s) |
|
981 | s2 = self._cast_buffer_type(s) | |
982 | if self.logfile is not None: |
|
982 | if self.logfile is not None: | |
983 | self.logfile.write(s2) |
|
983 | self.logfile.write(s2) | |
984 | self.logfile.flush() |
|
984 | self.logfile.flush() | |
985 | if self.logfile_send is not None: |
|
985 | if self.logfile_send is not None: | |
986 | self.logfile_send.write(s2) |
|
986 | self.logfile_send.write(s2) | |
987 | self.logfile_send.flush() |
|
987 | self.logfile_send.flush() | |
988 | c = os.write (self.child_fd, _cast_bytes(s, self.encoding)) |
|
988 | c = os.write (self.child_fd, _cast_bytes(s, self.encoding)) | |
989 | return c |
|
989 | return c | |
990 |
|
990 | |||
991 | def sendline(self, s=''): |
|
991 | def sendline(self, s=''): | |
992 |
|
992 | |||
993 | """This is like send(), but it adds a line feed (os.linesep). This |
|
993 | """This is like send(), but it adds a line feed (os.linesep). This | |
994 | returns the number of bytes written. """ |
|
994 | returns the number of bytes written. """ | |
995 |
|
995 | |||
996 | n = self.send (s) |
|
996 | n = self.send (s) | |
997 | n = n + self.send (os.linesep) |
|
997 | n = n + self.send (os.linesep) | |
998 | return n |
|
998 | return n | |
999 |
|
999 | |||
1000 | def sendcontrol(self, char): |
|
1000 | def sendcontrol(self, char): | |
1001 |
|
1001 | |||
1002 | """This sends a control character to the child such as Ctrl-C or |
|
1002 | """This sends a control character to the child such as Ctrl-C or | |
1003 | Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: |
|
1003 | Ctrl-D. For example, to send a Ctrl-G (ASCII 7):: | |
1004 |
|
1004 | |||
1005 | child.sendcontrol('g') |
|
1005 | child.sendcontrol('g') | |
1006 |
|
1006 | |||
1007 | See also, sendintr() and sendeof(). |
|
1007 | See also, sendintr() and sendeof(). | |
1008 | """ |
|
1008 | """ | |
1009 |
|
1009 | |||
1010 | char = char.lower() |
|
1010 | char = char.lower() | |
1011 | a = ord(char) |
|
1011 | a = ord(char) | |
1012 | if a>=97 and a<=122: |
|
1012 | if a>=97 and a<=122: | |
1013 | a = a - ord('a') + 1 |
|
1013 | a = a - ord('a') + 1 | |
1014 | return self.send (chr(a)) |
|
1014 | return self.send (chr(a)) | |
1015 | d = {'@':0, '`':0, |
|
1015 | d = {'@':0, '`':0, | |
1016 | '[':27, '{':27, |
|
1016 | '[':27, '{':27, | |
1017 | '\\':28, '|':28, |
|
1017 | '\\':28, '|':28, | |
1018 | ']':29, '}': 29, |
|
1018 | ']':29, '}': 29, | |
1019 | '^':30, '~':30, |
|
1019 | '^':30, '~':30, | |
1020 | '_':31, |
|
1020 | '_':31, | |
1021 | '?':127} |
|
1021 | '?':127} | |
1022 | if char not in d: |
|
1022 | if char not in d: | |
1023 | return 0 |
|
1023 | return 0 | |
1024 | return self.send (chr(d[char])) |
|
1024 | return self.send (chr(d[char])) | |
1025 |
|
1025 | |||
1026 | def sendeof(self): |
|
1026 | def sendeof(self): | |
1027 |
|
1027 | |||
1028 | """This sends an EOF to the child. This sends a character which causes |
|
1028 | """This sends an EOF to the child. This sends a character which causes | |
1029 | the pending parent output buffer to be sent to the waiting child |
|
1029 | the pending parent output buffer to be sent to the waiting child | |
1030 | program without waiting for end-of-line. If it is the first character |
|
1030 | program without waiting for end-of-line. If it is the first character | |
1031 | of the line, the read() in the user program returns 0, which signifies |
|
1031 | of the line, the read() in the user program returns 0, which signifies | |
1032 | end-of-file. This means to work as expected a sendeof() has to be |
|
1032 | end-of-file. This means to work as expected a sendeof() has to be | |
1033 | called at the beginning of a line. This method does not send a newline. |
|
1033 | called at the beginning of a line. This method does not send a newline. | |
1034 | It is the responsibility of the caller to ensure the eof is sent at the |
|
1034 | It is the responsibility of the caller to ensure the eof is sent at the | |
1035 | beginning of a line. """ |
|
1035 | beginning of a line. """ | |
1036 |
|
1036 | |||
1037 | ### Hmmm... how do I send an EOF? |
|
1037 | ### Hmmm... how do I send an EOF? | |
1038 | ###C if ((m = write(pty, *buf, p - *buf)) < 0) |
|
1038 | ###C if ((m = write(pty, *buf, p - *buf)) < 0) | |
1039 | ###C return (errno == EWOULDBLOCK) ? n : -1; |
|
1039 | ###C return (errno == EWOULDBLOCK) ? n : -1; | |
1040 | #fd = sys.stdin.fileno() |
|
1040 | #fd = sys.stdin.fileno() | |
1041 | #old = termios.tcgetattr(fd) # remember current state |
|
1041 | #old = termios.tcgetattr(fd) # remember current state | |
1042 | #attr = termios.tcgetattr(fd) |
|
1042 | #attr = termios.tcgetattr(fd) | |
1043 | #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF |
|
1043 | #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF | |
1044 | #try: # use try/finally to ensure state gets restored |
|
1044 | #try: # use try/finally to ensure state gets restored | |
1045 | # termios.tcsetattr(fd, termios.TCSADRAIN, attr) |
|
1045 | # termios.tcsetattr(fd, termios.TCSADRAIN, attr) | |
1046 | # if hasattr(termios, 'CEOF'): |
|
1046 | # if hasattr(termios, 'CEOF'): | |
1047 | # os.write (self.child_fd, '%c' % termios.CEOF) |
|
1047 | # os.write (self.child_fd, '%c' % termios.CEOF) | |
1048 | # else: |
|
1048 | # else: | |
1049 | # # Silly platform does not define CEOF so assume CTRL-D |
|
1049 | # # Silly platform does not define CEOF so assume CTRL-D | |
1050 | # os.write (self.child_fd, '%c' % 4) |
|
1050 | # os.write (self.child_fd, '%c' % 4) | |
1051 | #finally: # restore state |
|
1051 | #finally: # restore state | |
1052 | # termios.tcsetattr(fd, termios.TCSADRAIN, old) |
|
1052 | # termios.tcsetattr(fd, termios.TCSADRAIN, old) | |
1053 | if hasattr(termios, 'VEOF'): |
|
1053 | if hasattr(termios, 'VEOF'): | |
1054 | char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] |
|
1054 | char = termios.tcgetattr(self.child_fd)[6][termios.VEOF] | |
1055 | else: |
|
1055 | else: | |
1056 | # platform does not define VEOF so assume CTRL-D |
|
1056 | # platform does not define VEOF so assume CTRL-D | |
1057 | char = chr(4) |
|
1057 | char = chr(4) | |
1058 | self.send(char) |
|
1058 | self.send(char) | |
1059 |
|
1059 | |||
1060 | def sendintr(self): |
|
1060 | def sendintr(self): | |
1061 |
|
1061 | |||
1062 | """This sends a SIGINT to the child. It does not require |
|
1062 | """This sends a SIGINT to the child. It does not require | |
1063 | the SIGINT to be the first character on a line. """ |
|
1063 | the SIGINT to be the first character on a line. """ | |
1064 |
|
1064 | |||
1065 | if hasattr(termios, 'VINTR'): |
|
1065 | if hasattr(termios, 'VINTR'): | |
1066 | char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] |
|
1066 | char = termios.tcgetattr(self.child_fd)[6][termios.VINTR] | |
1067 | else: |
|
1067 | else: | |
1068 | # platform does not define VINTR so assume CTRL-C |
|
1068 | # platform does not define VINTR so assume CTRL-C | |
1069 | char = chr(3) |
|
1069 | char = chr(3) | |
1070 | self.send (char) |
|
1070 | self.send (char) | |
1071 |
|
1071 | |||
1072 | def eof (self): |
|
1072 | def eof (self): | |
1073 |
|
1073 | |||
1074 | """This returns True if the EOF exception was ever raised. |
|
1074 | """This returns True if the EOF exception was ever raised. | |
1075 | """ |
|
1075 | """ | |
1076 |
|
1076 | |||
1077 | return self.flag_eof |
|
1077 | return self.flag_eof | |
1078 |
|
1078 | |||
1079 | def terminate(self, force=False): |
|
1079 | def terminate(self, force=False): | |
1080 |
|
1080 | |||
1081 | """This forces a child process to terminate. It starts nicely with |
|
1081 | """This forces a child process to terminate. It starts nicely with | |
1082 | SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This |
|
1082 | SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This | |
1083 | returns True if the child was terminated. This returns False if the |
|
1083 | returns True if the child was terminated. This returns False if the | |
1084 | child could not be terminated. """ |
|
1084 | child could not be terminated. """ | |
1085 |
|
1085 | |||
1086 | if not self.isalive(): |
|
1086 | if not self.isalive(): | |
1087 | return True |
|
1087 | return True | |
1088 | try: |
|
1088 | try: | |
1089 | self.kill(signal.SIGHUP) |
|
1089 | self.kill(signal.SIGHUP) | |
1090 | time.sleep(self.delayafterterminate) |
|
1090 | time.sleep(self.delayafterterminate) | |
1091 | if not self.isalive(): |
|
1091 | if not self.isalive(): | |
1092 | return True |
|
1092 | return True | |
1093 | self.kill(signal.SIGCONT) |
|
1093 | self.kill(signal.SIGCONT) | |
1094 | time.sleep(self.delayafterterminate) |
|
1094 | time.sleep(self.delayafterterminate) | |
1095 | if not self.isalive(): |
|
1095 | if not self.isalive(): | |
1096 | return True |
|
1096 | return True | |
1097 | self.kill(signal.SIGINT) |
|
1097 | self.kill(signal.SIGINT) | |
1098 | time.sleep(self.delayafterterminate) |
|
1098 | time.sleep(self.delayafterterminate) | |
1099 | if not self.isalive(): |
|
1099 | if not self.isalive(): | |
1100 | return True |
|
1100 | return True | |
1101 | if force: |
|
1101 | if force: | |
1102 | self.kill(signal.SIGKILL) |
|
1102 | self.kill(signal.SIGKILL) | |
1103 | time.sleep(self.delayafterterminate) |
|
1103 | time.sleep(self.delayafterterminate) | |
1104 | if not self.isalive(): |
|
1104 | if not self.isalive(): | |
1105 | return True |
|
1105 | return True | |
1106 | else: |
|
1106 | else: | |
1107 | return False |
|
1107 | return False | |
1108 | return False |
|
1108 | return False | |
1109 | except OSError as e: |
|
1109 | except OSError as e: | |
1110 | # I think there are kernel timing issues that sometimes cause |
|
1110 | # I think there are kernel timing issues that sometimes cause | |
1111 | # this to happen. I think isalive() reports True, but the |
|
1111 | # this to happen. I think isalive() reports True, but the | |
1112 | # process is dead to the kernel. |
|
1112 | # process is dead to the kernel. | |
1113 | # Make one last attempt to see if the kernel is up to date. |
|
1113 | # Make one last attempt to see if the kernel is up to date. | |
1114 | time.sleep(self.delayafterterminate) |
|
1114 | time.sleep(self.delayafterterminate) | |
1115 | if not self.isalive(): |
|
1115 | if not self.isalive(): | |
1116 | return True |
|
1116 | return True | |
1117 | else: |
|
1117 | else: | |
1118 | return False |
|
1118 | return False | |
1119 |
|
1119 | |||
1120 | def wait(self): |
|
1120 | def wait(self): | |
1121 |
|
1121 | |||
1122 | """This waits until the child exits. This is a blocking call. This will |
|
1122 | """This waits until the child exits. This is a blocking call. This will | |
1123 | not read any data from the child, so this will block forever if the |
|
1123 | not read any data from the child, so this will block forever if the | |
1124 | child has unread output and has terminated. In other words, the child |
|
1124 | child has unread output and has terminated. In other words, the child | |
1125 | may have printed output then called exit(); but, technically, the child |
|
1125 | may have printed output then called exit(); but, technically, the child | |
1126 | is still alive until its output is read. """ |
|
1126 | is still alive until its output is read. """ | |
1127 |
|
1127 | |||
1128 | if self.isalive(): |
|
1128 | if self.isalive(): | |
1129 | pid, status = os.waitpid(self.pid, 0) |
|
1129 | pid, status = os.waitpid(self.pid, 0) | |
1130 | else: |
|
1130 | else: | |
1131 | raise ExceptionPexpect ('Cannot wait for dead child process.') |
|
1131 | raise ExceptionPexpect ('Cannot wait for dead child process.') | |
1132 | self.exitstatus = os.WEXITSTATUS(status) |
|
1132 | self.exitstatus = os.WEXITSTATUS(status) | |
1133 | if os.WIFEXITED (status): |
|
1133 | if os.WIFEXITED (status): | |
1134 | self.status = status |
|
1134 | self.status = status | |
1135 | self.exitstatus = os.WEXITSTATUS(status) |
|
1135 | self.exitstatus = os.WEXITSTATUS(status) | |
1136 | self.signalstatus = None |
|
1136 | self.signalstatus = None | |
1137 | self.terminated = True |
|
1137 | self.terminated = True | |
1138 | elif os.WIFSIGNALED (status): |
|
1138 | elif os.WIFSIGNALED (status): | |
1139 | self.status = status |
|
1139 | self.status = status | |
1140 | self.exitstatus = None |
|
1140 | self.exitstatus = None | |
1141 | self.signalstatus = os.WTERMSIG(status) |
|
1141 | self.signalstatus = os.WTERMSIG(status) | |
1142 | self.terminated = True |
|
1142 | self.terminated = True | |
1143 | elif os.WIFSTOPPED (status): |
|
1143 | elif os.WIFSTOPPED (status): | |
1144 | raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?') |
|
1144 | raise ExceptionPexpect ('Wait was called for a child process that is stopped. This is not supported. Is some other process attempting job control with our child pid?') | |
1145 | return self.exitstatus |
|
1145 | return self.exitstatus | |
1146 |
|
1146 | |||
1147 | def isalive(self): |
|
1147 | def isalive(self): | |
1148 |
|
1148 | |||
1149 | """This tests if the child process is running or not. This is |
|
1149 | """This tests if the child process is running or not. This is | |
1150 | non-blocking. If the child was terminated then this will read the |
|
1150 | non-blocking. If the child was terminated then this will read the | |
1151 | exitstatus or signalstatus of the child. This returns True if the child |
|
1151 | exitstatus or signalstatus of the child. This returns True if the child | |
1152 | process appears to be running or False if not. It can take literally |
|
1152 | process appears to be running or False if not. It can take literally | |
1153 | SECONDS for Solaris to return the right status. """ |
|
1153 | SECONDS for Solaris to return the right status. """ | |
1154 |
|
1154 | |||
1155 | if self.terminated: |
|
1155 | if self.terminated: | |
1156 | return False |
|
1156 | return False | |
1157 |
|
1157 | |||
1158 | if self.flag_eof: |
|
1158 | if self.flag_eof: | |
1159 | # This is for Linux, which requires the blocking form of waitpid to get |
|
1159 | # This is for Linux, which requires the blocking form of waitpid to get | |
1160 | # status of a defunct process. This is super-lame. The flag_eof would have |
|
1160 | # status of a defunct process. This is super-lame. The flag_eof would have | |
1161 | # been set in read_nonblocking(), so this should be safe. |
|
1161 | # been set in read_nonblocking(), so this should be safe. | |
1162 | waitpid_options = 0 |
|
1162 | waitpid_options = 0 | |
1163 | else: |
|
1163 | else: | |
1164 | waitpid_options = os.WNOHANG |
|
1164 | waitpid_options = os.WNOHANG | |
1165 |
|
1165 | |||
1166 | try: |
|
1166 | try: | |
1167 | pid, status = os.waitpid(self.pid, waitpid_options) |
|
1167 | pid, status = os.waitpid(self.pid, waitpid_options) | |
1168 | except OSError as e: # No child processes |
|
1168 | except OSError as e: # No child processes | |
1169 | if e.errno == errno.ECHILD: |
|
1169 | if e.errno == errno.ECHILD: | |
1170 | raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') |
|
1170 | raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') | |
1171 | else: |
|
1171 | else: | |
1172 | raise e |
|
1172 | raise e | |
1173 |
|
1173 | |||
1174 | # I have to do this twice for Solaris. I can't even believe that I figured this out... |
|
1174 | # I have to do this twice for Solaris. I can't even believe that I figured this out... | |
1175 | # If waitpid() returns 0 it means that no child process wishes to |
|
1175 | # If waitpid() returns 0 it means that no child process wishes to | |
1176 | # report, and the value of status is undefined. |
|
1176 | # report, and the value of status is undefined. | |
1177 | if pid == 0: |
|
1177 | if pid == 0: | |
1178 | try: |
|
1178 | try: | |
1179 | pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris! |
|
1179 | pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris! | |
1180 | except OSError as e: # This should never happen... |
|
1180 | except OSError as e: # This should never happen... | |
1181 | if e[0] == errno.ECHILD: |
|
1181 | if e[0] == errno.ECHILD: | |
1182 | raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?') |
|
1182 | raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?') | |
1183 | else: |
|
1183 | else: | |
1184 | raise e |
|
1184 | raise e | |
1185 |
|
1185 | |||
1186 | # If pid is still 0 after two calls to waitpid() then |
|
1186 | # If pid is still 0 after two calls to waitpid() then | |
1187 | # the process really is alive. This seems to work on all platforms, except |
|
1187 | # the process really is alive. This seems to work on all platforms, except | |
1188 | # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking |
|
1188 | # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking | |
1189 | # take care of this situation (unfortunately, this requires waiting through the timeout). |
|
1189 | # take care of this situation (unfortunately, this requires waiting through the timeout). | |
1190 | if pid == 0: |
|
1190 | if pid == 0: | |
1191 | return True |
|
1191 | return True | |
1192 |
|
1192 | |||
1193 | if pid == 0: |
|
1193 | if pid == 0: | |
1194 | return True |
|
1194 | return True | |
1195 |
|
1195 | |||
1196 | if os.WIFEXITED (status): |
|
1196 | if os.WIFEXITED (status): | |
1197 | self.status = status |
|
1197 | self.status = status | |
1198 | self.exitstatus = os.WEXITSTATUS(status) |
|
1198 | self.exitstatus = os.WEXITSTATUS(status) | |
1199 | self.signalstatus = None |
|
1199 | self.signalstatus = None | |
1200 | self.terminated = True |
|
1200 | self.terminated = True | |
1201 | elif os.WIFSIGNALED (status): |
|
1201 | elif os.WIFSIGNALED (status): | |
1202 | self.status = status |
|
1202 | self.status = status | |
1203 | self.exitstatus = None |
|
1203 | self.exitstatus = None | |
1204 | self.signalstatus = os.WTERMSIG(status) |
|
1204 | self.signalstatus = os.WTERMSIG(status) | |
1205 | self.terminated = True |
|
1205 | self.terminated = True | |
1206 | elif os.WIFSTOPPED (status): |
|
1206 | elif os.WIFSTOPPED (status): | |
1207 | raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?') |
|
1207 | raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?') | |
1208 | return False |
|
1208 | return False | |
1209 |
|
1209 | |||
1210 | def kill(self, sig): |
|
1210 | def kill(self, sig): | |
1211 |
|
1211 | |||
1212 | """This sends the given signal to the child application. In keeping |
|
1212 | """This sends the given signal to the child application. In keeping | |
1213 | with UNIX tradition it has a misleading name. It does not necessarily |
|
1213 | with UNIX tradition it has a misleading name. It does not necessarily | |
1214 | kill the child unless you send the right signal. """ |
|
1214 | kill the child unless you send the right signal. """ | |
1215 |
|
1215 | |||
1216 | # Same as os.kill, but the pid is given for you. |
|
1216 | # Same as os.kill, but the pid is given for you. | |
1217 | if self.isalive(): |
|
1217 | if self.isalive(): | |
1218 | os.kill(self.pid, sig) |
|
1218 | os.kill(self.pid, sig) | |
1219 |
|
1219 | |||
1220 | def compile_pattern_list(self, patterns): |
|
1220 | def compile_pattern_list(self, patterns): | |
1221 |
|
1221 | |||
1222 | """This compiles a pattern-string or a list of pattern-strings. |
|
1222 | """This compiles a pattern-string or a list of pattern-strings. | |
1223 | Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of |
|
1223 | Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of | |
1224 | those. Patterns may also be None which results in an empty list (you |
|
1224 | those. Patterns may also be None which results in an empty list (you | |
1225 | might do this if waiting for an EOF or TIMEOUT condition without |
|
1225 | might do this if waiting for an EOF or TIMEOUT condition without | |
1226 | expecting any pattern). |
|
1226 | expecting any pattern). | |
1227 |
|
1227 | |||
1228 | This is used by expect() when calling expect_list(). Thus expect() is |
|
1228 | This is used by expect() when calling expect_list(). Thus expect() is | |
1229 | nothing more than:: |
|
1229 | nothing more than:: | |
1230 |
|
1230 | |||
1231 | cpl = self.compile_pattern_list(pl) |
|
1231 | cpl = self.compile_pattern_list(pl) | |
1232 | return self.expect_list(cpl, timeout) |
|
1232 | return self.expect_list(cpl, timeout) | |
1233 |
|
1233 | |||
1234 | If you are using expect() within a loop it may be more |
|
1234 | If you are using expect() within a loop it may be more | |
1235 | efficient to compile the patterns first and then call expect_list(). |
|
1235 | efficient to compile the patterns first and then call expect_list(). | |
1236 | This avoid calls in a loop to compile_pattern_list():: |
|
1236 | This avoid calls in a loop to compile_pattern_list():: | |
1237 |
|
1237 | |||
1238 | cpl = self.compile_pattern_list(my_pattern) |
|
1238 | cpl = self.compile_pattern_list(my_pattern) | |
1239 | while some_condition: |
|
1239 | while some_condition: | |
1240 | ... |
|
1240 | ... | |
1241 | i = self.expect_list(clp, timeout) |
|
1241 | i = self.expect_list(clp, timeout) | |
1242 | ... |
|
1242 | ... | |
1243 | """ |
|
1243 | """ | |
1244 |
|
1244 | |||
1245 | if patterns is None: |
|
1245 | if patterns is None: | |
1246 | return [] |
|
1246 | return [] | |
1247 | if not isinstance(patterns, list): |
|
1247 | if not isinstance(patterns, list): | |
1248 | patterns = [patterns] |
|
1248 | patterns = [patterns] | |
1249 |
|
1249 | |||
1250 | compile_flags = re.DOTALL # Allow dot to match \n |
|
1250 | compile_flags = re.DOTALL # Allow dot to match \n | |
1251 | if self.ignorecase: |
|
1251 | if self.ignorecase: | |
1252 | compile_flags = compile_flags | re.IGNORECASE |
|
1252 | compile_flags = compile_flags | re.IGNORECASE | |
1253 | compiled_pattern_list = [] |
|
1253 | compiled_pattern_list = [] | |
1254 | for p in patterns: |
|
1254 | for p in patterns: | |
1255 | if isinstance(p, (bytes, unicode)): |
|
1255 | if isinstance(p, (bytes, unicode)): | |
1256 | p = self._cast_buffer_type(p) |
|
1256 | p = self._cast_buffer_type(p) | |
1257 | compiled_pattern_list.append(re.compile(p, compile_flags)) |
|
1257 | compiled_pattern_list.append(re.compile(p, compile_flags)) | |
1258 | elif p is EOF: |
|
1258 | elif p is EOF: | |
1259 | compiled_pattern_list.append(EOF) |
|
1259 | compiled_pattern_list.append(EOF) | |
1260 | elif p is TIMEOUT: |
|
1260 | elif p is TIMEOUT: | |
1261 | compiled_pattern_list.append(TIMEOUT) |
|
1261 | compiled_pattern_list.append(TIMEOUT) | |
1262 | elif type(p) is re_type: |
|
1262 | elif type(p) is re_type: | |
1263 | p = self._prepare_regex_pattern(p) |
|
1263 | p = self._prepare_regex_pattern(p) | |
1264 | compiled_pattern_list.append(p) |
|
1264 | compiled_pattern_list.append(p) | |
1265 | else: |
|
1265 | else: | |
1266 | raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) |
|
1266 | raise TypeError ('Argument must be one of StringTypes, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) | |
1267 |
|
1267 | |||
1268 | return compiled_pattern_list |
|
1268 | return compiled_pattern_list | |
1269 |
|
1269 | |||
1270 | def _prepare_regex_pattern(self, p): |
|
1270 | def _prepare_regex_pattern(self, p): | |
1271 | "Recompile unicode regexes as bytes regexes. Overridden in subclass." |
|
1271 | "Recompile unicode regexes as bytes regexes. Overridden in subclass." | |
1272 | if isinstance(p.pattern, unicode): |
|
1272 | if isinstance(p.pattern, unicode): | |
1273 | p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) |
|
1273 | p = re.compile(p.pattern.encode('utf-8'), p.flags &~ re.UNICODE) | |
1274 | return p |
|
1274 | return p | |
1275 |
|
1275 | |||
1276 | def expect(self, pattern, timeout = -1, searchwindowsize=-1): |
|
1276 | def expect(self, pattern, timeout = -1, searchwindowsize=-1): | |
1277 |
|
1277 | |||
1278 | """This seeks through the stream until a pattern is matched. The |
|
1278 | """This seeks through the stream until a pattern is matched. The | |
1279 | pattern is overloaded and may take several types. The pattern can be a |
|
1279 | pattern is overloaded and may take several types. The pattern can be a | |
1280 | StringType, EOF, a compiled re, or a list of any of those types. |
|
1280 | StringType, EOF, a compiled re, or a list of any of those types. | |
1281 | Strings will be compiled to re types. This returns the index into the |
|
1281 | Strings will be compiled to re types. This returns the index into the | |
1282 | pattern list. If the pattern was not a list this returns index 0 on a |
|
1282 | pattern list. If the pattern was not a list this returns index 0 on a | |
1283 | successful match. This may raise exceptions for EOF or TIMEOUT. To |
|
1283 | successful match. This may raise exceptions for EOF or TIMEOUT. To | |
1284 | avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern |
|
1284 | avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern | |
1285 | list. That will cause expect to match an EOF or TIMEOUT condition |
|
1285 | list. That will cause expect to match an EOF or TIMEOUT condition | |
1286 | instead of raising an exception. |
|
1286 | instead of raising an exception. | |
1287 |
|
1287 | |||
1288 | If you pass a list of patterns and more than one matches, the first match |
|
1288 | If you pass a list of patterns and more than one matches, the first match | |
1289 | in the stream is chosen. If more than one pattern matches at that point, |
|
1289 | in the stream is chosen. If more than one pattern matches at that point, | |
1290 | the leftmost in the pattern list is chosen. For example:: |
|
1290 | the leftmost in the pattern list is chosen. For example:: | |
1291 |
|
1291 | |||
1292 | # the input is 'foobar' |
|
1292 | # the input is 'foobar' | |
1293 | index = p.expect (['bar', 'foo', 'foobar']) |
|
1293 | index = p.expect (['bar', 'foo', 'foobar']) | |
1294 | # returns 1 ('foo') even though 'foobar' is a "better" match |
|
1294 | # returns 1 ('foo') even though 'foobar' is a "better" match | |
1295 |
|
1295 | |||
1296 | Please note, however, that buffering can affect this behavior, since |
|
1296 | Please note, however, that buffering can affect this behavior, since | |
1297 | input arrives in unpredictable chunks. For example:: |
|
1297 | input arrives in unpredictable chunks. For example:: | |
1298 |
|
1298 | |||
1299 | # the input is 'foobar' |
|
1299 | # the input is 'foobar' | |
1300 | index = p.expect (['foobar', 'foo']) |
|
1300 | index = p.expect (['foobar', 'foo']) | |
1301 | # returns 0 ('foobar') if all input is available at once, |
|
1301 | # returns 0 ('foobar') if all input is available at once, | |
1302 | # but returs 1 ('foo') if parts of the final 'bar' arrive late |
|
1302 | # but returs 1 ('foo') if parts of the final 'bar' arrive late | |
1303 |
|
1303 | |||
1304 | After a match is found the instance attributes 'before', 'after' and |
|
1304 | After a match is found the instance attributes 'before', 'after' and | |
1305 | 'match' will be set. You can see all the data read before the match in |
|
1305 | 'match' will be set. You can see all the data read before the match in | |
1306 | 'before'. You can see the data that was matched in 'after'. The |
|
1306 | 'before'. You can see the data that was matched in 'after'. The | |
1307 | re.MatchObject used in the re match will be in 'match'. If an error |
|
1307 | re.MatchObject used in the re match will be in 'match'. If an error | |
1308 | occurred then 'before' will be set to all the data read so far and |
|
1308 | occurred then 'before' will be set to all the data read so far and | |
1309 | 'after' and 'match' will be None. |
|
1309 | 'after' and 'match' will be None. | |
1310 |
|
1310 | |||
1311 | If timeout is -1 then timeout will be set to the self.timeout value. |
|
1311 | If timeout is -1 then timeout will be set to the self.timeout value. | |
1312 |
|
1312 | |||
1313 | A list entry may be EOF or TIMEOUT instead of a string. This will |
|
1313 | A list entry may be EOF or TIMEOUT instead of a string. This will | |
1314 | catch these exceptions and return the index of the list entry instead |
|
1314 | catch these exceptions and return the index of the list entry instead | |
1315 | of raising the exception. The attribute 'after' will be set to the |
|
1315 | of raising the exception. The attribute 'after' will be set to the | |
1316 | exception type. The attribute 'match' will be None. This allows you to |
|
1316 | exception type. The attribute 'match' will be None. This allows you to | |
1317 | write code like this:: |
|
1317 | write code like this:: | |
1318 |
|
1318 | |||
1319 | index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) |
|
1319 | index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) | |
1320 | if index == 0: |
|
1320 | if index == 0: | |
1321 | do_something() |
|
1321 | do_something() | |
1322 | elif index == 1: |
|
1322 | elif index == 1: | |
1323 | do_something_else() |
|
1323 | do_something_else() | |
1324 | elif index == 2: |
|
1324 | elif index == 2: | |
1325 | do_some_other_thing() |
|
1325 | do_some_other_thing() | |
1326 | elif index == 3: |
|
1326 | elif index == 3: | |
1327 | do_something_completely_different() |
|
1327 | do_something_completely_different() | |
1328 |
|
1328 | |||
1329 | instead of code like this:: |
|
1329 | instead of code like this:: | |
1330 |
|
1330 | |||
1331 | try: |
|
1331 | try: | |
1332 | index = p.expect (['good', 'bad']) |
|
1332 | index = p.expect (['good', 'bad']) | |
1333 | if index == 0: |
|
1333 | if index == 0: | |
1334 | do_something() |
|
1334 | do_something() | |
1335 | elif index == 1: |
|
1335 | elif index == 1: | |
1336 | do_something_else() |
|
1336 | do_something_else() | |
1337 | except EOF: |
|
1337 | except EOF: | |
1338 | do_some_other_thing() |
|
1338 | do_some_other_thing() | |
1339 | except TIMEOUT: |
|
1339 | except TIMEOUT: | |
1340 | do_something_completely_different() |
|
1340 | do_something_completely_different() | |
1341 |
|
1341 | |||
1342 | These two forms are equivalent. It all depends on what you want. You |
|
1342 | These two forms are equivalent. It all depends on what you want. You | |
1343 | can also just expect the EOF if you are waiting for all output of a |
|
1343 | can also just expect the EOF if you are waiting for all output of a | |
1344 | child to finish. For example:: |
|
1344 | child to finish. For example:: | |
1345 |
|
1345 | |||
1346 | p = pexpect.spawn('/bin/ls') |
|
1346 | p = pexpect.spawn('/bin/ls') | |
1347 | p.expect (pexpect.EOF) |
|
1347 | p.expect (pexpect.EOF) | |
1348 | print p.before |
|
1348 | print p.before | |
1349 |
|
1349 | |||
1350 | If you are trying to optimize for speed then see expect_list(). |
|
1350 | If you are trying to optimize for speed then see expect_list(). | |
1351 | """ |
|
1351 | """ | |
1352 |
|
1352 | |||
1353 | compiled_pattern_list = self.compile_pattern_list(pattern) |
|
1353 | compiled_pattern_list = self.compile_pattern_list(pattern) | |
1354 | return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) |
|
1354 | return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) | |
1355 |
|
1355 | |||
1356 | def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): |
|
1356 | def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): | |
1357 |
|
1357 | |||
1358 | """This takes a list of compiled regular expressions and returns the |
|
1358 | """This takes a list of compiled regular expressions and returns the | |
1359 | index into the pattern_list that matched the child output. The list may |
|
1359 | index into the pattern_list that matched the child output. The list may | |
1360 | also contain EOF or TIMEOUT (which are not compiled regular |
|
1360 | also contain EOF or TIMEOUT (which are not compiled regular | |
1361 | expressions). This method is similar to the expect() method except that |
|
1361 | expressions). This method is similar to the expect() method except that | |
1362 | expect_list() does not recompile the pattern list on every call. This |
|
1362 | expect_list() does not recompile the pattern list on every call. This | |
1363 | may help if you are trying to optimize for speed, otherwise just use |
|
1363 | may help if you are trying to optimize for speed, otherwise just use | |
1364 | the expect() method. This is called by expect(). If timeout==-1 then |
|
1364 | the expect() method. This is called by expect(). If timeout==-1 then | |
1365 | the self.timeout value is used. If searchwindowsize==-1 then the |
|
1365 | the self.timeout value is used. If searchwindowsize==-1 then the | |
1366 | self.searchwindowsize value is used. """ |
|
1366 | self.searchwindowsize value is used. """ | |
1367 |
|
1367 | |||
1368 | return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize) |
|
1368 | return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize) | |
1369 |
|
1369 | |||
1370 | def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): |
|
1370 | def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1): | |
1371 |
|
1371 | |||
1372 | """This is similar to expect(), but uses plain string matching instead |
|
1372 | """This is similar to expect(), but uses plain string matching instead | |
1373 | of compiled regular expressions in 'pattern_list'. The 'pattern_list' |
|
1373 | of compiled regular expressions in 'pattern_list'. The 'pattern_list' | |
1374 | may be a string; a list or other sequence of strings; or TIMEOUT and |
|
1374 | may be a string; a list or other sequence of strings; or TIMEOUT and | |
1375 | EOF. |
|
1375 | EOF. | |
1376 |
|
1376 | |||
1377 | This call might be faster than expect() for two reasons: string |
|
1377 | This call might be faster than expect() for two reasons: string | |
1378 | searching is faster than RE matching and it is possible to limit the |
|
1378 | searching is faster than RE matching and it is possible to limit the | |
1379 | search to just the end of the input buffer. |
|
1379 | search to just the end of the input buffer. | |
1380 |
|
1380 | |||
1381 | This method is also useful when you don't want to have to worry about |
|
1381 | This method is also useful when you don't want to have to worry about | |
1382 | escaping regular expression characters that you want to match.""" |
|
1382 | escaping regular expression characters that you want to match.""" | |
1383 |
|
1383 | |||
1384 | if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): |
|
1384 | if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF): | |
1385 | pattern_list = [pattern_list] |
|
1385 | pattern_list = [pattern_list] | |
1386 | return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) |
|
1386 | return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) | |
1387 |
|
1387 | |||
1388 | def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): |
|
1388 | def expect_loop(self, searcher, timeout = -1, searchwindowsize = -1): | |
1389 |
|
1389 | |||
1390 | """This is the common loop used inside expect. The 'searcher' should be |
|
1390 | """This is the common loop used inside expect. The 'searcher' should be | |
1391 | an instance of searcher_re or searcher_string, which describes how and what |
|
1391 | an instance of searcher_re or searcher_string, which describes how and what | |
1392 | to search for in the input. |
|
1392 | to search for in the input. | |
1393 |
|
1393 | |||
1394 | See expect() for other arguments, return value and exceptions. """ |
|
1394 | See expect() for other arguments, return value and exceptions. """ | |
1395 |
|
1395 | |||
1396 | self.searcher = searcher |
|
1396 | self.searcher = searcher | |
1397 |
|
1397 | |||
1398 | if timeout == -1: |
|
1398 | if timeout == -1: | |
1399 | timeout = self.timeout |
|
1399 | timeout = self.timeout | |
1400 | if timeout is not None: |
|
1400 | if timeout is not None: | |
1401 | end_time = time.time() + timeout |
|
1401 | end_time = time.time() + timeout | |
1402 | if searchwindowsize == -1: |
|
1402 | if searchwindowsize == -1: | |
1403 | searchwindowsize = self.searchwindowsize |
|
1403 | searchwindowsize = self.searchwindowsize | |
1404 |
|
1404 | |||
1405 | try: |
|
1405 | try: | |
1406 | incoming = self.buffer |
|
1406 | incoming = self.buffer | |
1407 | freshlen = len(incoming) |
|
1407 | freshlen = len(incoming) | |
1408 | while True: # Keep reading until exception or return. |
|
1408 | while True: # Keep reading until exception or return. | |
1409 | index = searcher.search(incoming, freshlen, searchwindowsize) |
|
1409 | index = searcher.search(incoming, freshlen, searchwindowsize) | |
1410 | if index >= 0: |
|
1410 | if index >= 0: | |
1411 | self.buffer = incoming[searcher.end : ] |
|
1411 | self.buffer = incoming[searcher.end : ] | |
1412 | self.before = incoming[ : searcher.start] |
|
1412 | self.before = incoming[ : searcher.start] | |
1413 | self.after = incoming[searcher.start : searcher.end] |
|
1413 | self.after = incoming[searcher.start : searcher.end] | |
1414 | self.match = searcher.match |
|
1414 | self.match = searcher.match | |
1415 | self.match_index = index |
|
1415 | self.match_index = index | |
1416 | return self.match_index |
|
1416 | return self.match_index | |
1417 | # No match at this point |
|
1417 | # No match at this point | |
1418 | if timeout is not None and timeout < 0: |
|
1418 | if timeout is not None and timeout < 0: | |
1419 | raise TIMEOUT ('Timeout exceeded in expect_any().') |
|
1419 | raise TIMEOUT ('Timeout exceeded in expect_any().') | |
1420 | # Still have time left, so read more data |
|
1420 | # Still have time left, so read more data | |
1421 | c = self.read_nonblocking (self.maxread, timeout) |
|
1421 | c = self.read_nonblocking (self.maxread, timeout) | |
1422 | freshlen = len(c) |
|
1422 | freshlen = len(c) | |
1423 | time.sleep (0.0001) |
|
1423 | time.sleep (0.0001) | |
1424 | incoming = incoming + c |
|
1424 | incoming = incoming + c | |
1425 | if timeout is not None: |
|
1425 | if timeout is not None: | |
1426 | timeout = end_time - time.time() |
|
1426 | timeout = end_time - time.time() | |
1427 | except EOF as e: |
|
1427 | except EOF as e: | |
1428 | self.buffer = self._empty_buffer |
|
1428 | self.buffer = self._empty_buffer | |
1429 | self.before = incoming |
|
1429 | self.before = incoming | |
1430 | self.after = EOF |
|
1430 | self.after = EOF | |
1431 | index = searcher.eof_index |
|
1431 | index = searcher.eof_index | |
1432 | if index >= 0: |
|
1432 | if index >= 0: | |
1433 | self.match = EOF |
|
1433 | self.match = EOF | |
1434 | self.match_index = index |
|
1434 | self.match_index = index | |
1435 | return self.match_index |
|
1435 | return self.match_index | |
1436 | else: |
|
1436 | else: | |
1437 | self.match = None |
|
1437 | self.match = None | |
1438 | self.match_index = None |
|
1438 | self.match_index = None | |
1439 | raise EOF (str(e) + '\n' + str(self)) |
|
1439 | raise EOF (str(e) + '\n' + str(self)) | |
1440 | except TIMEOUT as e: |
|
1440 | except TIMEOUT as e: | |
1441 | self.buffer = incoming |
|
1441 | self.buffer = incoming | |
1442 | self.before = incoming |
|
1442 | self.before = incoming | |
1443 | self.after = TIMEOUT |
|
1443 | self.after = TIMEOUT | |
1444 | index = searcher.timeout_index |
|
1444 | index = searcher.timeout_index | |
1445 | if index >= 0: |
|
1445 | if index >= 0: | |
1446 | self.match = TIMEOUT |
|
1446 | self.match = TIMEOUT | |
1447 | self.match_index = index |
|
1447 | self.match_index = index | |
1448 | return self.match_index |
|
1448 | return self.match_index | |
1449 | else: |
|
1449 | else: | |
1450 | self.match = None |
|
1450 | self.match = None | |
1451 | self.match_index = None |
|
1451 | self.match_index = None | |
1452 | raise TIMEOUT (str(e) + '\n' + str(self)) |
|
1452 | raise TIMEOUT (str(e) + '\n' + str(self)) | |
1453 | except: |
|
1453 | except: | |
1454 | self.before = incoming |
|
1454 | self.before = incoming | |
1455 | self.after = None |
|
1455 | self.after = None | |
1456 | self.match = None |
|
1456 | self.match = None | |
1457 | self.match_index = None |
|
1457 | self.match_index = None | |
1458 | raise |
|
1458 | raise | |
1459 |
|
1459 | |||
1460 | def getwinsize(self): |
|
1460 | def getwinsize(self): | |
1461 |
|
1461 | |||
1462 | """This returns the terminal window size of the child tty. The return |
|
1462 | """This returns the terminal window size of the child tty. The return | |
1463 | value is a tuple of (rows, cols). """ |
|
1463 | value is a tuple of (rows, cols). """ | |
1464 |
|
1464 | |||
1465 | TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) |
|
1465 | TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912L) | |
1466 | s = struct.pack('HHHH', 0, 0, 0, 0) |
|
1466 | s = struct.pack('HHHH', 0, 0, 0, 0) | |
1467 | x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) |
|
1467 | x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) | |
1468 | return struct.unpack('HHHH', x)[0:2] |
|
1468 | return struct.unpack('HHHH', x)[0:2] | |
1469 |
|
1469 | |||
1470 | def setwinsize(self, r, c): |
|
1470 | def setwinsize(self, r, c): | |
1471 |
|
1471 | |||
1472 | """This sets the terminal window size of the child tty. This will cause |
|
1472 | """This sets the terminal window size of the child tty. This will cause | |
1473 | a SIGWINCH signal to be sent to the child. This does not change the |
|
1473 | a SIGWINCH signal to be sent to the child. This does not change the | |
1474 | physical window size. It changes the size reported to TTY-aware |
|
1474 | physical window size. It changes the size reported to TTY-aware | |
1475 | applications like vi or curses -- applications that respond to the |
|
1475 | applications like vi or curses -- applications that respond to the | |
1476 | SIGWINCH signal. """ |
|
1476 | SIGWINCH signal. """ | |
1477 |
|
1477 | |||
1478 | # Check for buggy platforms. Some Python versions on some platforms |
|
1478 | # Check for buggy platforms. Some Python versions on some platforms | |
1479 | # (notably OSF1 Alpha and RedHat 7.1) truncate the value for |
|
1479 | # (notably OSF1 Alpha and RedHat 7.1) truncate the value for | |
1480 | # termios.TIOCSWINSZ. It is not clear why this happens. |
|
1480 | # termios.TIOCSWINSZ. It is not clear why this happens. | |
1481 | # These platforms don't seem to handle the signed int very well; |
|
1481 | # These platforms don't seem to handle the signed int very well; | |
1482 | # yet other platforms like OpenBSD have a large negative value for |
|
1482 | # yet other platforms like OpenBSD have a large negative value for | |
1483 | # TIOCSWINSZ and they don't have a truncate problem. |
|
1483 | # TIOCSWINSZ and they don't have a truncate problem. | |
1484 | # Newer versions of Linux have totally different values for TIOCSWINSZ. |
|
1484 | # Newer versions of Linux have totally different values for TIOCSWINSZ. | |
1485 | # Note that this fix is a hack. |
|
1485 | # Note that this fix is a hack. | |
1486 | TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) |
|
1486 | TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) | |
1487 | if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. |
|
1487 | if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. | |
1488 | TIOCSWINSZ = -2146929561 # Same bits, but with sign. |
|
1488 | TIOCSWINSZ = -2146929561 # Same bits, but with sign. | |
1489 | # Note, assume ws_xpixel and ws_ypixel are zero. |
|
1489 | # Note, assume ws_xpixel and ws_ypixel are zero. | |
1490 | s = struct.pack('HHHH', r, c, 0, 0) |
|
1490 | s = struct.pack('HHHH', r, c, 0, 0) | |
1491 | fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) |
|
1491 | fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) | |
1492 |
|
1492 | |||
1493 | def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None): |
|
1493 | def interact(self, escape_character = b'\x1d', input_filter = None, output_filter = None): | |
1494 |
|
1494 | |||
1495 | """This gives control of the child process to the interactive user (the |
|
1495 | """This gives control of the child process to the interactive user (the | |
1496 | human at the keyboard). Keystrokes are sent to the child process, and |
|
1496 | human at the keyboard). Keystrokes are sent to the child process, and | |
1497 | the stdout and stderr output of the child process is printed. This |
|
1497 | the stdout and stderr output of the child process is printed. This | |
1498 | simply echos the child stdout and child stderr to the real stdout and |
|
1498 | simply echos the child stdout and child stderr to the real stdout and | |
1499 | it echos the real stdin to the child stdin. When the user types the |
|
1499 | it echos the real stdin to the child stdin. When the user types the | |
1500 | escape_character this method will stop. The default for |
|
1500 | escape_character this method will stop. The default for | |
1501 | escape_character is ^]. This should not be confused with ASCII 27 -- |
|
1501 | escape_character is ^]. This should not be confused with ASCII 27 -- | |
1502 | the ESC character. ASCII 29 was chosen for historical merit because |
|
1502 | the ESC character. ASCII 29 was chosen for historical merit because | |
1503 | this is the character used by 'telnet' as the escape character. The |
|
1503 | this is the character used by 'telnet' as the escape character. The | |
1504 | escape_character will not be sent to the child process. |
|
1504 | escape_character will not be sent to the child process. | |
1505 |
|
1505 | |||
1506 | You may pass in optional input and output filter functions. These |
|
1506 | You may pass in optional input and output filter functions. These | |
1507 | functions should take a string and return a string. The output_filter |
|
1507 | functions should take a string and return a string. The output_filter | |
1508 | will be passed all the output from the child process. The input_filter |
|
1508 | will be passed all the output from the child process. The input_filter | |
1509 | will be passed all the keyboard input from the user. The input_filter |
|
1509 | will be passed all the keyboard input from the user. The input_filter | |
1510 | is run BEFORE the check for the escape_character. |
|
1510 | is run BEFORE the check for the escape_character. | |
1511 |
|
1511 | |||
1512 | Note that if you change the window size of the parent the SIGWINCH |
|
1512 | Note that if you change the window size of the parent the SIGWINCH | |
1513 | signal will not be passed through to the child. If you want the child |
|
1513 | signal will not be passed through to the child. If you want the child | |
1514 | window size to change when the parent's window size changes then do |
|
1514 | window size to change when the parent's window size changes then do | |
1515 | something like the following example:: |
|
1515 | something like the following example:: | |
1516 |
|
1516 | |||
1517 | import pexpect, struct, fcntl, termios, signal, sys |
|
1517 | import pexpect, struct, fcntl, termios, signal, sys | |
1518 | def sigwinch_passthrough (sig, data): |
|
1518 | def sigwinch_passthrough (sig, data): | |
1519 | s = struct.pack("HHHH", 0, 0, 0, 0) |
|
1519 | s = struct.pack("HHHH", 0, 0, 0, 0) | |
1520 | a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) |
|
1520 | a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) | |
1521 | global p |
|
1521 | global p | |
1522 | p.setwinsize(a[0],a[1]) |
|
1522 | p.setwinsize(a[0],a[1]) | |
1523 | p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. |
|
1523 | p = pexpect.spawn('/bin/bash') # Note this is global and used in sigwinch_passthrough. | |
1524 | signal.signal(signal.SIGWINCH, sigwinch_passthrough) |
|
1524 | signal.signal(signal.SIGWINCH, sigwinch_passthrough) | |
1525 | p.interact() |
|
1525 | p.interact() | |
1526 | """ |
|
1526 | """ | |
1527 |
|
1527 | |||
1528 | # Flush the buffer. |
|
1528 | # Flush the buffer. | |
1529 | if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding)) |
|
1529 | if PY3: self.stdout.write(_cast_unicode(self.buffer, self.encoding)) | |
1530 | else: self.stdout.write(self.buffer) |
|
1530 | else: self.stdout.write(self.buffer) | |
1531 | self.stdout.flush() |
|
1531 | self.stdout.flush() | |
1532 | self.buffer = self._empty_buffer |
|
1532 | self.buffer = self._empty_buffer | |
1533 | mode = tty.tcgetattr(self.STDIN_FILENO) |
|
1533 | mode = tty.tcgetattr(self.STDIN_FILENO) | |
1534 | tty.setraw(self.STDIN_FILENO) |
|
1534 | tty.setraw(self.STDIN_FILENO) | |
1535 | try: |
|
1535 | try: | |
1536 | self.__interact_copy(escape_character, input_filter, output_filter) |
|
1536 | self.__interact_copy(escape_character, input_filter, output_filter) | |
1537 | finally: |
|
1537 | finally: | |
1538 | tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode) |
|
1538 | tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode) | |
1539 |
|
1539 | |||
1540 | def __interact_writen(self, fd, data): |
|
1540 | def __interact_writen(self, fd, data): | |
1541 |
|
1541 | |||
1542 | """This is used by the interact() method. |
|
1542 | """This is used by the interact() method. | |
1543 | """ |
|
1543 | """ | |
1544 |
|
1544 | |||
1545 | while data != b'' and self.isalive(): |
|
1545 | while data != b'' and self.isalive(): | |
1546 | n = os.write(fd, data) |
|
1546 | n = os.write(fd, data) | |
1547 | data = data[n:] |
|
1547 | data = data[n:] | |
1548 |
|
1548 | |||
1549 | def __interact_read(self, fd): |
|
1549 | def __interact_read(self, fd): | |
1550 |
|
1550 | |||
1551 | """This is used by the interact() method. |
|
1551 | """This is used by the interact() method. | |
1552 | """ |
|
1552 | """ | |
1553 |
|
1553 | |||
1554 | return os.read(fd, 1000) |
|
1554 | return os.read(fd, 1000) | |
1555 |
|
1555 | |||
1556 | def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): |
|
1556 | def __interact_copy(self, escape_character = None, input_filter = None, output_filter = None): | |
1557 |
|
1557 | |||
1558 | """This is used by the interact() method. |
|
1558 | """This is used by the interact() method. | |
1559 | """ |
|
1559 | """ | |
1560 |
|
1560 | |||
1561 | while self.isalive(): |
|
1561 | while self.isalive(): | |
1562 | r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) |
|
1562 | r,w,e = self.__select([self.child_fd, self.STDIN_FILENO], [], []) | |
1563 | if self.child_fd in r: |
|
1563 | if self.child_fd in r: | |
1564 | data = self.__interact_read(self.child_fd) |
|
1564 | data = self.__interact_read(self.child_fd) | |
1565 | if output_filter: data = output_filter(data) |
|
1565 | if output_filter: data = output_filter(data) | |
1566 | if self.logfile is not None: |
|
1566 | if self.logfile is not None: | |
1567 | self.logfile.write (data) |
|
1567 | self.logfile.write (data) | |
1568 | self.logfile.flush() |
|
1568 | self.logfile.flush() | |
1569 | os.write(self.STDOUT_FILENO, data) |
|
1569 | os.write(self.STDOUT_FILENO, data) | |
1570 | if self.STDIN_FILENO in r: |
|
1570 | if self.STDIN_FILENO in r: | |
1571 | data = self.__interact_read(self.STDIN_FILENO) |
|
1571 | data = self.__interact_read(self.STDIN_FILENO) | |
1572 | if input_filter: data = input_filter(data) |
|
1572 | if input_filter: data = input_filter(data) | |
1573 | i = data.rfind(escape_character) |
|
1573 | i = data.rfind(escape_character) | |
1574 | if i != -1: |
|
1574 | if i != -1: | |
1575 | data = data[:i] |
|
1575 | data = data[:i] | |
1576 | self.__interact_writen(self.child_fd, data) |
|
1576 | self.__interact_writen(self.child_fd, data) | |
1577 | break |
|
1577 | break | |
1578 | self.__interact_writen(self.child_fd, data) |
|
1578 | self.__interact_writen(self.child_fd, data) | |
1579 |
|
1579 | |||
1580 | def __select (self, iwtd, owtd, ewtd, timeout=None): |
|
1580 | def __select (self, iwtd, owtd, ewtd, timeout=None): | |
1581 |
|
1581 | |||
1582 | """This is a wrapper around select.select() that ignores signals. If |
|
1582 | """This is a wrapper around select.select() that ignores signals. If | |
1583 | select.select raises a select.error exception and errno is an EINTR |
|
1583 | select.select raises a select.error exception and errno is an EINTR | |
1584 | error then it is ignored. Mainly this is used to ignore sigwinch |
|
1584 | error then it is ignored. Mainly this is used to ignore sigwinch | |
1585 | (terminal resize). """ |
|
1585 | (terminal resize). """ | |
1586 |
|
1586 | |||
1587 | # if select() is interrupted by a signal (errno==EINTR) then |
|
1587 | # if select() is interrupted by a signal (errno==EINTR) then | |
1588 | # we loop back and enter the select() again. |
|
1588 | # we loop back and enter the select() again. | |
1589 | if timeout is not None: |
|
1589 | if timeout is not None: | |
1590 | end_time = time.time() + timeout |
|
1590 | end_time = time.time() + timeout | |
1591 | while True: |
|
1591 | while True: | |
1592 | try: |
|
1592 | try: | |
1593 | return select.select (iwtd, owtd, ewtd, timeout) |
|
1593 | return select.select (iwtd, owtd, ewtd, timeout) | |
1594 | except select.error as e: |
|
1594 | except select.error as e: | |
1595 | if e.args[0] == errno.EINTR: |
|
1595 | if e.args[0] == errno.EINTR: | |
1596 | # if we loop back we have to subtract the amount of time we already waited. |
|
1596 | # if we loop back we have to subtract the amount of time we already waited. | |
1597 | if timeout is not None: |
|
1597 | if timeout is not None: | |
1598 | timeout = end_time - time.time() |
|
1598 | timeout = end_time - time.time() | |
1599 | if timeout < 0: |
|
1599 | if timeout < 0: | |
1600 | return ([],[],[]) |
|
1600 | return ([],[],[]) | |
1601 | else: # something else caused the select.error, so this really is an exception |
|
1601 | else: # something else caused the select.error, so this really is an exception | |
1602 | raise |
|
1602 | raise | |
1603 |
|
1603 | |||
1604 | class spawn(spawnb): |
|
1604 | class spawn(spawnb): | |
1605 | """This is the main class interface for Pexpect. Use this class to start |
|
1605 | """This is the main class interface for Pexpect. Use this class to start | |
1606 | and control child applications.""" |
|
1606 | and control child applications.""" | |
1607 |
|
1607 | |||
1608 | _buffer_type = unicode |
|
1608 | _buffer_type = unicode | |
1609 | def _cast_buffer_type(self, s): |
|
1609 | def _cast_buffer_type(self, s): | |
1610 | return _cast_unicode(s, self.encoding) |
|
1610 | return _cast_unicode(s, self.encoding) | |
1611 | _empty_buffer = u'' |
|
1611 | _empty_buffer = u'' | |
1612 | _pty_newline = u'\r\n' |
|
1612 | _pty_newline = u'\r\n' | |
1613 |
|
1613 | |||
1614 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, |
|
1614 | def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, | |
1615 | logfile=None, cwd=None, env=None, encoding='utf-8'): |
|
1615 | logfile=None, cwd=None, env=None, encoding='utf-8'): | |
1616 | super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread, |
|
1616 | super(spawn, self).__init__(command, args, timeout=timeout, maxread=maxread, | |
1617 | searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env) |
|
1617 | searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env) | |
1618 | self.encoding = encoding |
|
1618 | self.encoding = encoding | |
1619 |
|
1619 | |||
1620 | def _prepare_regex_pattern(self, p): |
|
1620 | def _prepare_regex_pattern(self, p): | |
1621 | "Recompile bytes regexes as unicode regexes." |
|
1621 | "Recompile bytes regexes as unicode regexes." | |
1622 | if isinstance(p.pattern, bytes): |
|
1622 | if isinstance(p.pattern, bytes): | |
1623 | p = re.compile(p.pattern.decode(self.encoding), p.flags) |
|
1623 | p = re.compile(p.pattern.decode(self.encoding), p.flags) | |
1624 | return p |
|
1624 | return p | |
1625 |
|
1625 | |||
1626 | def read_nonblocking(self, size=1, timeout=-1): |
|
1626 | def read_nonblocking(self, size=1, timeout=-1): | |
1627 | return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\ |
|
1627 | return super(spawn, self).read_nonblocking(size=size, timeout=timeout)\ | |
1628 | .decode(self.encoding) |
|
1628 | .decode(self.encoding) | |
1629 |
|
1629 | |||
1630 | read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__ |
|
1630 | read_nonblocking.__doc__ = spawnb.read_nonblocking.__doc__ | |
1631 |
|
1631 | |||
1632 |
|
1632 | |||
1633 | ############################################################################## |
|
1633 | ############################################################################## | |
1634 | # End of spawn class |
|
1634 | # End of spawn class | |
1635 | ############################################################################## |
|
1635 | ############################################################################## | |
1636 |
|
1636 | |||
1637 | class searcher_string (object): |
|
1637 | class searcher_string (object): | |
1638 |
|
1638 | |||
1639 | """This is a plain string search helper for the spawn.expect_any() method. |
|
1639 | """This is a plain string search helper for the spawn.expect_any() method. | |
1640 | This helper class is for speed. For more powerful regex patterns |
|
1640 | This helper class is for speed. For more powerful regex patterns | |
1641 | see the helper class, searcher_re. |
|
1641 | see the helper class, searcher_re. | |
1642 |
|
1642 | |||
1643 | Attributes: |
|
1643 | Attributes: | |
1644 |
|
1644 | |||
1645 | eof_index - index of EOF, or -1 |
|
1645 | eof_index - index of EOF, or -1 | |
1646 | timeout_index - index of TIMEOUT, or -1 |
|
1646 | timeout_index - index of TIMEOUT, or -1 | |
1647 |
|
1647 | |||
1648 | After a successful match by the search() method the following attributes |
|
1648 | After a successful match by the search() method the following attributes | |
1649 | are available: |
|
1649 | are available: | |
1650 |
|
1650 | |||
1651 | start - index into the buffer, first byte of match |
|
1651 | start - index into the buffer, first byte of match | |
1652 | end - index into the buffer, first byte after match |
|
1652 | end - index into the buffer, first byte after match | |
1653 | match - the matching string itself |
|
1653 | match - the matching string itself | |
1654 |
|
1654 | |||
1655 | """ |
|
1655 | """ | |
1656 |
|
1656 | |||
1657 | def __init__(self, strings): |
|
1657 | def __init__(self, strings): | |
1658 |
|
1658 | |||
1659 | """This creates an instance of searcher_string. This argument 'strings' |
|
1659 | """This creates an instance of searcher_string. This argument 'strings' | |
1660 | may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ |
|
1660 | may be a list; a sequence of strings; or the EOF or TIMEOUT types. """ | |
1661 |
|
1661 | |||
1662 | self.eof_index = -1 |
|
1662 | self.eof_index = -1 | |
1663 | self.timeout_index = -1 |
|
1663 | self.timeout_index = -1 | |
1664 | self._strings = [] |
|
1664 | self._strings = [] | |
1665 | for n, s in enumerate(strings): |
|
1665 | for n, s in enumerate(strings): | |
1666 | if s is EOF: |
|
1666 | if s is EOF: | |
1667 | self.eof_index = n |
|
1667 | self.eof_index = n | |
1668 | continue |
|
1668 | continue | |
1669 | if s is TIMEOUT: |
|
1669 | if s is TIMEOUT: | |
1670 | self.timeout_index = n |
|
1670 | self.timeout_index = n | |
1671 | continue |
|
1671 | continue | |
1672 | self._strings.append((n, s)) |
|
1672 | self._strings.append((n, s)) | |
1673 |
|
1673 | |||
1674 | def __str__(self): |
|
1674 | def __str__(self): | |
1675 |
|
1675 | |||
1676 | """This returns a human-readable string that represents the state of |
|
1676 | """This returns a human-readable string that represents the state of | |
1677 | the object.""" |
|
1677 | the object.""" | |
1678 |
|
1678 | |||
1679 | ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ] |
|
1679 | ss = [ (ns[0],' %d: "%s"' % ns) for ns in self._strings ] | |
1680 | ss.append((-1,'searcher_string:')) |
|
1680 | ss.append((-1,'searcher_string:')) | |
1681 | if self.eof_index >= 0: |
|
1681 | if self.eof_index >= 0: | |
1682 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) |
|
1682 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) | |
1683 | if self.timeout_index >= 0: |
|
1683 | if self.timeout_index >= 0: | |
1684 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) |
|
1684 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) | |
1685 | ss.sort() |
|
1685 | ss.sort() | |
1686 | return '\n'.join(a[1] for a in ss) |
|
1686 | return '\n'.join(a[1] for a in ss) | |
1687 |
|
1687 | |||
1688 | def search(self, buffer, freshlen, searchwindowsize=None): |
|
1688 | def search(self, buffer, freshlen, searchwindowsize=None): | |
1689 |
|
1689 | |||
1690 | """This searches 'buffer' for the first occurence of one of the search |
|
1690 | """This searches 'buffer' for the first occurence of one of the search | |
1691 | strings. 'freshlen' must indicate the number of bytes at the end of |
|
1691 | strings. 'freshlen' must indicate the number of bytes at the end of | |
1692 | 'buffer' which have not been searched before. It helps to avoid |
|
1692 | 'buffer' which have not been searched before. It helps to avoid | |
1693 | searching the same, possibly big, buffer over and over again. |
|
1693 | searching the same, possibly big, buffer over and over again. | |
1694 |
|
1694 | |||
1695 | See class spawn for the 'searchwindowsize' argument. |
|
1695 | See class spawn for the 'searchwindowsize' argument. | |
1696 |
|
1696 | |||
1697 | If there is a match this returns the index of that string, and sets |
|
1697 | If there is a match this returns the index of that string, and sets | |
1698 | 'start', 'end' and 'match'. Otherwise, this returns -1. """ |
|
1698 | 'start', 'end' and 'match'. Otherwise, this returns -1. """ | |
1699 |
|
1699 | |||
1700 | absurd_match = len(buffer) |
|
1700 | absurd_match = len(buffer) | |
1701 | first_match = absurd_match |
|
1701 | first_match = absurd_match | |
1702 |
|
1702 | |||
1703 | # 'freshlen' helps a lot here. Further optimizations could |
|
1703 | # 'freshlen' helps a lot here. Further optimizations could | |
1704 | # possibly include: |
|
1704 | # possibly include: | |
1705 | # |
|
1705 | # | |
1706 | # using something like the Boyer-Moore Fast String Searching |
|
1706 | # using something like the Boyer-Moore Fast String Searching | |
1707 | # Algorithm; pre-compiling the search through a list of |
|
1707 | # Algorithm; pre-compiling the search through a list of | |
1708 | # strings into something that can scan the input once to |
|
1708 | # strings into something that can scan the input once to | |
1709 | # search for all N strings; realize that if we search for |
|
1709 | # search for all N strings; realize that if we search for | |
1710 | # ['bar', 'baz'] and the input is '...foo' we need not bother |
|
1710 | # ['bar', 'baz'] and the input is '...foo' we need not bother | |
1711 | # rescanning until we've read three more bytes. |
|
1711 | # rescanning until we've read three more bytes. | |
1712 | # |
|
1712 | # | |
1713 | # Sadly, I don't know enough about this interesting topic. /grahn |
|
1713 | # Sadly, I don't know enough about this interesting topic. /grahn | |
1714 |
|
1714 | |||
1715 | for index, s in self._strings: |
|
1715 | for index, s in self._strings: | |
1716 | if searchwindowsize is None: |
|
1716 | if searchwindowsize is None: | |
1717 | # the match, if any, can only be in the fresh data, |
|
1717 | # the match, if any, can only be in the fresh data, | |
1718 | # or at the very end of the old data |
|
1718 | # or at the very end of the old data | |
1719 | offset = -(freshlen+len(s)) |
|
1719 | offset = -(freshlen+len(s)) | |
1720 | else: |
|
1720 | else: | |
1721 | # better obey searchwindowsize |
|
1721 | # better obey searchwindowsize | |
1722 | offset = -searchwindowsize |
|
1722 | offset = -searchwindowsize | |
1723 | n = buffer.find(s, offset) |
|
1723 | n = buffer.find(s, offset) | |
1724 | if n >= 0 and n < first_match: |
|
1724 | if n >= 0 and n < first_match: | |
1725 | first_match = n |
|
1725 | first_match = n | |
1726 | best_index, best_match = index, s |
|
1726 | best_index, best_match = index, s | |
1727 | if first_match == absurd_match: |
|
1727 | if first_match == absurd_match: | |
1728 | return -1 |
|
1728 | return -1 | |
1729 | self.match = best_match |
|
1729 | self.match = best_match | |
1730 | self.start = first_match |
|
1730 | self.start = first_match | |
1731 | self.end = self.start + len(self.match) |
|
1731 | self.end = self.start + len(self.match) | |
1732 | return best_index |
|
1732 | return best_index | |
1733 |
|
1733 | |||
1734 | class searcher_re (object): |
|
1734 | class searcher_re (object): | |
1735 |
|
1735 | |||
1736 | """This is regular expression string search helper for the |
|
1736 | """This is regular expression string search helper for the | |
1737 | spawn.expect_any() method. This helper class is for powerful |
|
1737 | spawn.expect_any() method. This helper class is for powerful | |
1738 | pattern matching. For speed, see the helper class, searcher_string. |
|
1738 | pattern matching. For speed, see the helper class, searcher_string. | |
1739 |
|
1739 | |||
1740 | Attributes: |
|
1740 | Attributes: | |
1741 |
|
1741 | |||
1742 | eof_index - index of EOF, or -1 |
|
1742 | eof_index - index of EOF, or -1 | |
1743 | timeout_index - index of TIMEOUT, or -1 |
|
1743 | timeout_index - index of TIMEOUT, or -1 | |
1744 |
|
1744 | |||
1745 | After a successful match by the search() method the following attributes |
|
1745 | After a successful match by the search() method the following attributes | |
1746 | are available: |
|
1746 | are available: | |
1747 |
|
1747 | |||
1748 | start - index into the buffer, first byte of match |
|
1748 | start - index into the buffer, first byte of match | |
1749 | end - index into the buffer, first byte after match |
|
1749 | end - index into the buffer, first byte after match | |
1750 | match - the re.match object returned by a succesful re.search |
|
1750 | match - the re.match object returned by a succesful re.search | |
1751 |
|
1751 | |||
1752 | """ |
|
1752 | """ | |
1753 |
|
1753 | |||
1754 | def __init__(self, patterns): |
|
1754 | def __init__(self, patterns): | |
1755 |
|
1755 | |||
1756 | """This creates an instance that searches for 'patterns' Where |
|
1756 | """This creates an instance that searches for 'patterns' Where | |
1757 | 'patterns' may be a list or other sequence of compiled regular |
|
1757 | 'patterns' may be a list or other sequence of compiled regular | |
1758 | expressions, or the EOF or TIMEOUT types.""" |
|
1758 | expressions, or the EOF or TIMEOUT types.""" | |
1759 |
|
1759 | |||
1760 | self.eof_index = -1 |
|
1760 | self.eof_index = -1 | |
1761 | self.timeout_index = -1 |
|
1761 | self.timeout_index = -1 | |
1762 | self._searches = [] |
|
1762 | self._searches = [] | |
1763 | for n, s in enumerate(patterns): |
|
1763 | for n, s in enumerate(patterns): | |
1764 | if s is EOF: |
|
1764 | if s is EOF: | |
1765 | self.eof_index = n |
|
1765 | self.eof_index = n | |
1766 | continue |
|
1766 | continue | |
1767 | if s is TIMEOUT: |
|
1767 | if s is TIMEOUT: | |
1768 | self.timeout_index = n |
|
1768 | self.timeout_index = n | |
1769 | continue |
|
1769 | continue | |
1770 | self._searches.append((n, s)) |
|
1770 | self._searches.append((n, s)) | |
1771 |
|
1771 | |||
1772 | def __str__(self): |
|
1772 | def __str__(self): | |
1773 |
|
1773 | |||
1774 | """This returns a human-readable string that represents the state of |
|
1774 | """This returns a human-readable string that represents the state of | |
1775 | the object.""" |
|
1775 | the object.""" | |
1776 |
|
1776 | |||
1777 | ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches] |
|
1777 | ss = [ (n,' %d: re.compile("%s")' % (n,str(s.pattern))) for n,s in self._searches] | |
1778 | ss.append((-1,'searcher_re:')) |
|
1778 | ss.append((-1,'searcher_re:')) | |
1779 | if self.eof_index >= 0: |
|
1779 | if self.eof_index >= 0: | |
1780 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) |
|
1780 | ss.append ((self.eof_index,' %d: EOF' % self.eof_index)) | |
1781 | if self.timeout_index >= 0: |
|
1781 | if self.timeout_index >= 0: | |
1782 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) |
|
1782 | ss.append ((self.timeout_index,' %d: TIMEOUT' % self.timeout_index)) | |
1783 | ss.sort() |
|
1783 | ss.sort() | |
1784 | return '\n'.join(a[1] for a in ss) |
|
1784 | return '\n'.join(a[1] for a in ss) | |
1785 |
|
1785 | |||
1786 | def search(self, buffer, freshlen, searchwindowsize=None): |
|
1786 | def search(self, buffer, freshlen, searchwindowsize=None): | |
1787 |
|
1787 | |||
1788 | """This searches 'buffer' for the first occurence of one of the regular |
|
1788 | """This searches 'buffer' for the first occurence of one of the regular | |
1789 | expressions. 'freshlen' must indicate the number of bytes at the end of |
|
1789 | expressions. 'freshlen' must indicate the number of bytes at the end of | |
1790 | 'buffer' which have not been searched before. |
|
1790 | 'buffer' which have not been searched before. | |
1791 |
|
1791 | |||
1792 | See class spawn for the 'searchwindowsize' argument. |
|
1792 | See class spawn for the 'searchwindowsize' argument. | |
1793 |
|
1793 | |||
1794 | If there is a match this returns the index of that string, and sets |
|
1794 | If there is a match this returns the index of that string, and sets | |
1795 | 'start', 'end' and 'match'. Otherwise, returns -1.""" |
|
1795 | 'start', 'end' and 'match'. Otherwise, returns -1.""" | |
1796 |
|
1796 | |||
1797 | absurd_match = len(buffer) |
|
1797 | absurd_match = len(buffer) | |
1798 | first_match = absurd_match |
|
1798 | first_match = absurd_match | |
1799 | # 'freshlen' doesn't help here -- we cannot predict the |
|
1799 | # 'freshlen' doesn't help here -- we cannot predict the | |
1800 | # length of a match, and the re module provides no help. |
|
1800 | # length of a match, and the re module provides no help. | |
1801 | if searchwindowsize is None: |
|
1801 | if searchwindowsize is None: | |
1802 | searchstart = 0 |
|
1802 | searchstart = 0 | |
1803 | else: |
|
1803 | else: | |
1804 | searchstart = max(0, len(buffer)-searchwindowsize) |
|
1804 | searchstart = max(0, len(buffer)-searchwindowsize) | |
1805 | for index, s in self._searches: |
|
1805 | for index, s in self._searches: | |
1806 | match = s.search(buffer, searchstart) |
|
1806 | match = s.search(buffer, searchstart) | |
1807 | if match is None: |
|
1807 | if match is None: | |
1808 | continue |
|
1808 | continue | |
1809 | n = match.start() |
|
1809 | n = match.start() | |
1810 | if n < first_match: |
|
1810 | if n < first_match: | |
1811 | first_match = n |
|
1811 | first_match = n | |
1812 | the_match = match |
|
1812 | the_match = match | |
1813 | best_index = index |
|
1813 | best_index = index | |
1814 | if first_match == absurd_match: |
|
1814 | if first_match == absurd_match: | |
1815 | return -1 |
|
1815 | return -1 | |
1816 | self.start = first_match |
|
1816 | self.start = first_match | |
1817 | self.match = the_match |
|
1817 | self.match = the_match | |
1818 | self.end = self.match.end() |
|
1818 | self.end = self.match.end() | |
1819 | return best_index |
|
1819 | return best_index | |
1820 |
|
1820 | |||
1821 | def which (filename): |
|
1821 | def which (filename): | |
1822 |
|
1822 | |||
1823 | """This takes a given filename; tries to find it in the environment path; |
|
1823 | """This takes a given filename; tries to find it in the environment path; | |
1824 | then checks if it is executable. This returns the full path to the filename |
|
1824 | then checks if it is executable. This returns the full path to the filename | |
1825 | if found and executable. Otherwise this returns None.""" |
|
1825 | if found and executable. Otherwise this returns None.""" | |
1826 |
|
1826 | |||
1827 | # Special case where filename already contains a path. |
|
1827 | # Special case where filename already contains a path. | |
1828 | if os.path.dirname(filename) != '': |
|
1828 | if os.path.dirname(filename) != '': | |
1829 | if os.access (filename, os.X_OK): |
|
1829 | if os.access (filename, os.X_OK): | |
1830 | return filename |
|
1830 | return filename | |
1831 |
|
1831 | |||
1832 | if not os.environ.has_key('PATH') or os.environ['PATH'] == '': |
|
1832 | if not os.environ.has_key('PATH') or os.environ['PATH'] == '': | |
1833 | p = os.defpath |
|
1833 | p = os.defpath | |
1834 | else: |
|
1834 | else: | |
1835 | p = os.environ['PATH'] |
|
1835 | p = os.environ['PATH'] | |
1836 |
|
1836 | |||
1837 | pathlist = p.split(os.pathsep) |
|
1837 | pathlist = p.split(os.pathsep) | |
1838 |
|
1838 | |||
1839 | for path in pathlist: |
|
1839 | for path in pathlist: | |
1840 | f = os.path.join(path, filename) |
|
1840 | f = os.path.join(path, filename) | |
1841 | if os.access(f, os.X_OK): |
|
1841 | if os.access(f, os.X_OK): | |
1842 | return f |
|
1842 | return f | |
1843 | return None |
|
1843 | return None | |
1844 |
|
1844 | |||
1845 | def split_command_line(command_line): |
|
1845 | def split_command_line(command_line): | |
1846 |
|
1846 | |||
1847 | """This splits a command line into a list of arguments. It splits arguments |
|
1847 | """This splits a command line into a list of arguments. It splits arguments | |
1848 | on spaces, but handles embedded quotes, doublequotes, and escaped |
|
1848 | on spaces, but handles embedded quotes, doublequotes, and escaped | |
1849 | characters. It's impossible to do this with a regular expression, so I |
|
1849 | characters. It's impossible to do this with a regular expression, so I | |
1850 | wrote a little state machine to parse the command line. """ |
|
1850 | wrote a little state machine to parse the command line. """ | |
1851 |
|
1851 | |||
1852 | arg_list = [] |
|
1852 | arg_list = [] | |
1853 | arg = '' |
|
1853 | arg = '' | |
1854 |
|
1854 | |||
1855 | # Constants to name the states we can be in. |
|
1855 | # Constants to name the states we can be in. | |
1856 | state_basic = 0 |
|
1856 | state_basic = 0 | |
1857 | state_esc = 1 |
|
1857 | state_esc = 1 | |
1858 | state_singlequote = 2 |
|
1858 | state_singlequote = 2 | |
1859 | state_doublequote = 3 |
|
1859 | state_doublequote = 3 | |
1860 | state_whitespace = 4 # The state of consuming whitespace between commands. |
|
1860 | state_whitespace = 4 # The state of consuming whitespace between commands. | |
1861 | state = state_basic |
|
1861 | state = state_basic | |
1862 |
|
1862 | |||
1863 | for c in command_line: |
|
1863 | for c in command_line: | |
1864 | if state == state_basic or state == state_whitespace: |
|
1864 | if state == state_basic or state == state_whitespace: | |
1865 | if c == '\\': # Escape the next character |
|
1865 | if c == '\\': # Escape the next character | |
1866 | state = state_esc |
|
1866 | state = state_esc | |
1867 | elif c == r"'": # Handle single quote |
|
1867 | elif c == r"'": # Handle single quote | |
1868 | state = state_singlequote |
|
1868 | state = state_singlequote | |
1869 | elif c == r'"': # Handle double quote |
|
1869 | elif c == r'"': # Handle double quote | |
1870 | state = state_doublequote |
|
1870 | state = state_doublequote | |
1871 | elif c.isspace(): |
|
1871 | elif c.isspace(): | |
1872 | # Add arg to arg_list if we aren't in the middle of whitespace. |
|
1872 | # Add arg to arg_list if we aren't in the middle of whitespace. | |
1873 | if state == state_whitespace: |
|
1873 | if state == state_whitespace: | |
1874 | None # Do nothing. |
|
1874 | None # Do nothing. | |
1875 | else: |
|
1875 | else: | |
1876 | arg_list.append(arg) |
|
1876 | arg_list.append(arg) | |
1877 | arg = '' |
|
1877 | arg = '' | |
1878 | state = state_whitespace |
|
1878 | state = state_whitespace | |
1879 | else: |
|
1879 | else: | |
1880 | arg = arg + c |
|
1880 | arg = arg + c | |
1881 | state = state_basic |
|
1881 | state = state_basic | |
1882 | elif state == state_esc: |
|
1882 | elif state == state_esc: | |
1883 | arg = arg + c |
|
1883 | arg = arg + c | |
1884 | state = state_basic |
|
1884 | state = state_basic | |
1885 | elif state == state_singlequote: |
|
1885 | elif state == state_singlequote: | |
1886 | if c == r"'": |
|
1886 | if c == r"'": | |
1887 | state = state_basic |
|
1887 | state = state_basic | |
1888 | else: |
|
1888 | else: | |
1889 | arg = arg + c |
|
1889 | arg = arg + c | |
1890 | elif state == state_doublequote: |
|
1890 | elif state == state_doublequote: | |
1891 | if c == r'"': |
|
1891 | if c == r'"': | |
1892 | state = state_basic |
|
1892 | state = state_basic | |
1893 | else: |
|
1893 | else: | |
1894 | arg = arg + c |
|
1894 | arg = arg + c | |
1895 |
|
1895 | |||
1896 | if arg != '': |
|
1896 | if arg != '': | |
1897 | arg_list.append(arg) |
|
1897 | arg_list.append(arg) | |
1898 | return arg_list |
|
1898 | return arg_list | |
1899 |
|
1899 | |||
1900 | # vi:set sr et ts=4 sw=4 ft=python : |
|
1900 | # vi:set sr et ts=4 sw=4 ft=python : |
@@ -1,484 +1,483 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Manage background (threaded) jobs conveniently from an interactive shell. |
|
2 | """Manage background (threaded) jobs conveniently from an interactive shell. | |
3 |
|
3 | |||
4 | This module provides a BackgroundJobManager class. This is the main class |
|
4 | This module provides a BackgroundJobManager class. This is the main class | |
5 | meant for public usage, it implements an object which can create and manage |
|
5 | meant for public usage, it implements an object which can create and manage | |
6 | new background jobs. |
|
6 | new background jobs. | |
7 |
|
7 | |||
8 | It also provides the actual job classes managed by these BackgroundJobManager |
|
8 | It also provides the actual job classes managed by these BackgroundJobManager | |
9 | objects, see their docstrings below. |
|
9 | objects, see their docstrings below. | |
10 |
|
10 | |||
11 |
|
11 | |||
12 | This system was inspired by discussions with B. Granger and the |
|
12 | This system was inspired by discussions with B. Granger and the | |
13 | BackgroundCommand class described in the book Python Scripting for |
|
13 | BackgroundCommand class described in the book Python Scripting for | |
14 | Computational Science, by H. P. Langtangen: |
|
14 | Computational Science, by H. P. Langtangen: | |
15 |
|
15 | |||
16 | http://folk.uio.no/hpl/scripting |
|
16 | http://folk.uio.no/hpl/scripting | |
17 |
|
17 | |||
18 | (although ultimately no code from this text was used, as IPython's system is a |
|
18 | (although ultimately no code from this text was used, as IPython's system is a | |
19 | separate implementation). |
|
19 | separate implementation). | |
20 |
|
20 | |||
21 | An example notebook is provided in our documentation illustrating interactive |
|
21 | An example notebook is provided in our documentation illustrating interactive | |
22 | use of the system. |
|
22 | use of the system. | |
23 | """ |
|
23 | """ | |
24 |
|
24 | |||
25 | #***************************************************************************** |
|
25 | #***************************************************************************** | |
26 | # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu> |
|
26 | # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu> | |
27 | # |
|
27 | # | |
28 | # Distributed under the terms of the BSD License. The full license is in |
|
28 | # Distributed under the terms of the BSD License. The full license is in | |
29 | # the file COPYING, distributed as part of this software. |
|
29 | # the file COPYING, distributed as part of this software. | |
30 | #***************************************************************************** |
|
30 | #***************************************************************************** | |
31 |
|
31 | |||
32 | # Code begins |
|
32 | # Code begins | |
33 | import sys |
|
33 | import sys | |
34 | import threading |
|
34 | import threading | |
35 |
|
35 | |||
36 | from IPython.core.ultratb import AutoFormattedTB |
|
36 | from IPython.core.ultratb import AutoFormattedTB | |
37 | from IPython.utils.warn import warn, error |
|
37 | from IPython.utils.warn import warn, error | |
38 |
|
38 | |||
39 |
|
39 | |||
40 | class BackgroundJobManager(object): |
|
40 | class BackgroundJobManager(object): | |
41 | """Class to manage a pool of backgrounded threaded jobs. |
|
41 | """Class to manage a pool of backgrounded threaded jobs. | |
42 |
|
42 | |||
43 | Below, we assume that 'jobs' is a BackgroundJobManager instance. |
|
43 | Below, we assume that 'jobs' is a BackgroundJobManager instance. | |
44 |
|
44 | |||
45 | Usage summary (see the method docstrings for details): |
|
45 | Usage summary (see the method docstrings for details): | |
46 |
|
46 | |||
47 | jobs.new(...) -> start a new job |
|
47 | jobs.new(...) -> start a new job | |
48 |
|
48 | |||
49 | jobs() or jobs.status() -> print status summary of all jobs |
|
49 | jobs() or jobs.status() -> print status summary of all jobs | |
50 |
|
50 | |||
51 | jobs[N] -> returns job number N. |
|
51 | jobs[N] -> returns job number N. | |
52 |
|
52 | |||
53 | foo = jobs[N].result -> assign to variable foo the result of job N |
|
53 | foo = jobs[N].result -> assign to variable foo the result of job N | |
54 |
|
54 | |||
55 | jobs[N].traceback() -> print the traceback of dead job N |
|
55 | jobs[N].traceback() -> print the traceback of dead job N | |
56 |
|
56 | |||
57 | jobs.remove(N) -> remove (finished) job N |
|
57 | jobs.remove(N) -> remove (finished) job N | |
58 |
|
58 | |||
59 | jobs.flush() -> remove all finished jobs |
|
59 | jobs.flush() -> remove all finished jobs | |
60 |
|
60 | |||
61 | As a convenience feature, BackgroundJobManager instances provide the |
|
61 | As a convenience feature, BackgroundJobManager instances provide the | |
62 | utility result and traceback methods which retrieve the corresponding |
|
62 | utility result and traceback methods which retrieve the corresponding | |
63 | information from the jobs list: |
|
63 | information from the jobs list: | |
64 |
|
64 | |||
65 | jobs.result(N) <--> jobs[N].result |
|
65 | jobs.result(N) <--> jobs[N].result | |
66 | jobs.traceback(N) <--> jobs[N].traceback() |
|
66 | jobs.traceback(N) <--> jobs[N].traceback() | |
67 |
|
67 | |||
68 | While this appears minor, it allows you to use tab completion |
|
68 | While this appears minor, it allows you to use tab completion | |
69 | interactively on the job manager instance. |
|
69 | interactively on the job manager instance. | |
70 | """ |
|
70 | """ | |
71 |
|
71 | |||
72 | def __init__(self): |
|
72 | def __init__(self): | |
73 | # Lists for job management, accessed via a property to ensure they're |
|
73 | # Lists for job management, accessed via a property to ensure they're | |
74 | # up to date.x |
|
74 | # up to date.x | |
75 | self._running = [] |
|
75 | self._running = [] | |
76 | self._completed = [] |
|
76 | self._completed = [] | |
77 | self._dead = [] |
|
77 | self._dead = [] | |
78 | # A dict of all jobs, so users can easily access any of them |
|
78 | # A dict of all jobs, so users can easily access any of them | |
79 | self.all = {} |
|
79 | self.all = {} | |
80 | # For reporting |
|
80 | # For reporting | |
81 | self._comp_report = [] |
|
81 | self._comp_report = [] | |
82 | self._dead_report = [] |
|
82 | self._dead_report = [] | |
83 | # Store status codes locally for fast lookups |
|
83 | # Store status codes locally for fast lookups | |
84 | self._s_created = BackgroundJobBase.stat_created_c |
|
84 | self._s_created = BackgroundJobBase.stat_created_c | |
85 | self._s_running = BackgroundJobBase.stat_running_c |
|
85 | self._s_running = BackgroundJobBase.stat_running_c | |
86 | self._s_completed = BackgroundJobBase.stat_completed_c |
|
86 | self._s_completed = BackgroundJobBase.stat_completed_c | |
87 | self._s_dead = BackgroundJobBase.stat_dead_c |
|
87 | self._s_dead = BackgroundJobBase.stat_dead_c | |
88 |
|
88 | |||
89 | @property |
|
89 | @property | |
90 | def running(self): |
|
90 | def running(self): | |
91 | self._update_status() |
|
91 | self._update_status() | |
92 | return self._running |
|
92 | return self._running | |
93 |
|
93 | |||
94 | @property |
|
94 | @property | |
95 | def dead(self): |
|
95 | def dead(self): | |
96 | self._update_status() |
|
96 | self._update_status() | |
97 | return self._dead |
|
97 | return self._dead | |
98 |
|
98 | |||
99 | @property |
|
99 | @property | |
100 | def completed(self): |
|
100 | def completed(self): | |
101 | self._update_status() |
|
101 | self._update_status() | |
102 | return self._completed |
|
102 | return self._completed | |
103 |
|
103 | |||
104 | def new(self, func_or_exp, *args, **kwargs): |
|
104 | def new(self, func_or_exp, *args, **kwargs): | |
105 | """Add a new background job and start it in a separate thread. |
|
105 | """Add a new background job and start it in a separate thread. | |
106 |
|
106 | |||
107 | There are two types of jobs which can be created: |
|
107 | There are two types of jobs which can be created: | |
108 |
|
108 | |||
109 | 1. Jobs based on expressions which can be passed to an eval() call. |
|
109 | 1. Jobs based on expressions which can be passed to an eval() call. | |
110 | The expression must be given as a string. For example: |
|
110 | The expression must be given as a string. For example: | |
111 |
|
111 | |||
112 | job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) |
|
112 | job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]]) | |
113 |
|
113 | |||
114 | The given expression is passed to eval(), along with the optional |
|
114 | The given expression is passed to eval(), along with the optional | |
115 | global/local dicts provided. If no dicts are given, they are |
|
115 | global/local dicts provided. If no dicts are given, they are | |
116 | extracted automatically from the caller's frame. |
|
116 | extracted automatically from the caller's frame. | |
117 |
|
117 | |||
118 | A Python statement is NOT a valid eval() expression. Basically, you |
|
118 | A Python statement is NOT a valid eval() expression. Basically, you | |
119 | can only use as an eval() argument something which can go on the right |
|
119 | can only use as an eval() argument something which can go on the right | |
120 | of an '=' sign and be assigned to a variable. |
|
120 | of an '=' sign and be assigned to a variable. | |
121 |
|
121 | |||
122 | For example,"print 'hello'" is not valid, but '2+3' is. |
|
122 | For example,"print 'hello'" is not valid, but '2+3' is. | |
123 |
|
123 | |||
124 | 2. Jobs given a function object, optionally passing additional |
|
124 | 2. Jobs given a function object, optionally passing additional | |
125 | positional arguments: |
|
125 | positional arguments: | |
126 |
|
126 | |||
127 | job_manager.new(myfunc, x, y) |
|
127 | job_manager.new(myfunc, x, y) | |
128 |
|
128 | |||
129 | The function is called with the given arguments. |
|
129 | The function is called with the given arguments. | |
130 |
|
130 | |||
131 | If you need to pass keyword arguments to your function, you must |
|
131 | If you need to pass keyword arguments to your function, you must | |
132 | supply them as a dict named kw: |
|
132 | supply them as a dict named kw: | |
133 |
|
133 | |||
134 | job_manager.new(myfunc, x, y, kw=dict(z=1)) |
|
134 | job_manager.new(myfunc, x, y, kw=dict(z=1)) | |
135 |
|
135 | |||
136 | The reason for this assymmetry is that the new() method needs to |
|
136 | The reason for this assymmetry is that the new() method needs to | |
137 | maintain access to its own keywords, and this prevents name collisions |
|
137 | maintain access to its own keywords, and this prevents name collisions | |
138 | between arguments to new() and arguments to your own functions. |
|
138 | between arguments to new() and arguments to your own functions. | |
139 |
|
139 | |||
140 | In both cases, the result is stored in the job.result field of the |
|
140 | In both cases, the result is stored in the job.result field of the | |
141 | background job object. |
|
141 | background job object. | |
142 |
|
142 | |||
143 | You can set `daemon` attribute of the thread by giving the keyword |
|
143 | You can set `daemon` attribute of the thread by giving the keyword | |
144 | argument `daemon`. |
|
144 | argument `daemon`. | |
145 |
|
145 | |||
146 | Notes and caveats: |
|
146 | Notes and caveats: | |
147 |
|
147 | |||
148 | 1. All threads running share the same standard output. Thus, if your |
|
148 | 1. All threads running share the same standard output. Thus, if your | |
149 | background jobs generate output, it will come out on top of whatever |
|
149 | background jobs generate output, it will come out on top of whatever | |
150 | you are currently writing. For this reason, background jobs are best |
|
150 | you are currently writing. For this reason, background jobs are best | |
151 | used with silent functions which simply return their output. |
|
151 | used with silent functions which simply return their output. | |
152 |
|
152 | |||
153 | 2. Threads also all work within the same global namespace, and this |
|
153 | 2. Threads also all work within the same global namespace, and this | |
154 | system does not lock interactive variables. So if you send job to the |
|
154 | system does not lock interactive variables. So if you send job to the | |
155 | background which operates on a mutable object for a long time, and |
|
155 | background which operates on a mutable object for a long time, and | |
156 | start modifying that same mutable object interactively (or in another |
|
156 | start modifying that same mutable object interactively (or in another | |
157 | backgrounded job), all sorts of bizarre behaviour will occur. |
|
157 | backgrounded job), all sorts of bizarre behaviour will occur. | |
158 |
|
158 | |||
159 | 3. If a background job is spending a lot of time inside a C extension |
|
159 | 3. If a background job is spending a lot of time inside a C extension | |
160 | module which does not release the Python Global Interpreter Lock |
|
160 | module which does not release the Python Global Interpreter Lock | |
161 | (GIL), this will block the IPython prompt. This is simply because the |
|
161 | (GIL), this will block the IPython prompt. This is simply because the | |
162 | Python interpreter can only switch between threads at Python |
|
162 | Python interpreter can only switch between threads at Python | |
163 | bytecodes. While the execution is inside C code, the interpreter must |
|
163 | bytecodes. While the execution is inside C code, the interpreter must | |
164 | simply wait unless the extension module releases the GIL. |
|
164 | simply wait unless the extension module releases the GIL. | |
165 |
|
165 | |||
166 | 4. There is no way, due to limitations in the Python threads library, |
|
166 | 4. There is no way, due to limitations in the Python threads library, | |
167 | to kill a thread once it has started.""" |
|
167 | to kill a thread once it has started.""" | |
168 |
|
168 | |||
169 | if callable(func_or_exp): |
|
169 | if callable(func_or_exp): | |
170 | kw = kwargs.get('kw',{}) |
|
170 | kw = kwargs.get('kw',{}) | |
171 | job = BackgroundJobFunc(func_or_exp,*args,**kw) |
|
171 | job = BackgroundJobFunc(func_or_exp,*args,**kw) | |
172 | elif isinstance(func_or_exp, basestring): |
|
172 | elif isinstance(func_or_exp, basestring): | |
173 | if not args: |
|
173 | if not args: | |
174 | frame = sys._getframe(1) |
|
174 | frame = sys._getframe(1) | |
175 | glob, loc = frame.f_globals, frame.f_locals |
|
175 | glob, loc = frame.f_globals, frame.f_locals | |
176 | elif len(args)==1: |
|
176 | elif len(args)==1: | |
177 | glob = loc = args[0] |
|
177 | glob = loc = args[0] | |
178 | elif len(args)==2: |
|
178 | elif len(args)==2: | |
179 | glob,loc = args |
|
179 | glob,loc = args | |
180 | else: |
|
180 | else: | |
181 | raise ValueError( |
|
181 | raise ValueError( | |
182 | 'Expression jobs take at most 2 args (globals,locals)') |
|
182 | 'Expression jobs take at most 2 args (globals,locals)') | |
183 | job = BackgroundJobExpr(func_or_exp, glob, loc) |
|
183 | job = BackgroundJobExpr(func_or_exp, glob, loc) | |
184 | else: |
|
184 | else: | |
185 | raise TypeError('invalid args for new job') |
|
185 | raise TypeError('invalid args for new job') | |
186 |
|
186 | |||
187 | if kwargs.get('daemon', False): |
|
187 | if kwargs.get('daemon', False): | |
188 | job.daemon = True |
|
188 | job.daemon = True | |
189 | job.num = len(self.all)+1 if self.all else 0 |
|
189 | job.num = len(self.all)+1 if self.all else 0 | |
190 | self.running.append(job) |
|
190 | self.running.append(job) | |
191 | self.all[job.num] = job |
|
191 | self.all[job.num] = job | |
192 | print 'Starting job # %s in a separate thread.' % job.num |
|
192 | print 'Starting job # %s in a separate thread.' % job.num | |
193 | job.start() |
|
193 | job.start() | |
194 | return job |
|
194 | return job | |
195 |
|
195 | |||
196 | def __getitem__(self, job_key): |
|
196 | def __getitem__(self, job_key): | |
197 | num = job_key if isinstance(job_key, int) else job_key.num |
|
197 | num = job_key if isinstance(job_key, int) else job_key.num | |
198 | return self.all[num] |
|
198 | return self.all[num] | |
199 |
|
199 | |||
200 | def __call__(self): |
|
200 | def __call__(self): | |
201 | """An alias to self.status(), |
|
201 | """An alias to self.status(), | |
202 |
|
202 | |||
203 | This allows you to simply call a job manager instance much like the |
|
203 | This allows you to simply call a job manager instance much like the | |
204 | Unix `jobs` shell command.""" |
|
204 | Unix `jobs` shell command.""" | |
205 |
|
205 | |||
206 | return self.status() |
|
206 | return self.status() | |
207 |
|
207 | |||
208 | def _update_status(self): |
|
208 | def _update_status(self): | |
209 | """Update the status of the job lists. |
|
209 | """Update the status of the job lists. | |
210 |
|
210 | |||
211 | This method moves finished jobs to one of two lists: |
|
211 | This method moves finished jobs to one of two lists: | |
212 | - self.completed: jobs which completed successfully |
|
212 | - self.completed: jobs which completed successfully | |
213 | - self.dead: jobs which finished but died. |
|
213 | - self.dead: jobs which finished but died. | |
214 |
|
214 | |||
215 | It also copies those jobs to corresponding _report lists. These lists |
|
215 | It also copies those jobs to corresponding _report lists. These lists | |
216 | are used to report jobs completed/dead since the last update, and are |
|
216 | are used to report jobs completed/dead since the last update, and are | |
217 | then cleared by the reporting function after each call.""" |
|
217 | then cleared by the reporting function after each call.""" | |
218 |
|
218 | |||
219 | # Status codes |
|
219 | # Status codes | |
220 | srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead |
|
220 | srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead | |
221 | # State lists, use the actual lists b/c the public names are properties |
|
221 | # State lists, use the actual lists b/c the public names are properties | |
222 | # that call this very function on access |
|
222 | # that call this very function on access | |
223 | running, completed, dead = self._running, self._completed, self._dead |
|
223 | running, completed, dead = self._running, self._completed, self._dead | |
224 |
|
224 | |||
225 | # Now, update all state lists |
|
225 | # Now, update all state lists | |
226 | for num, job in enumerate(running): |
|
226 | for num, job in enumerate(running): | |
227 | stat = job.stat_code |
|
227 | stat = job.stat_code | |
228 | if stat == srun: |
|
228 | if stat == srun: | |
229 | continue |
|
229 | continue | |
230 | elif stat == scomp: |
|
230 | elif stat == scomp: | |
231 | completed.append(job) |
|
231 | completed.append(job) | |
232 | self._comp_report.append(job) |
|
232 | self._comp_report.append(job) | |
233 | running[num] = False |
|
233 | running[num] = False | |
234 | elif stat == sdead: |
|
234 | elif stat == sdead: | |
235 | dead.append(job) |
|
235 | dead.append(job) | |
236 | self._dead_report.append(job) |
|
236 | self._dead_report.append(job) | |
237 | running[num] = False |
|
237 | running[num] = False | |
238 | # Remove dead/completed jobs from running list |
|
238 | # Remove dead/completed jobs from running list | |
239 | running[:] = filter(None, running) |
|
239 | running[:] = filter(None, running) | |
240 |
|
240 | |||
241 | def _group_report(self,group,name): |
|
241 | def _group_report(self,group,name): | |
242 | """Report summary for a given job group. |
|
242 | """Report summary for a given job group. | |
243 |
|
243 | |||
244 | Return True if the group had any elements.""" |
|
244 | Return True if the group had any elements.""" | |
245 |
|
245 | |||
246 | if group: |
|
246 | if group: | |
247 | print '%s jobs:' % name |
|
247 | print '%s jobs:' % name | |
248 | for job in group: |
|
248 | for job in group: | |
249 | print '%s : %s' % (job.num,job) |
|
249 | print '%s : %s' % (job.num,job) | |
250 |
|
250 | |||
251 | return True |
|
251 | return True | |
252 |
|
252 | |||
253 | def _group_flush(self,group,name): |
|
253 | def _group_flush(self,group,name): | |
254 | """Flush a given job group |
|
254 | """Flush a given job group | |
255 |
|
255 | |||
256 | Return True if the group had any elements.""" |
|
256 | Return True if the group had any elements.""" | |
257 |
|
257 | |||
258 | njobs = len(group) |
|
258 | njobs = len(group) | |
259 | if njobs: |
|
259 | if njobs: | |
260 | plural = {1:''}.setdefault(njobs,'s') |
|
260 | plural = {1:''}.setdefault(njobs,'s') | |
261 | print 'Flushing %s %s job%s.' % (njobs,name,plural) |
|
261 | print 'Flushing %s %s job%s.' % (njobs,name,plural) | |
262 | group[:] = [] |
|
262 | group[:] = [] | |
263 | return True |
|
263 | return True | |
264 |
|
264 | |||
265 | def _status_new(self): |
|
265 | def _status_new(self): | |
266 | """Print the status of newly finished jobs. |
|
266 | """Print the status of newly finished jobs. | |
267 |
|
267 | |||
268 | Return True if any new jobs are reported. |
|
268 | Return True if any new jobs are reported. | |
269 |
|
269 | |||
270 | This call resets its own state every time, so it only reports jobs |
|
270 | This call resets its own state every time, so it only reports jobs | |
271 | which have finished since the last time it was called.""" |
|
271 | which have finished since the last time it was called.""" | |
272 |
|
272 | |||
273 | self._update_status() |
|
273 | self._update_status() | |
274 | new_comp = self._group_report(self._comp_report, 'Completed') |
|
274 | new_comp = self._group_report(self._comp_report, 'Completed') | |
275 | new_dead = self._group_report(self._dead_report, |
|
275 | new_dead = self._group_report(self._dead_report, | |
276 | 'Dead, call jobs.traceback() for details') |
|
276 | 'Dead, call jobs.traceback() for details') | |
277 | self._comp_report[:] = [] |
|
277 | self._comp_report[:] = [] | |
278 | self._dead_report[:] = [] |
|
278 | self._dead_report[:] = [] | |
279 | return new_comp or new_dead |
|
279 | return new_comp or new_dead | |
280 |
|
280 | |||
281 | def status(self,verbose=0): |
|
281 | def status(self,verbose=0): | |
282 | """Print a status of all jobs currently being managed.""" |
|
282 | """Print a status of all jobs currently being managed.""" | |
283 |
|
283 | |||
284 | self._update_status() |
|
284 | self._update_status() | |
285 | self._group_report(self.running,'Running') |
|
285 | self._group_report(self.running,'Running') | |
286 | self._group_report(self.completed,'Completed') |
|
286 | self._group_report(self.completed,'Completed') | |
287 | self._group_report(self.dead,'Dead') |
|
287 | self._group_report(self.dead,'Dead') | |
288 | # Also flush the report queues |
|
288 | # Also flush the report queues | |
289 | self._comp_report[:] = [] |
|
289 | self._comp_report[:] = [] | |
290 | self._dead_report[:] = [] |
|
290 | self._dead_report[:] = [] | |
291 |
|
291 | |||
292 | def remove(self,num): |
|
292 | def remove(self,num): | |
293 | """Remove a finished (completed or dead) job.""" |
|
293 | """Remove a finished (completed or dead) job.""" | |
294 |
|
294 | |||
295 | try: |
|
295 | try: | |
296 | job = self.all[num] |
|
296 | job = self.all[num] | |
297 | except KeyError: |
|
297 | except KeyError: | |
298 | error('Job #%s not found' % num) |
|
298 | error('Job #%s not found' % num) | |
299 | else: |
|
299 | else: | |
300 | stat_code = job.stat_code |
|
300 | stat_code = job.stat_code | |
301 | if stat_code == self._s_running: |
|
301 | if stat_code == self._s_running: | |
302 | error('Job #%s is still running, it can not be removed.' % num) |
|
302 | error('Job #%s is still running, it can not be removed.' % num) | |
303 | return |
|
303 | return | |
304 | elif stat_code == self._s_completed: |
|
304 | elif stat_code == self._s_completed: | |
305 | self.completed.remove(job) |
|
305 | self.completed.remove(job) | |
306 | elif stat_code == self._s_dead: |
|
306 | elif stat_code == self._s_dead: | |
307 | self.dead.remove(job) |
|
307 | self.dead.remove(job) | |
308 |
|
308 | |||
309 | def flush(self): |
|
309 | def flush(self): | |
310 | """Flush all finished jobs (completed and dead) from lists. |
|
310 | """Flush all finished jobs (completed and dead) from lists. | |
311 |
|
311 | |||
312 | Running jobs are never flushed. |
|
312 | Running jobs are never flushed. | |
313 |
|
313 | |||
314 | It first calls _status_new(), to update info. If any jobs have |
|
314 | It first calls _status_new(), to update info. If any jobs have | |
315 | completed since the last _status_new() call, the flush operation |
|
315 | completed since the last _status_new() call, the flush operation | |
316 | aborts.""" |
|
316 | aborts.""" | |
317 |
|
317 | |||
318 | # Remove the finished jobs from the master dict |
|
318 | # Remove the finished jobs from the master dict | |
319 | alljobs = self.all |
|
319 | alljobs = self.all | |
320 | for job in self.completed+self.dead: |
|
320 | for job in self.completed+self.dead: | |
321 | del(alljobs[job.num]) |
|
321 | del(alljobs[job.num]) | |
322 |
|
322 | |||
323 | # Now flush these lists completely |
|
323 | # Now flush these lists completely | |
324 | fl_comp = self._group_flush(self.completed, 'Completed') |
|
324 | fl_comp = self._group_flush(self.completed, 'Completed') | |
325 | fl_dead = self._group_flush(self.dead, 'Dead') |
|
325 | fl_dead = self._group_flush(self.dead, 'Dead') | |
326 | if not (fl_comp or fl_dead): |
|
326 | if not (fl_comp or fl_dead): | |
327 | print 'No jobs to flush.' |
|
327 | print 'No jobs to flush.' | |
328 |
|
328 | |||
329 | def result(self,num): |
|
329 | def result(self,num): | |
330 | """result(N) -> return the result of job N.""" |
|
330 | """result(N) -> return the result of job N.""" | |
331 | try: |
|
331 | try: | |
332 | return self.all[num].result |
|
332 | return self.all[num].result | |
333 | except KeyError: |
|
333 | except KeyError: | |
334 | error('Job #%s not found' % num) |
|
334 | error('Job #%s not found' % num) | |
335 |
|
335 | |||
336 | def _traceback(self, job): |
|
336 | def _traceback(self, job): | |
337 | num = job if isinstance(job, int) else job.num |
|
337 | num = job if isinstance(job, int) else job.num | |
338 | try: |
|
338 | try: | |
339 | self.all[num].traceback() |
|
339 | self.all[num].traceback() | |
340 | except KeyError: |
|
340 | except KeyError: | |
341 | error('Job #%s not found' % num) |
|
341 | error('Job #%s not found' % num) | |
342 |
|
342 | |||
343 | def traceback(self, job=None): |
|
343 | def traceback(self, job=None): | |
344 | if job is None: |
|
344 | if job is None: | |
345 | self._update_status() |
|
345 | self._update_status() | |
346 | for deadjob in self.dead: |
|
346 | for deadjob in self.dead: | |
347 | print "Traceback for: %r" % deadjob |
|
347 | print "Traceback for: %r" % deadjob | |
348 | self._traceback(deadjob) |
|
348 | self._traceback(deadjob) | |
349 |
|
349 | |||
350 | else: |
|
350 | else: | |
351 | self._traceback(job) |
|
351 | self._traceback(job) | |
352 |
|
352 | |||
353 |
|
353 | |||
354 | class BackgroundJobBase(threading.Thread): |
|
354 | class BackgroundJobBase(threading.Thread): | |
355 | """Base class to build BackgroundJob classes. |
|
355 | """Base class to build BackgroundJob classes. | |
356 |
|
356 | |||
357 | The derived classes must implement: |
|
357 | The derived classes must implement: | |
358 |
|
358 | |||
359 | - Their own __init__, since the one here raises NotImplementedError. The |
|
359 | - Their own __init__, since the one here raises NotImplementedError. The | |
360 | derived constructor must call self._init() at the end, to provide common |
|
360 | derived constructor must call self._init() at the end, to provide common | |
361 | initialization. |
|
361 | initialization. | |
362 |
|
362 | |||
363 | - A strform attribute used in calls to __str__. |
|
363 | - A strform attribute used in calls to __str__. | |
364 |
|
364 | |||
365 | - A call() method, which will make the actual execution call and must |
|
365 | - A call() method, which will make the actual execution call and must | |
366 | return a value to be held in the 'result' field of the job object.""" |
|
366 | return a value to be held in the 'result' field of the job object.""" | |
367 |
|
367 | |||
368 | # Class constants for status, in string and as numerical codes (when |
|
368 | # Class constants for status, in string and as numerical codes (when | |
369 | # updating jobs lists, we don't want to do string comparisons). This will |
|
369 | # updating jobs lists, we don't want to do string comparisons). This will | |
370 | # be done at every user prompt, so it has to be as fast as possible |
|
370 | # be done at every user prompt, so it has to be as fast as possible | |
371 | stat_created = 'Created'; stat_created_c = 0 |
|
371 | stat_created = 'Created'; stat_created_c = 0 | |
372 | stat_running = 'Running'; stat_running_c = 1 |
|
372 | stat_running = 'Running'; stat_running_c = 1 | |
373 | stat_completed = 'Completed'; stat_completed_c = 2 |
|
373 | stat_completed = 'Completed'; stat_completed_c = 2 | |
374 | stat_dead = 'Dead (Exception), call jobs.traceback() for details' |
|
374 | stat_dead = 'Dead (Exception), call jobs.traceback() for details' | |
375 | stat_dead_c = -1 |
|
375 | stat_dead_c = -1 | |
376 |
|
376 | |||
377 | def __init__(self): |
|
377 | def __init__(self): | |
378 | raise NotImplementedError, \ |
|
378 | raise NotImplementedError("This class can not be instantiated directly.") | |
379 | "This class can not be instantiated directly." |
|
|||
380 |
|
379 | |||
381 | def _init(self): |
|
380 | def _init(self): | |
382 | """Common initialization for all BackgroundJob objects""" |
|
381 | """Common initialization for all BackgroundJob objects""" | |
383 |
|
382 | |||
384 | for attr in ['call','strform']: |
|
383 | for attr in ['call','strform']: | |
385 | assert hasattr(self,attr), "Missing attribute <%s>" % attr |
|
384 | assert hasattr(self,attr), "Missing attribute <%s>" % attr | |
386 |
|
385 | |||
387 | # The num tag can be set by an external job manager |
|
386 | # The num tag can be set by an external job manager | |
388 | self.num = None |
|
387 | self.num = None | |
389 |
|
388 | |||
390 | self.status = BackgroundJobBase.stat_created |
|
389 | self.status = BackgroundJobBase.stat_created | |
391 | self.stat_code = BackgroundJobBase.stat_created_c |
|
390 | self.stat_code = BackgroundJobBase.stat_created_c | |
392 | self.finished = False |
|
391 | self.finished = False | |
393 | self.result = '<BackgroundJob has not completed>' |
|
392 | self.result = '<BackgroundJob has not completed>' | |
394 |
|
393 | |||
395 | # reuse the ipython traceback handler if we can get to it, otherwise |
|
394 | # reuse the ipython traceback handler if we can get to it, otherwise | |
396 | # make a new one |
|
395 | # make a new one | |
397 | try: |
|
396 | try: | |
398 | make_tb = get_ipython().InteractiveTB.text |
|
397 | make_tb = get_ipython().InteractiveTB.text | |
399 | except: |
|
398 | except: | |
400 | make_tb = AutoFormattedTB(mode = 'Context', |
|
399 | make_tb = AutoFormattedTB(mode = 'Context', | |
401 | color_scheme='NoColor', |
|
400 | color_scheme='NoColor', | |
402 | tb_offset = 1).text |
|
401 | tb_offset = 1).text | |
403 | # Note that the actual API for text() requires the three args to be |
|
402 | # Note that the actual API for text() requires the three args to be | |
404 | # passed in, so we wrap it in a simple lambda. |
|
403 | # passed in, so we wrap it in a simple lambda. | |
405 | self._make_tb = lambda : make_tb(None, None, None) |
|
404 | self._make_tb = lambda : make_tb(None, None, None) | |
406 |
|
405 | |||
407 | # Hold a formatted traceback if one is generated. |
|
406 | # Hold a formatted traceback if one is generated. | |
408 | self._tb = None |
|
407 | self._tb = None | |
409 |
|
408 | |||
410 | threading.Thread.__init__(self) |
|
409 | threading.Thread.__init__(self) | |
411 |
|
410 | |||
412 | def __str__(self): |
|
411 | def __str__(self): | |
413 | return self.strform |
|
412 | return self.strform | |
414 |
|
413 | |||
415 | def __repr__(self): |
|
414 | def __repr__(self): | |
416 | return '<BackgroundJob #%d: %s>' % (self.num, self.strform) |
|
415 | return '<BackgroundJob #%d: %s>' % (self.num, self.strform) | |
417 |
|
416 | |||
418 | def traceback(self): |
|
417 | def traceback(self): | |
419 | print self._tb |
|
418 | print self._tb | |
420 |
|
419 | |||
421 | def run(self): |
|
420 | def run(self): | |
422 | try: |
|
421 | try: | |
423 | self.status = BackgroundJobBase.stat_running |
|
422 | self.status = BackgroundJobBase.stat_running | |
424 | self.stat_code = BackgroundJobBase.stat_running_c |
|
423 | self.stat_code = BackgroundJobBase.stat_running_c | |
425 | self.result = self.call() |
|
424 | self.result = self.call() | |
426 | except: |
|
425 | except: | |
427 | self.status = BackgroundJobBase.stat_dead |
|
426 | self.status = BackgroundJobBase.stat_dead | |
428 | self.stat_code = BackgroundJobBase.stat_dead_c |
|
427 | self.stat_code = BackgroundJobBase.stat_dead_c | |
429 | self.finished = None |
|
428 | self.finished = None | |
430 | self.result = ('<BackgroundJob died, call jobs.traceback() for details>') |
|
429 | self.result = ('<BackgroundJob died, call jobs.traceback() for details>') | |
431 | self._tb = self._make_tb() |
|
430 | self._tb = self._make_tb() | |
432 | else: |
|
431 | else: | |
433 | self.status = BackgroundJobBase.stat_completed |
|
432 | self.status = BackgroundJobBase.stat_completed | |
434 | self.stat_code = BackgroundJobBase.stat_completed_c |
|
433 | self.stat_code = BackgroundJobBase.stat_completed_c | |
435 | self.finished = True |
|
434 | self.finished = True | |
436 |
|
435 | |||
437 |
|
436 | |||
438 | class BackgroundJobExpr(BackgroundJobBase): |
|
437 | class BackgroundJobExpr(BackgroundJobBase): | |
439 | """Evaluate an expression as a background job (uses a separate thread).""" |
|
438 | """Evaluate an expression as a background job (uses a separate thread).""" | |
440 |
|
439 | |||
441 | def __init__(self, expression, glob=None, loc=None): |
|
440 | def __init__(self, expression, glob=None, loc=None): | |
442 | """Create a new job from a string which can be fed to eval(). |
|
441 | """Create a new job from a string which can be fed to eval(). | |
443 |
|
442 | |||
444 | global/locals dicts can be provided, which will be passed to the eval |
|
443 | global/locals dicts can be provided, which will be passed to the eval | |
445 | call.""" |
|
444 | call.""" | |
446 |
|
445 | |||
447 | # fail immediately if the given expression can't be compiled |
|
446 | # fail immediately if the given expression can't be compiled | |
448 | self.code = compile(expression,'<BackgroundJob compilation>','eval') |
|
447 | self.code = compile(expression,'<BackgroundJob compilation>','eval') | |
449 |
|
448 | |||
450 | glob = {} if glob is None else glob |
|
449 | glob = {} if glob is None else glob | |
451 | loc = {} if loc is None else loc |
|
450 | loc = {} if loc is None else loc | |
452 | self.expression = self.strform = expression |
|
451 | self.expression = self.strform = expression | |
453 | self.glob = glob |
|
452 | self.glob = glob | |
454 | self.loc = loc |
|
453 | self.loc = loc | |
455 | self._init() |
|
454 | self._init() | |
456 |
|
455 | |||
457 | def call(self): |
|
456 | def call(self): | |
458 | return eval(self.code,self.glob,self.loc) |
|
457 | return eval(self.code,self.glob,self.loc) | |
459 |
|
458 | |||
460 |
|
459 | |||
461 | class BackgroundJobFunc(BackgroundJobBase): |
|
460 | class BackgroundJobFunc(BackgroundJobBase): | |
462 | """Run a function call as a background job (uses a separate thread).""" |
|
461 | """Run a function call as a background job (uses a separate thread).""" | |
463 |
|
462 | |||
464 | def __init__(self, func, *args, **kwargs): |
|
463 | def __init__(self, func, *args, **kwargs): | |
465 | """Create a new job from a callable object. |
|
464 | """Create a new job from a callable object. | |
466 |
|
465 | |||
467 | Any positional arguments and keyword args given to this constructor |
|
466 | Any positional arguments and keyword args given to this constructor | |
468 | after the initial callable are passed directly to it.""" |
|
467 | after the initial callable are passed directly to it.""" | |
469 |
|
468 | |||
470 | if not callable(func): |
|
469 | if not callable(func): | |
471 | raise TypeError( |
|
470 | raise TypeError( | |
472 | 'first argument to BackgroundJobFunc must be callable') |
|
471 | 'first argument to BackgroundJobFunc must be callable') | |
473 |
|
472 | |||
474 | self.func = func |
|
473 | self.func = func | |
475 | self.args = args |
|
474 | self.args = args | |
476 | self.kwargs = kwargs |
|
475 | self.kwargs = kwargs | |
477 | # The string form will only include the function passed, because |
|
476 | # The string form will only include the function passed, because | |
478 | # generating string representations of the arguments is a potentially |
|
477 | # generating string representations of the arguments is a potentially | |
479 | # _very_ expensive operation (e.g. with large arrays). |
|
478 | # _very_ expensive operation (e.g. with large arrays). | |
480 | self.strform = str(func) |
|
479 | self.strform = str(func) | |
481 | self._init() |
|
480 | self._init() | |
482 |
|
481 | |||
483 | def call(self): |
|
482 | def call(self): | |
484 | return self.func(*self.args, **self.kwargs) |
|
483 | return self.func(*self.args, **self.kwargs) |
@@ -1,188 +1,188 b'' | |||||
1 | """Tests for the decorators we've created for IPython. |
|
1 | """Tests for the decorators we've created for IPython. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | # Module imports |
|
4 | # Module imports | |
5 | # Std lib |
|
5 | # Std lib | |
6 | import inspect |
|
6 | import inspect | |
7 | import sys |
|
7 | import sys | |
8 | import unittest |
|
8 | import unittest | |
9 |
|
9 | |||
10 | # Third party |
|
10 | # Third party | |
11 | import nose.tools as nt |
|
11 | import nose.tools as nt | |
12 |
|
12 | |||
13 | # Our own |
|
13 | # Our own | |
14 | from IPython.testing import decorators as dec |
|
14 | from IPython.testing import decorators as dec | |
15 | from IPython.testing.skipdoctest import skip_doctest |
|
15 | from IPython.testing.skipdoctest import skip_doctest | |
16 | from IPython.testing.ipunittest import ParametricTestCase |
|
16 | from IPython.testing.ipunittest import ParametricTestCase | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Utilities |
|
19 | # Utilities | |
20 |
|
20 | |||
21 | # Note: copied from OInspect, kept here so the testing stuff doesn't create |
|
21 | # Note: copied from OInspect, kept here so the testing stuff doesn't create | |
22 | # circular dependencies and is easier to reuse. |
|
22 | # circular dependencies and is easier to reuse. | |
23 | def getargspec(obj): |
|
23 | def getargspec(obj): | |
24 | """Get the names and default values of a function's arguments. |
|
24 | """Get the names and default values of a function's arguments. | |
25 |
|
25 | |||
26 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
26 | A tuple of four things is returned: (args, varargs, varkw, defaults). | |
27 | 'args' is a list of the argument names (it may contain nested lists). |
|
27 | 'args' is a list of the argument names (it may contain nested lists). | |
28 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
28 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. | |
29 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
29 | 'defaults' is an n-tuple of the default values of the last n arguments. | |
30 |
|
30 | |||
31 | Modified version of inspect.getargspec from the Python Standard |
|
31 | Modified version of inspect.getargspec from the Python Standard | |
32 | Library.""" |
|
32 | Library.""" | |
33 |
|
33 | |||
34 | if inspect.isfunction(obj): |
|
34 | if inspect.isfunction(obj): | |
35 | func_obj = obj |
|
35 | func_obj = obj | |
36 | elif inspect.ismethod(obj): |
|
36 | elif inspect.ismethod(obj): | |
37 | func_obj = obj.im_func |
|
37 | func_obj = obj.im_func | |
38 | else: |
|
38 | else: | |
39 |
raise TypeError |
|
39 | raise TypeError('arg is not a Python function') | |
40 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
40 | args, varargs, varkw = inspect.getargs(func_obj.func_code) | |
41 | return args, varargs, varkw, func_obj.func_defaults |
|
41 | return args, varargs, varkw, func_obj.func_defaults | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Testing functions |
|
44 | # Testing functions | |
45 |
|
45 | |||
46 | @dec.as_unittest |
|
46 | @dec.as_unittest | |
47 | def trivial(): |
|
47 | def trivial(): | |
48 | """A trivial test""" |
|
48 | """A trivial test""" | |
49 | pass |
|
49 | pass | |
50 |
|
50 | |||
51 | # Some examples of parametric tests. |
|
51 | # Some examples of parametric tests. | |
52 |
|
52 | |||
53 | def is_smaller(i,j): |
|
53 | def is_smaller(i,j): | |
54 | assert i<j,"%s !< %s" % (i,j) |
|
54 | assert i<j,"%s !< %s" % (i,j) | |
55 |
|
55 | |||
56 | class Tester(ParametricTestCase): |
|
56 | class Tester(ParametricTestCase): | |
57 |
|
57 | |||
58 | def test_parametric(self): |
|
58 | def test_parametric(self): | |
59 | yield is_smaller(3, 4) |
|
59 | yield is_smaller(3, 4) | |
60 | x, y = 1, 2 |
|
60 | x, y = 1, 2 | |
61 | yield is_smaller(x, y) |
|
61 | yield is_smaller(x, y) | |
62 |
|
62 | |||
63 | @dec.parametric |
|
63 | @dec.parametric | |
64 | def test_par_standalone(): |
|
64 | def test_par_standalone(): | |
65 | yield is_smaller(3, 4) |
|
65 | yield is_smaller(3, 4) | |
66 | x, y = 1, 2 |
|
66 | x, y = 1, 2 | |
67 | yield is_smaller(x, y) |
|
67 | yield is_smaller(x, y) | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | @dec.skip |
|
70 | @dec.skip | |
71 | def test_deliberately_broken(): |
|
71 | def test_deliberately_broken(): | |
72 | """A deliberately broken test - we want to skip this one.""" |
|
72 | """A deliberately broken test - we want to skip this one.""" | |
73 | 1/0 |
|
73 | 1/0 | |
74 |
|
74 | |||
75 | @dec.skip('Testing the skip decorator') |
|
75 | @dec.skip('Testing the skip decorator') | |
76 | def test_deliberately_broken2(): |
|
76 | def test_deliberately_broken2(): | |
77 | """Another deliberately broken test - we want to skip this one.""" |
|
77 | """Another deliberately broken test - we want to skip this one.""" | |
78 | 1/0 |
|
78 | 1/0 | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | # Verify that we can correctly skip the doctest for a function at will, but |
|
81 | # Verify that we can correctly skip the doctest for a function at will, but | |
82 | # that the docstring itself is NOT destroyed by the decorator. |
|
82 | # that the docstring itself is NOT destroyed by the decorator. | |
83 | @skip_doctest |
|
83 | @skip_doctest | |
84 | def doctest_bad(x,y=1,**k): |
|
84 | def doctest_bad(x,y=1,**k): | |
85 | """A function whose doctest we need to skip. |
|
85 | """A function whose doctest we need to skip. | |
86 |
|
86 | |||
87 | >>> 1+1 |
|
87 | >>> 1+1 | |
88 | 3 |
|
88 | 3 | |
89 | """ |
|
89 | """ | |
90 | print 'x:',x |
|
90 | print 'x:',x | |
91 | print 'y:',y |
|
91 | print 'y:',y | |
92 | print 'k:',k |
|
92 | print 'k:',k | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | def call_doctest_bad(): |
|
95 | def call_doctest_bad(): | |
96 | """Check that we can still call the decorated functions. |
|
96 | """Check that we can still call the decorated functions. | |
97 |
|
97 | |||
98 | >>> doctest_bad(3,y=4) |
|
98 | >>> doctest_bad(3,y=4) | |
99 | x: 3 |
|
99 | x: 3 | |
100 | y: 4 |
|
100 | y: 4 | |
101 | k: {} |
|
101 | k: {} | |
102 | """ |
|
102 | """ | |
103 | pass |
|
103 | pass | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | def test_skip_dt_decorator(): |
|
106 | def test_skip_dt_decorator(): | |
107 | """Doctest-skipping decorator should preserve the docstring. |
|
107 | """Doctest-skipping decorator should preserve the docstring. | |
108 | """ |
|
108 | """ | |
109 | # Careful: 'check' must be a *verbatim* copy of the doctest_bad docstring! |
|
109 | # Careful: 'check' must be a *verbatim* copy of the doctest_bad docstring! | |
110 | check = """A function whose doctest we need to skip. |
|
110 | check = """A function whose doctest we need to skip. | |
111 |
|
111 | |||
112 | >>> 1+1 |
|
112 | >>> 1+1 | |
113 | 3 |
|
113 | 3 | |
114 | """ |
|
114 | """ | |
115 | # Fetch the docstring from doctest_bad after decoration. |
|
115 | # Fetch the docstring from doctest_bad after decoration. | |
116 | val = doctest_bad.__doc__ |
|
116 | val = doctest_bad.__doc__ | |
117 |
|
117 | |||
118 | nt.assert_equal(check,val,"doctest_bad docstrings don't match") |
|
118 | nt.assert_equal(check,val,"doctest_bad docstrings don't match") | |
119 |
|
119 | |||
120 |
|
120 | |||
121 | # Doctest skipping should work for class methods too |
|
121 | # Doctest skipping should work for class methods too | |
122 | class FooClass(object): |
|
122 | class FooClass(object): | |
123 | """FooClass |
|
123 | """FooClass | |
124 |
|
124 | |||
125 | Example: |
|
125 | Example: | |
126 |
|
126 | |||
127 | >>> 1+1 |
|
127 | >>> 1+1 | |
128 | 2 |
|
128 | 2 | |
129 | """ |
|
129 | """ | |
130 |
|
130 | |||
131 | @skip_doctest |
|
131 | @skip_doctest | |
132 | def __init__(self,x): |
|
132 | def __init__(self,x): | |
133 | """Make a FooClass. |
|
133 | """Make a FooClass. | |
134 |
|
134 | |||
135 | Example: |
|
135 | Example: | |
136 |
|
136 | |||
137 | >>> f = FooClass(3) |
|
137 | >>> f = FooClass(3) | |
138 | junk |
|
138 | junk | |
139 | """ |
|
139 | """ | |
140 | print 'Making a FooClass.' |
|
140 | print 'Making a FooClass.' | |
141 | self.x = x |
|
141 | self.x = x | |
142 |
|
142 | |||
143 | @skip_doctest |
|
143 | @skip_doctest | |
144 | def bar(self,y): |
|
144 | def bar(self,y): | |
145 | """Example: |
|
145 | """Example: | |
146 |
|
146 | |||
147 | >>> ff = FooClass(3) |
|
147 | >>> ff = FooClass(3) | |
148 | >>> ff.bar(0) |
|
148 | >>> ff.bar(0) | |
149 | boom! |
|
149 | boom! | |
150 | >>> 1/0 |
|
150 | >>> 1/0 | |
151 | bam! |
|
151 | bam! | |
152 | """ |
|
152 | """ | |
153 | return 1/y |
|
153 | return 1/y | |
154 |
|
154 | |||
155 | def baz(self,y): |
|
155 | def baz(self,y): | |
156 | """Example: |
|
156 | """Example: | |
157 |
|
157 | |||
158 | >>> ff2 = FooClass(3) |
|
158 | >>> ff2 = FooClass(3) | |
159 | Making a FooClass. |
|
159 | Making a FooClass. | |
160 | >>> ff2.baz(3) |
|
160 | >>> ff2.baz(3) | |
161 | True |
|
161 | True | |
162 | """ |
|
162 | """ | |
163 | return self.x==y |
|
163 | return self.x==y | |
164 |
|
164 | |||
165 |
|
165 | |||
166 | def test_skip_dt_decorator2(): |
|
166 | def test_skip_dt_decorator2(): | |
167 | """Doctest-skipping decorator should preserve function signature. |
|
167 | """Doctest-skipping decorator should preserve function signature. | |
168 | """ |
|
168 | """ | |
169 | # Hardcoded correct answer |
|
169 | # Hardcoded correct answer | |
170 | dtargs = (['x', 'y'], None, 'k', (1,)) |
|
170 | dtargs = (['x', 'y'], None, 'k', (1,)) | |
171 | # Introspect out the value |
|
171 | # Introspect out the value | |
172 | dtargsr = getargspec(doctest_bad) |
|
172 | dtargsr = getargspec(doctest_bad) | |
173 | assert dtargsr==dtargs, \ |
|
173 | assert dtargsr==dtargs, \ | |
174 | "Incorrectly reconstructed args for doctest_bad: %s" % (dtargsr,) |
|
174 | "Incorrectly reconstructed args for doctest_bad: %s" % (dtargsr,) | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | @dec.skip_linux |
|
177 | @dec.skip_linux | |
178 | def test_linux(): |
|
178 | def test_linux(): | |
179 | nt.assert_false(sys.platform.startswith('linux'),"This test can't run under linux") |
|
179 | nt.assert_false(sys.platform.startswith('linux'),"This test can't run under linux") | |
180 |
|
180 | |||
181 | @dec.skip_win32 |
|
181 | @dec.skip_win32 | |
182 | def test_win32(): |
|
182 | def test_win32(): | |
183 | nt.assert_not_equals(sys.platform,'win32',"This test can't run under windows") |
|
183 | nt.assert_not_equals(sys.platform,'win32',"This test can't run under windows") | |
184 |
|
184 | |||
185 | @dec.skip_osx |
|
185 | @dec.skip_osx | |
186 | def test_osx(): |
|
186 | def test_osx(): | |
187 | nt.assert_not_equals(sys.platform,'darwin',"This test can't run under osx") |
|
187 | nt.assert_not_equals(sys.platform,'darwin',"This test can't run under osx") | |
188 |
|
188 |
@@ -1,167 +1,167 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Older utilities that are not being used. |
|
3 | Older utilities that are not being used. | |
4 |
|
4 | |||
5 | WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT |
|
5 | WARNING: IF YOU NEED TO USE ONE OF THESE FUNCTIONS, PLEASE FIRST MOVE IT | |
6 | TO ANOTHER APPROPRIATE MODULE IN IPython.utils. |
|
6 | TO ANOTHER APPROPRIATE MODULE IN IPython.utils. | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2008-2011 The IPython Development Team |
|
10 | # Copyright (C) 2008-2011 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | import sys |
|
20 | import sys | |
21 | import warnings |
|
21 | import warnings | |
22 |
|
22 | |||
23 | from IPython.utils.warn import warn |
|
23 | from IPython.utils.warn import warn | |
24 |
|
24 | |||
25 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
26 | # Code |
|
26 | # Code | |
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 |
|
28 | |||
29 |
|
29 | |||
30 | def mutex_opts(dict,ex_op): |
|
30 | def mutex_opts(dict,ex_op): | |
31 | """Check for presence of mutually exclusive keys in a dict. |
|
31 | """Check for presence of mutually exclusive keys in a dict. | |
32 |
|
32 | |||
33 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" |
|
33 | Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]""" | |
34 | for op1,op2 in ex_op: |
|
34 | for op1,op2 in ex_op: | |
35 | if op1 in dict and op2 in dict: |
|
35 | if op1 in dict and op2 in dict: | |
36 |
raise ValueError |
|
36 | raise ValueError('\n*** ERROR in Arguments *** '\ | |
37 | 'Options '+op1+' and '+op2+' are mutually exclusive.' |
|
37 | 'Options '+op1+' and '+op2+' are mutually exclusive.') | |
38 |
|
38 | |||
39 |
|
39 | |||
40 | class EvalDict: |
|
40 | class EvalDict: | |
41 | """ |
|
41 | """ | |
42 | Emulate a dict which evaluates its contents in the caller's frame. |
|
42 | Emulate a dict which evaluates its contents in the caller's frame. | |
43 |
|
43 | |||
44 | Usage: |
|
44 | Usage: | |
45 | >>> number = 19 |
|
45 | >>> number = 19 | |
46 |
|
46 | |||
47 | >>> text = "python" |
|
47 | >>> text = "python" | |
48 |
|
48 | |||
49 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() |
|
49 | >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict() | |
50 | Python 2.1 rules! |
|
50 | Python 2.1 rules! | |
51 | """ |
|
51 | """ | |
52 |
|
52 | |||
53 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a |
|
53 | # This version is due to sismex01@hebmex.com on c.l.py, and is basically a | |
54 | # modified (shorter) version of: |
|
54 | # modified (shorter) version of: | |
55 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by |
|
55 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by | |
56 | # Skip Montanaro (skip@pobox.com). |
|
56 | # Skip Montanaro (skip@pobox.com). | |
57 |
|
57 | |||
58 | def __getitem__(self, name): |
|
58 | def __getitem__(self, name): | |
59 | frame = sys._getframe(1) |
|
59 | frame = sys._getframe(1) | |
60 | return eval(name, frame.f_globals, frame.f_locals) |
|
60 | return eval(name, frame.f_globals, frame.f_locals) | |
61 |
|
61 | |||
62 | EvalString = EvalDict # for backwards compatibility |
|
62 | EvalString = EvalDict # for backwards compatibility | |
63 |
|
63 | |||
64 |
|
64 | |||
65 | def all_belong(candidates,checklist): |
|
65 | def all_belong(candidates,checklist): | |
66 | """Check whether a list of items ALL appear in a given list of options. |
|
66 | """Check whether a list of items ALL appear in a given list of options. | |
67 |
|
67 | |||
68 | Returns a single 1 or 0 value.""" |
|
68 | Returns a single 1 or 0 value.""" | |
69 |
|
69 | |||
70 | return 1-(0 in [x in checklist for x in candidates]) |
|
70 | return 1-(0 in [x in checklist for x in candidates]) | |
71 |
|
71 | |||
72 |
|
72 | |||
73 | def belong(candidates,checklist): |
|
73 | def belong(candidates,checklist): | |
74 | """Check whether a list of items appear in a given list of options. |
|
74 | """Check whether a list of items appear in a given list of options. | |
75 |
|
75 | |||
76 | Returns a list of 1 and 0, one for each candidate given.""" |
|
76 | Returns a list of 1 and 0, one for each candidate given.""" | |
77 |
|
77 | |||
78 | return [x in checklist for x in candidates] |
|
78 | return [x in checklist for x in candidates] | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | def with_obj(object, **args): |
|
81 | def with_obj(object, **args): | |
82 | """Set multiple attributes for an object, similar to Pascal's with. |
|
82 | """Set multiple attributes for an object, similar to Pascal's with. | |
83 |
|
83 | |||
84 | Example: |
|
84 | Example: | |
85 | with_obj(jim, |
|
85 | with_obj(jim, | |
86 | born = 1960, |
|
86 | born = 1960, | |
87 | haircolour = 'Brown', |
|
87 | haircolour = 'Brown', | |
88 | eyecolour = 'Green') |
|
88 | eyecolour = 'Green') | |
89 |
|
89 | |||
90 | Credit: Greg Ewing, in |
|
90 | Credit: Greg Ewing, in | |
91 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. |
|
91 | http://mail.python.org/pipermail/python-list/2001-May/040703.html. | |
92 |
|
92 | |||
93 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' |
|
93 | NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with' | |
94 | has become a keyword for Python 2.5, so we had to rename it.""" |
|
94 | has become a keyword for Python 2.5, so we had to rename it.""" | |
95 |
|
95 | |||
96 | object.__dict__.update(args) |
|
96 | object.__dict__.update(args) | |
97 |
|
97 | |||
98 |
|
98 | |||
99 | def map_method(method,object_list,*argseq,**kw): |
|
99 | def map_method(method,object_list,*argseq,**kw): | |
100 | """map_method(method,object_list,*args,**kw) -> list |
|
100 | """map_method(method,object_list,*args,**kw) -> list | |
101 |
|
101 | |||
102 | Return a list of the results of applying the methods to the items of the |
|
102 | Return a list of the results of applying the methods to the items of the | |
103 | argument sequence(s). If more than one sequence is given, the method is |
|
103 | argument sequence(s). If more than one sequence is given, the method is | |
104 | called with an argument list consisting of the corresponding item of each |
|
104 | called with an argument list consisting of the corresponding item of each | |
105 | sequence. All sequences must be of the same length. |
|
105 | sequence. All sequences must be of the same length. | |
106 |
|
106 | |||
107 | Keyword arguments are passed verbatim to all objects called. |
|
107 | Keyword arguments are passed verbatim to all objects called. | |
108 |
|
108 | |||
109 | This is Python code, so it's not nearly as fast as the builtin map().""" |
|
109 | This is Python code, so it's not nearly as fast as the builtin map().""" | |
110 |
|
110 | |||
111 | out_list = [] |
|
111 | out_list = [] | |
112 | idx = 0 |
|
112 | idx = 0 | |
113 | for object in object_list: |
|
113 | for object in object_list: | |
114 | try: |
|
114 | try: | |
115 | handler = getattr(object, method) |
|
115 | handler = getattr(object, method) | |
116 | except AttributeError: |
|
116 | except AttributeError: | |
117 | out_list.append(None) |
|
117 | out_list.append(None) | |
118 | else: |
|
118 | else: | |
119 | if argseq: |
|
119 | if argseq: | |
120 | args = map(lambda lst:lst[idx],argseq) |
|
120 | args = map(lambda lst:lst[idx],argseq) | |
121 | #print 'ob',object,'hand',handler,'ar',args # dbg |
|
121 | #print 'ob',object,'hand',handler,'ar',args # dbg | |
122 | out_list.append(handler(args,**kw)) |
|
122 | out_list.append(handler(args,**kw)) | |
123 | else: |
|
123 | else: | |
124 | out_list.append(handler(**kw)) |
|
124 | out_list.append(handler(**kw)) | |
125 | idx += 1 |
|
125 | idx += 1 | |
126 | return out_list |
|
126 | return out_list | |
127 |
|
127 | |||
128 |
|
128 | |||
129 | def import_fail_info(mod_name,fns=None): |
|
129 | def import_fail_info(mod_name,fns=None): | |
130 | """Inform load failure for a module.""" |
|
130 | """Inform load failure for a module.""" | |
131 |
|
131 | |||
132 | if fns == None: |
|
132 | if fns == None: | |
133 | warn("Loading of %s failed.\n" % (mod_name,)) |
|
133 | warn("Loading of %s failed.\n" % (mod_name,)) | |
134 | else: |
|
134 | else: | |
135 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) |
|
135 | warn("Loading of %s from %s failed.\n" % (fns,mod_name)) | |
136 |
|
136 | |||
137 |
|
137 | |||
138 | class NotGiven: pass |
|
138 | class NotGiven: pass | |
139 |
|
139 | |||
140 | def popkey(dct,key,default=NotGiven): |
|
140 | def popkey(dct,key,default=NotGiven): | |
141 | """Return dct[key] and delete dct[key]. |
|
141 | """Return dct[key] and delete dct[key]. | |
142 |
|
142 | |||
143 | If default is given, return it if dct[key] doesn't exist, otherwise raise |
|
143 | If default is given, return it if dct[key] doesn't exist, otherwise raise | |
144 | KeyError. """ |
|
144 | KeyError. """ | |
145 |
|
145 | |||
146 | try: |
|
146 | try: | |
147 | val = dct[key] |
|
147 | val = dct[key] | |
148 | except KeyError: |
|
148 | except KeyError: | |
149 | if default is NotGiven: |
|
149 | if default is NotGiven: | |
150 | raise |
|
150 | raise | |
151 | else: |
|
151 | else: | |
152 | return default |
|
152 | return default | |
153 | else: |
|
153 | else: | |
154 | del dct[key] |
|
154 | del dct[key] | |
155 | return val |
|
155 | return val | |
156 |
|
156 | |||
157 |
|
157 | |||
158 | def wrap_deprecated(func, suggest = '<nothing>'): |
|
158 | def wrap_deprecated(func, suggest = '<nothing>'): | |
159 | def newFunc(*args, **kwargs): |
|
159 | def newFunc(*args, **kwargs): | |
160 | warnings.warn("Call to deprecated function %s, use %s instead" % |
|
160 | warnings.warn("Call to deprecated function %s, use %s instead" % | |
161 | ( func.__name__, suggest), |
|
161 | ( func.__name__, suggest), | |
162 | category=DeprecationWarning, |
|
162 | category=DeprecationWarning, | |
163 | stacklevel = 2) |
|
163 | stacklevel = 2) | |
164 | return func(*args, **kwargs) |
|
164 | return func(*args, **kwargs) | |
165 | return newFunc |
|
165 | return newFunc | |
166 |
|
166 | |||
167 |
|
167 |
@@ -1,186 +1,186 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tools for coloring text in ANSI terminals. |
|
2 | """Tools for coloring text in ANSI terminals. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #***************************************************************************** |
|
5 | #***************************************************************************** | |
6 | # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2002-2006 Fernando Perez. <fperez@colorado.edu> | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 |
|
11 | |||
12 | __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable'] |
|
12 | __all__ = ['TermColors','InputTermColors','ColorScheme','ColorSchemeTable'] | |
13 |
|
13 | |||
14 | import os |
|
14 | import os | |
15 |
|
15 | |||
16 | from IPython.utils.ipstruct import Struct |
|
16 | from IPython.utils.ipstruct import Struct | |
17 |
|
17 | |||
18 | color_templates = ( |
|
18 | color_templates = ( | |
19 | # Dark colors |
|
19 | # Dark colors | |
20 | ("Black" , "0;30"), |
|
20 | ("Black" , "0;30"), | |
21 | ("Red" , "0;31"), |
|
21 | ("Red" , "0;31"), | |
22 | ("Green" , "0;32"), |
|
22 | ("Green" , "0;32"), | |
23 | ("Brown" , "0;33"), |
|
23 | ("Brown" , "0;33"), | |
24 | ("Blue" , "0;34"), |
|
24 | ("Blue" , "0;34"), | |
25 | ("Purple" , "0;35"), |
|
25 | ("Purple" , "0;35"), | |
26 | ("Cyan" , "0;36"), |
|
26 | ("Cyan" , "0;36"), | |
27 | ("LightGray" , "0;37"), |
|
27 | ("LightGray" , "0;37"), | |
28 | # Light colors |
|
28 | # Light colors | |
29 | ("DarkGray" , "1;30"), |
|
29 | ("DarkGray" , "1;30"), | |
30 | ("LightRed" , "1;31"), |
|
30 | ("LightRed" , "1;31"), | |
31 | ("LightGreen" , "1;32"), |
|
31 | ("LightGreen" , "1;32"), | |
32 | ("Yellow" , "1;33"), |
|
32 | ("Yellow" , "1;33"), | |
33 | ("LightBlue" , "1;34"), |
|
33 | ("LightBlue" , "1;34"), | |
34 | ("LightPurple" , "1;35"), |
|
34 | ("LightPurple" , "1;35"), | |
35 | ("LightCyan" , "1;36"), |
|
35 | ("LightCyan" , "1;36"), | |
36 | ("White" , "1;37"), |
|
36 | ("White" , "1;37"), | |
37 | # Blinking colors. Probably should not be used in anything serious. |
|
37 | # Blinking colors. Probably should not be used in anything serious. | |
38 | ("BlinkBlack" , "5;30"), |
|
38 | ("BlinkBlack" , "5;30"), | |
39 | ("BlinkRed" , "5;31"), |
|
39 | ("BlinkRed" , "5;31"), | |
40 | ("BlinkGreen" , "5;32"), |
|
40 | ("BlinkGreen" , "5;32"), | |
41 | ("BlinkYellow" , "5;33"), |
|
41 | ("BlinkYellow" , "5;33"), | |
42 | ("BlinkBlue" , "5;34"), |
|
42 | ("BlinkBlue" , "5;34"), | |
43 | ("BlinkPurple" , "5;35"), |
|
43 | ("BlinkPurple" , "5;35"), | |
44 | ("BlinkCyan" , "5;36"), |
|
44 | ("BlinkCyan" , "5;36"), | |
45 | ("BlinkLightGray", "5;37"), |
|
45 | ("BlinkLightGray", "5;37"), | |
46 | ) |
|
46 | ) | |
47 |
|
47 | |||
48 | def make_color_table(in_class): |
|
48 | def make_color_table(in_class): | |
49 | """Build a set of color attributes in a class. |
|
49 | """Build a set of color attributes in a class. | |
50 |
|
50 | |||
51 | Helper function for building the *TermColors classes.""" |
|
51 | Helper function for building the *TermColors classes.""" | |
52 |
|
52 | |||
53 | for name,value in color_templates: |
|
53 | for name,value in color_templates: | |
54 | setattr(in_class,name,in_class._base % value) |
|
54 | setattr(in_class,name,in_class._base % value) | |
55 |
|
55 | |||
56 | class TermColors: |
|
56 | class TermColors: | |
57 | """Color escape sequences. |
|
57 | """Color escape sequences. | |
58 |
|
58 | |||
59 | This class defines the escape sequences for all the standard (ANSI?) |
|
59 | This class defines the escape sequences for all the standard (ANSI?) | |
60 | colors in terminals. Also defines a NoColor escape which is just the null |
|
60 | colors in terminals. Also defines a NoColor escape which is just the null | |
61 | string, suitable for defining 'dummy' color schemes in terminals which get |
|
61 | string, suitable for defining 'dummy' color schemes in terminals which get | |
62 | confused by color escapes. |
|
62 | confused by color escapes. | |
63 |
|
63 | |||
64 | This class should be used as a mixin for building color schemes.""" |
|
64 | This class should be used as a mixin for building color schemes.""" | |
65 |
|
65 | |||
66 | NoColor = '' # for color schemes in color-less terminals. |
|
66 | NoColor = '' # for color schemes in color-less terminals. | |
67 | Normal = '\033[0m' # Reset normal coloring |
|
67 | Normal = '\033[0m' # Reset normal coloring | |
68 | _base = '\033[%sm' # Template for all other colors |
|
68 | _base = '\033[%sm' # Template for all other colors | |
69 |
|
69 | |||
70 | # Build the actual color table as a set of class attributes: |
|
70 | # Build the actual color table as a set of class attributes: | |
71 | make_color_table(TermColors) |
|
71 | make_color_table(TermColors) | |
72 |
|
72 | |||
73 | class InputTermColors: |
|
73 | class InputTermColors: | |
74 | """Color escape sequences for input prompts. |
|
74 | """Color escape sequences for input prompts. | |
75 |
|
75 | |||
76 | This class is similar to TermColors, but the escapes are wrapped in \001 |
|
76 | This class is similar to TermColors, but the escapes are wrapped in \001 | |
77 | and \002 so that readline can properly know the length of each line and |
|
77 | and \002 so that readline can properly know the length of each line and | |
78 | can wrap lines accordingly. Use this class for any colored text which |
|
78 | can wrap lines accordingly. Use this class for any colored text which | |
79 | needs to be used in input prompts, such as in calls to raw_input(). |
|
79 | needs to be used in input prompts, such as in calls to raw_input(). | |
80 |
|
80 | |||
81 | This class defines the escape sequences for all the standard (ANSI?) |
|
81 | This class defines the escape sequences for all the standard (ANSI?) | |
82 | colors in terminals. Also defines a NoColor escape which is just the null |
|
82 | colors in terminals. Also defines a NoColor escape which is just the null | |
83 | string, suitable for defining 'dummy' color schemes in terminals which get |
|
83 | string, suitable for defining 'dummy' color schemes in terminals which get | |
84 | confused by color escapes. |
|
84 | confused by color escapes. | |
85 |
|
85 | |||
86 | This class should be used as a mixin for building color schemes.""" |
|
86 | This class should be used as a mixin for building color schemes.""" | |
87 |
|
87 | |||
88 | NoColor = '' # for color schemes in color-less terminals. |
|
88 | NoColor = '' # for color schemes in color-less terminals. | |
89 |
|
89 | |||
90 | if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs': |
|
90 | if os.name == 'nt' and os.environ.get('TERM','dumb') == 'emacs': | |
91 | # (X)emacs on W32 gets confused with \001 and \002 so we remove them |
|
91 | # (X)emacs on W32 gets confused with \001 and \002 so we remove them | |
92 | Normal = '\033[0m' # Reset normal coloring |
|
92 | Normal = '\033[0m' # Reset normal coloring | |
93 | _base = '\033[%sm' # Template for all other colors |
|
93 | _base = '\033[%sm' # Template for all other colors | |
94 | else: |
|
94 | else: | |
95 | Normal = '\001\033[0m\002' # Reset normal coloring |
|
95 | Normal = '\001\033[0m\002' # Reset normal coloring | |
96 | _base = '\001\033[%sm\002' # Template for all other colors |
|
96 | _base = '\001\033[%sm\002' # Template for all other colors | |
97 |
|
97 | |||
98 | # Build the actual color table as a set of class attributes: |
|
98 | # Build the actual color table as a set of class attributes: | |
99 | make_color_table(InputTermColors) |
|
99 | make_color_table(InputTermColors) | |
100 |
|
100 | |||
101 | class NoColors: |
|
101 | class NoColors: | |
102 | """This defines all the same names as the colour classes, but maps them to |
|
102 | """This defines all the same names as the colour classes, but maps them to | |
103 | empty strings, so it can easily be substituted to turn off colours.""" |
|
103 | empty strings, so it can easily be substituted to turn off colours.""" | |
104 | NoColor = '' |
|
104 | NoColor = '' | |
105 | Normal = '' |
|
105 | Normal = '' | |
106 |
|
106 | |||
107 | for name, value in color_templates: |
|
107 | for name, value in color_templates: | |
108 | setattr(NoColors, name, '') |
|
108 | setattr(NoColors, name, '') | |
109 |
|
109 | |||
110 | class ColorScheme: |
|
110 | class ColorScheme: | |
111 | """Generic color scheme class. Just a name and a Struct.""" |
|
111 | """Generic color scheme class. Just a name and a Struct.""" | |
112 | def __init__(self,__scheme_name_,colordict=None,**colormap): |
|
112 | def __init__(self,__scheme_name_,colordict=None,**colormap): | |
113 | self.name = __scheme_name_ |
|
113 | self.name = __scheme_name_ | |
114 | if colordict is None: |
|
114 | if colordict is None: | |
115 | self.colors = Struct(**colormap) |
|
115 | self.colors = Struct(**colormap) | |
116 | else: |
|
116 | else: | |
117 | self.colors = Struct(colordict) |
|
117 | self.colors = Struct(colordict) | |
118 |
|
118 | |||
119 | def copy(self,name=None): |
|
119 | def copy(self,name=None): | |
120 | """Return a full copy of the object, optionally renaming it.""" |
|
120 | """Return a full copy of the object, optionally renaming it.""" | |
121 | if name is None: |
|
121 | if name is None: | |
122 | name = self.name |
|
122 | name = self.name | |
123 | return ColorScheme(name, self.colors.dict()) |
|
123 | return ColorScheme(name, self.colors.dict()) | |
124 |
|
124 | |||
125 | class ColorSchemeTable(dict): |
|
125 | class ColorSchemeTable(dict): | |
126 | """General class to handle tables of color schemes. |
|
126 | """General class to handle tables of color schemes. | |
127 |
|
127 | |||
128 | It's basically a dict of color schemes with a couple of shorthand |
|
128 | It's basically a dict of color schemes with a couple of shorthand | |
129 | attributes and some convenient methods. |
|
129 | attributes and some convenient methods. | |
130 |
|
130 | |||
131 | active_scheme_name -> obvious |
|
131 | active_scheme_name -> obvious | |
132 | active_colors -> actual color table of the active scheme""" |
|
132 | active_colors -> actual color table of the active scheme""" | |
133 |
|
133 | |||
134 | def __init__(self,scheme_list=None,default_scheme=''): |
|
134 | def __init__(self,scheme_list=None,default_scheme=''): | |
135 | """Create a table of color schemes. |
|
135 | """Create a table of color schemes. | |
136 |
|
136 | |||
137 | The table can be created empty and manually filled or it can be |
|
137 | The table can be created empty and manually filled or it can be | |
138 | created with a list of valid color schemes AND the specification for |
|
138 | created with a list of valid color schemes AND the specification for | |
139 | the default active scheme. |
|
139 | the default active scheme. | |
140 | """ |
|
140 | """ | |
141 |
|
141 | |||
142 | # create object attributes to be set later |
|
142 | # create object attributes to be set later | |
143 | self.active_scheme_name = '' |
|
143 | self.active_scheme_name = '' | |
144 | self.active_colors = None |
|
144 | self.active_colors = None | |
145 |
|
145 | |||
146 | if scheme_list: |
|
146 | if scheme_list: | |
147 | if default_scheme == '': |
|
147 | if default_scheme == '': | |
148 |
raise ValueError |
|
148 | raise ValueError('you must specify the default color scheme') | |
149 | for scheme in scheme_list: |
|
149 | for scheme in scheme_list: | |
150 | self.add_scheme(scheme) |
|
150 | self.add_scheme(scheme) | |
151 | self.set_active_scheme(default_scheme) |
|
151 | self.set_active_scheme(default_scheme) | |
152 |
|
152 | |||
153 | def copy(self): |
|
153 | def copy(self): | |
154 | """Return full copy of object""" |
|
154 | """Return full copy of object""" | |
155 | return ColorSchemeTable(self.values(),self.active_scheme_name) |
|
155 | return ColorSchemeTable(self.values(),self.active_scheme_name) | |
156 |
|
156 | |||
157 | def add_scheme(self,new_scheme): |
|
157 | def add_scheme(self,new_scheme): | |
158 | """Add a new color scheme to the table.""" |
|
158 | """Add a new color scheme to the table.""" | |
159 | if not isinstance(new_scheme,ColorScheme): |
|
159 | if not isinstance(new_scheme,ColorScheme): | |
160 |
raise ValueError |
|
160 | raise ValueError('ColorSchemeTable only accepts ColorScheme instances') | |
161 | self[new_scheme.name] = new_scheme |
|
161 | self[new_scheme.name] = new_scheme | |
162 |
|
162 | |||
163 | def set_active_scheme(self,scheme,case_sensitive=0): |
|
163 | def set_active_scheme(self,scheme,case_sensitive=0): | |
164 | """Set the currently active scheme. |
|
164 | """Set the currently active scheme. | |
165 |
|
165 | |||
166 | Names are by default compared in a case-insensitive way, but this can |
|
166 | Names are by default compared in a case-insensitive way, but this can | |
167 | be changed by setting the parameter case_sensitive to true.""" |
|
167 | be changed by setting the parameter case_sensitive to true.""" | |
168 |
|
168 | |||
169 | scheme_names = self.keys() |
|
169 | scheme_names = self.keys() | |
170 | if case_sensitive: |
|
170 | if case_sensitive: | |
171 | valid_schemes = scheme_names |
|
171 | valid_schemes = scheme_names | |
172 | scheme_test = scheme |
|
172 | scheme_test = scheme | |
173 | else: |
|
173 | else: | |
174 | valid_schemes = [s.lower() for s in scheme_names] |
|
174 | valid_schemes = [s.lower() for s in scheme_names] | |
175 | scheme_test = scheme.lower() |
|
175 | scheme_test = scheme.lower() | |
176 | try: |
|
176 | try: | |
177 | scheme_idx = valid_schemes.index(scheme_test) |
|
177 | scheme_idx = valid_schemes.index(scheme_test) | |
178 | except ValueError: |
|
178 | except ValueError: | |
179 |
raise ValueError |
|
179 | raise ValueError('Unrecognized color scheme: ' + scheme + \ | |
180 | '\nValid schemes: '+str(scheme_names).replace("'', ",'') |
|
180 | '\nValid schemes: '+str(scheme_names).replace("'', ",'')) | |
181 | else: |
|
181 | else: | |
182 | active = scheme_names[scheme_idx] |
|
182 | active = scheme_names[scheme_idx] | |
183 | self.active_scheme_name = active |
|
183 | self.active_scheme_name = active | |
184 | self.active_colors = self[active].colors |
|
184 | self.active_colors = self[active].colors | |
185 | # Now allow using '' as an index for the current active scheme |
|
185 | # Now allow using '' as an index for the current active scheme | |
186 | self[''] = self[active] |
|
186 | self[''] = self[active] |
@@ -1,468 +1,468 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for path handling. |
|
3 | Utilities for path handling. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
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 | import os |
|
17 | import os | |
18 | import sys |
|
18 | import sys | |
19 | import tempfile |
|
19 | import tempfile | |
20 | import warnings |
|
20 | import warnings | |
21 | from hashlib import md5 |
|
21 | from hashlib import md5 | |
22 |
|
22 | |||
23 | import IPython |
|
23 | import IPython | |
24 | from IPython.testing.skipdoctest import skip_doctest |
|
24 | from IPython.testing.skipdoctest import skip_doctest | |
25 | from IPython.utils.process import system |
|
25 | from IPython.utils.process import system | |
26 | from IPython.utils.importstring import import_item |
|
26 | from IPython.utils.importstring import import_item | |
27 | from IPython.utils import py3compat |
|
27 | from IPython.utils import py3compat | |
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Code |
|
29 | # Code | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | fs_encoding = sys.getfilesystemencoding() |
|
32 | fs_encoding = sys.getfilesystemencoding() | |
33 |
|
33 | |||
34 | def _get_long_path_name(path): |
|
34 | def _get_long_path_name(path): | |
35 | """Dummy no-op.""" |
|
35 | """Dummy no-op.""" | |
36 | return path |
|
36 | return path | |
37 |
|
37 | |||
38 | def _writable_dir(path): |
|
38 | def _writable_dir(path): | |
39 | """Whether `path` is a directory, to which the user has write access.""" |
|
39 | """Whether `path` is a directory, to which the user has write access.""" | |
40 | return os.path.isdir(path) and os.access(path, os.W_OK) |
|
40 | return os.path.isdir(path) and os.access(path, os.W_OK) | |
41 |
|
41 | |||
42 | if sys.platform == 'win32': |
|
42 | if sys.platform == 'win32': | |
43 | @skip_doctest |
|
43 | @skip_doctest | |
44 | def _get_long_path_name(path): |
|
44 | def _get_long_path_name(path): | |
45 | """Get a long path name (expand ~) on Windows using ctypes. |
|
45 | """Get a long path name (expand ~) on Windows using ctypes. | |
46 |
|
46 | |||
47 | Examples |
|
47 | Examples | |
48 | -------- |
|
48 | -------- | |
49 |
|
49 | |||
50 | >>> get_long_path_name('c:\\docume~1') |
|
50 | >>> get_long_path_name('c:\\docume~1') | |
51 | u'c:\\\\Documents and Settings' |
|
51 | u'c:\\\\Documents and Settings' | |
52 |
|
52 | |||
53 | """ |
|
53 | """ | |
54 | try: |
|
54 | try: | |
55 | import ctypes |
|
55 | import ctypes | |
56 | except ImportError: |
|
56 | except ImportError: | |
57 | raise ImportError('you need to have ctypes installed for this to work') |
|
57 | raise ImportError('you need to have ctypes installed for this to work') | |
58 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
58 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW | |
59 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
59 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, | |
60 | ctypes.c_uint ] |
|
60 | ctypes.c_uint ] | |
61 |
|
61 | |||
62 | buf = ctypes.create_unicode_buffer(260) |
|
62 | buf = ctypes.create_unicode_buffer(260) | |
63 | rv = _GetLongPathName(path, buf, 260) |
|
63 | rv = _GetLongPathName(path, buf, 260) | |
64 | if rv == 0 or rv > 260: |
|
64 | if rv == 0 or rv > 260: | |
65 | return path |
|
65 | return path | |
66 | else: |
|
66 | else: | |
67 | return buf.value |
|
67 | return buf.value | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | def get_long_path_name(path): |
|
70 | def get_long_path_name(path): | |
71 | """Expand a path into its long form. |
|
71 | """Expand a path into its long form. | |
72 |
|
72 | |||
73 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
73 | On Windows this expands any ~ in the paths. On other platforms, it is | |
74 | a null operation. |
|
74 | a null operation. | |
75 | """ |
|
75 | """ | |
76 | return _get_long_path_name(path) |
|
76 | return _get_long_path_name(path) | |
77 |
|
77 | |||
78 |
|
78 | |||
79 | def unquote_filename(name, win32=(sys.platform=='win32')): |
|
79 | def unquote_filename(name, win32=(sys.platform=='win32')): | |
80 | """ On Windows, remove leading and trailing quotes from filenames. |
|
80 | """ On Windows, remove leading and trailing quotes from filenames. | |
81 | """ |
|
81 | """ | |
82 | if win32: |
|
82 | if win32: | |
83 | if name.startswith(("'", '"')) and name.endswith(("'", '"')): |
|
83 | if name.startswith(("'", '"')) and name.endswith(("'", '"')): | |
84 | name = name[1:-1] |
|
84 | name = name[1:-1] | |
85 | return name |
|
85 | return name | |
86 |
|
86 | |||
87 |
|
87 | |||
88 | def get_py_filename(name, force_win32=None): |
|
88 | def get_py_filename(name, force_win32=None): | |
89 | """Return a valid python filename in the current directory. |
|
89 | """Return a valid python filename in the current directory. | |
90 |
|
90 | |||
91 | If the given name is not a file, it adds '.py' and searches again. |
|
91 | If the given name is not a file, it adds '.py' and searches again. | |
92 | Raises IOError with an informative message if the file isn't found. |
|
92 | Raises IOError with an informative message if the file isn't found. | |
93 |
|
93 | |||
94 | On Windows, apply Windows semantics to the filename. In particular, remove |
|
94 | On Windows, apply Windows semantics to the filename. In particular, remove | |
95 | any quoting that has been applied to it. This option can be forced for |
|
95 | any quoting that has been applied to it. This option can be forced for | |
96 | testing purposes. |
|
96 | testing purposes. | |
97 | """ |
|
97 | """ | |
98 |
|
98 | |||
99 | name = os.path.expanduser(name) |
|
99 | name = os.path.expanduser(name) | |
100 | if force_win32 is None: |
|
100 | if force_win32 is None: | |
101 | win32 = (sys.platform == 'win32') |
|
101 | win32 = (sys.platform == 'win32') | |
102 | else: |
|
102 | else: | |
103 | win32 = force_win32 |
|
103 | win32 = force_win32 | |
104 | name = unquote_filename(name, win32=win32) |
|
104 | name = unquote_filename(name, win32=win32) | |
105 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
105 | if not os.path.isfile(name) and not name.endswith('.py'): | |
106 | name += '.py' |
|
106 | name += '.py' | |
107 | if os.path.isfile(name): |
|
107 | if os.path.isfile(name): | |
108 | return name |
|
108 | return name | |
109 | else: |
|
109 | else: | |
110 |
raise IOError |
|
110 | raise IOError('File `%r` not found.' % name) | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def filefind(filename, path_dirs=None): |
|
113 | def filefind(filename, path_dirs=None): | |
114 | """Find a file by looking through a sequence of paths. |
|
114 | """Find a file by looking through a sequence of paths. | |
115 |
|
115 | |||
116 | This iterates through a sequence of paths looking for a file and returns |
|
116 | This iterates through a sequence of paths looking for a file and returns | |
117 | the full, absolute path of the first occurence of the file. If no set of |
|
117 | the full, absolute path of the first occurence of the file. If no set of | |
118 | path dirs is given, the filename is tested as is, after running through |
|
118 | path dirs is given, the filename is tested as is, after running through | |
119 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
119 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: | |
120 |
|
120 | |||
121 | filefind('myfile.txt') |
|
121 | filefind('myfile.txt') | |
122 |
|
122 | |||
123 | will find the file in the current working dir, but:: |
|
123 | will find the file in the current working dir, but:: | |
124 |
|
124 | |||
125 | filefind('~/myfile.txt') |
|
125 | filefind('~/myfile.txt') | |
126 |
|
126 | |||
127 | Will find the file in the users home directory. This function does not |
|
127 | Will find the file in the users home directory. This function does not | |
128 | automatically try any paths, such as the cwd or the user's home directory. |
|
128 | automatically try any paths, such as the cwd or the user's home directory. | |
129 |
|
129 | |||
130 | Parameters |
|
130 | Parameters | |
131 | ---------- |
|
131 | ---------- | |
132 | filename : str |
|
132 | filename : str | |
133 | The filename to look for. |
|
133 | The filename to look for. | |
134 | path_dirs : str, None or sequence of str |
|
134 | path_dirs : str, None or sequence of str | |
135 | The sequence of paths to look for the file in. If None, the filename |
|
135 | The sequence of paths to look for the file in. If None, the filename | |
136 | need to be absolute or be in the cwd. If a string, the string is |
|
136 | need to be absolute or be in the cwd. If a string, the string is | |
137 | put into a sequence and the searched. If a sequence, walk through |
|
137 | put into a sequence and the searched. If a sequence, walk through | |
138 | each element and join with ``filename``, calling :func:`expandvars` |
|
138 | each element and join with ``filename``, calling :func:`expandvars` | |
139 | and :func:`expanduser` before testing for existence. |
|
139 | and :func:`expanduser` before testing for existence. | |
140 |
|
140 | |||
141 | Returns |
|
141 | Returns | |
142 | ------- |
|
142 | ------- | |
143 | Raises :exc:`IOError` or returns absolute path to file. |
|
143 | Raises :exc:`IOError` or returns absolute path to file. | |
144 | """ |
|
144 | """ | |
145 |
|
145 | |||
146 | # If paths are quoted, abspath gets confused, strip them... |
|
146 | # If paths are quoted, abspath gets confused, strip them... | |
147 | filename = filename.strip('"').strip("'") |
|
147 | filename = filename.strip('"').strip("'") | |
148 | # If the input is an absolute path, just check it exists |
|
148 | # If the input is an absolute path, just check it exists | |
149 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
149 | if os.path.isabs(filename) and os.path.isfile(filename): | |
150 | return filename |
|
150 | return filename | |
151 |
|
151 | |||
152 | if path_dirs is None: |
|
152 | if path_dirs is None: | |
153 | path_dirs = ("",) |
|
153 | path_dirs = ("",) | |
154 | elif isinstance(path_dirs, basestring): |
|
154 | elif isinstance(path_dirs, basestring): | |
155 | path_dirs = (path_dirs,) |
|
155 | path_dirs = (path_dirs,) | |
156 |
|
156 | |||
157 | for path in path_dirs: |
|
157 | for path in path_dirs: | |
158 | if path == '.': path = os.getcwdu() |
|
158 | if path == '.': path = os.getcwdu() | |
159 | testname = expand_path(os.path.join(path, filename)) |
|
159 | testname = expand_path(os.path.join(path, filename)) | |
160 | if os.path.isfile(testname): |
|
160 | if os.path.isfile(testname): | |
161 | return os.path.abspath(testname) |
|
161 | return os.path.abspath(testname) | |
162 |
|
162 | |||
163 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
163 | raise IOError("File %r does not exist in any of the search paths: %r" % | |
164 | (filename, path_dirs) ) |
|
164 | (filename, path_dirs) ) | |
165 |
|
165 | |||
166 |
|
166 | |||
167 | class HomeDirError(Exception): |
|
167 | class HomeDirError(Exception): | |
168 | pass |
|
168 | pass | |
169 |
|
169 | |||
170 |
|
170 | |||
171 | def get_home_dir(require_writable=False): |
|
171 | def get_home_dir(require_writable=False): | |
172 | """Return the 'home' directory, as a unicode string. |
|
172 | """Return the 'home' directory, as a unicode string. | |
173 |
|
173 | |||
174 | * First, check for frozen env in case of py2exe |
|
174 | * First, check for frozen env in case of py2exe | |
175 | * Otherwise, defer to os.path.expanduser('~') |
|
175 | * Otherwise, defer to os.path.expanduser('~') | |
176 |
|
176 | |||
177 | See stdlib docs for how this is determined. |
|
177 | See stdlib docs for how this is determined. | |
178 | $HOME is first priority on *ALL* platforms. |
|
178 | $HOME is first priority on *ALL* platforms. | |
179 |
|
179 | |||
180 | Parameters |
|
180 | Parameters | |
181 | ---------- |
|
181 | ---------- | |
182 |
|
182 | |||
183 | require_writable : bool [default: False] |
|
183 | require_writable : bool [default: False] | |
184 | if True: |
|
184 | if True: | |
185 | guarantees the return value is a writable directory, otherwise |
|
185 | guarantees the return value is a writable directory, otherwise | |
186 | raises HomeDirError |
|
186 | raises HomeDirError | |
187 | if False: |
|
187 | if False: | |
188 | The path is resolved, but it is not guaranteed to exist or be writable. |
|
188 | The path is resolved, but it is not guaranteed to exist or be writable. | |
189 | """ |
|
189 | """ | |
190 |
|
190 | |||
191 | # first, check py2exe distribution root directory for _ipython. |
|
191 | # first, check py2exe distribution root directory for _ipython. | |
192 | # This overrides all. Normally does not exist. |
|
192 | # This overrides all. Normally does not exist. | |
193 |
|
193 | |||
194 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
194 | if hasattr(sys, "frozen"): #Is frozen by py2exe | |
195 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
195 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file | |
196 | root, rest = IPython.__file__.lower().split('library.zip') |
|
196 | root, rest = IPython.__file__.lower().split('library.zip') | |
197 | else: |
|
197 | else: | |
198 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
198 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") | |
199 | root=os.path.abspath(root).rstrip('\\') |
|
199 | root=os.path.abspath(root).rstrip('\\') | |
200 | if _writable_dir(os.path.join(root, '_ipython')): |
|
200 | if _writable_dir(os.path.join(root, '_ipython')): | |
201 | os.environ["IPYKITROOT"] = root |
|
201 | os.environ["IPYKITROOT"] = root | |
202 | return py3compat.cast_unicode(root, fs_encoding) |
|
202 | return py3compat.cast_unicode(root, fs_encoding) | |
203 |
|
203 | |||
204 | homedir = os.path.expanduser('~') |
|
204 | homedir = os.path.expanduser('~') | |
205 | # Next line will make things work even when /home/ is a symlink to |
|
205 | # Next line will make things work even when /home/ is a symlink to | |
206 | # /usr/home as it is on FreeBSD, for example |
|
206 | # /usr/home as it is on FreeBSD, for example | |
207 | homedir = os.path.realpath(homedir) |
|
207 | homedir = os.path.realpath(homedir) | |
208 |
|
208 | |||
209 | if not _writable_dir(homedir) and os.name == 'nt': |
|
209 | if not _writable_dir(homedir) and os.name == 'nt': | |
210 | # expanduser failed, use the registry to get the 'My Documents' folder. |
|
210 | # expanduser failed, use the registry to get the 'My Documents' folder. | |
211 | try: |
|
211 | try: | |
212 | import _winreg as wreg |
|
212 | import _winreg as wreg | |
213 | key = wreg.OpenKey( |
|
213 | key = wreg.OpenKey( | |
214 | wreg.HKEY_CURRENT_USER, |
|
214 | wreg.HKEY_CURRENT_USER, | |
215 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
215 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" | |
216 | ) |
|
216 | ) | |
217 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
217 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
218 | key.Close() |
|
218 | key.Close() | |
219 | except: |
|
219 | except: | |
220 | pass |
|
220 | pass | |
221 |
|
221 | |||
222 | if (not require_writable) or _writable_dir(homedir): |
|
222 | if (not require_writable) or _writable_dir(homedir): | |
223 | return py3compat.cast_unicode(homedir, fs_encoding) |
|
223 | return py3compat.cast_unicode(homedir, fs_encoding) | |
224 | else: |
|
224 | else: | |
225 | raise HomeDirError('%s is not a writable dir, ' |
|
225 | raise HomeDirError('%s is not a writable dir, ' | |
226 | 'set $HOME environment variable to override' % homedir) |
|
226 | 'set $HOME environment variable to override' % homedir) | |
227 |
|
227 | |||
228 | def get_xdg_dir(): |
|
228 | def get_xdg_dir(): | |
229 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. |
|
229 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. | |
230 |
|
230 | |||
231 | This is only for non-OS X posix (Linux,Unix,etc.) systems. |
|
231 | This is only for non-OS X posix (Linux,Unix,etc.) systems. | |
232 | """ |
|
232 | """ | |
233 |
|
233 | |||
234 | env = os.environ |
|
234 | env = os.environ | |
235 |
|
235 | |||
236 | if os.name == 'posix' and sys.platform != 'darwin': |
|
236 | if os.name == 'posix' and sys.platform != 'darwin': | |
237 | # Linux, Unix, AIX, etc. |
|
237 | # Linux, Unix, AIX, etc. | |
238 | # use ~/.config if empty OR not set |
|
238 | # use ~/.config if empty OR not set | |
239 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') |
|
239 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') | |
240 | if xdg and _writable_dir(xdg): |
|
240 | if xdg and _writable_dir(xdg): | |
241 | return py3compat.cast_unicode(xdg, fs_encoding) |
|
241 | return py3compat.cast_unicode(xdg, fs_encoding) | |
242 |
|
242 | |||
243 | return None |
|
243 | return None | |
244 |
|
244 | |||
245 |
|
245 | |||
246 | def get_ipython_dir(): |
|
246 | def get_ipython_dir(): | |
247 | """Get the IPython directory for this platform and user. |
|
247 | """Get the IPython directory for this platform and user. | |
248 |
|
248 | |||
249 | This uses the logic in `get_home_dir` to find the home directory |
|
249 | This uses the logic in `get_home_dir` to find the home directory | |
250 | and then adds .ipython to the end of the path. |
|
250 | and then adds .ipython to the end of the path. | |
251 | """ |
|
251 | """ | |
252 |
|
252 | |||
253 | env = os.environ |
|
253 | env = os.environ | |
254 | pjoin = os.path.join |
|
254 | pjoin = os.path.join | |
255 |
|
255 | |||
256 |
|
256 | |||
257 | ipdir_def = '.ipython' |
|
257 | ipdir_def = '.ipython' | |
258 | xdg_def = 'ipython' |
|
258 | xdg_def = 'ipython' | |
259 |
|
259 | |||
260 | home_dir = get_home_dir() |
|
260 | home_dir = get_home_dir() | |
261 | xdg_dir = get_xdg_dir() |
|
261 | xdg_dir = get_xdg_dir() | |
262 |
|
262 | |||
263 | # import pdb; pdb.set_trace() # dbg |
|
263 | # import pdb; pdb.set_trace() # dbg | |
264 | if 'IPYTHON_DIR' in env: |
|
264 | if 'IPYTHON_DIR' in env: | |
265 | warnings.warn('The environment variable IPYTHON_DIR is deprecated. ' |
|
265 | warnings.warn('The environment variable IPYTHON_DIR is deprecated. ' | |
266 | 'Please use IPYTHONDIR instead.') |
|
266 | 'Please use IPYTHONDIR instead.') | |
267 | ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None)) |
|
267 | ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None)) | |
268 | if ipdir is None: |
|
268 | if ipdir is None: | |
269 | # not set explicitly, use XDG_CONFIG_HOME or HOME |
|
269 | # not set explicitly, use XDG_CONFIG_HOME or HOME | |
270 | home_ipdir = pjoin(home_dir, ipdir_def) |
|
270 | home_ipdir = pjoin(home_dir, ipdir_def) | |
271 | if xdg_dir: |
|
271 | if xdg_dir: | |
272 | # use XDG, as long as the user isn't already |
|
272 | # use XDG, as long as the user isn't already | |
273 | # using $HOME/.ipython and *not* XDG/ipython |
|
273 | # using $HOME/.ipython and *not* XDG/ipython | |
274 |
|
274 | |||
275 | xdg_ipdir = pjoin(xdg_dir, xdg_def) |
|
275 | xdg_ipdir = pjoin(xdg_dir, xdg_def) | |
276 |
|
276 | |||
277 | if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir): |
|
277 | if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir): | |
278 | ipdir = xdg_ipdir |
|
278 | ipdir = xdg_ipdir | |
279 |
|
279 | |||
280 | if ipdir is None: |
|
280 | if ipdir is None: | |
281 | # not using XDG |
|
281 | # not using XDG | |
282 | ipdir = home_ipdir |
|
282 | ipdir = home_ipdir | |
283 |
|
283 | |||
284 | ipdir = os.path.normpath(os.path.expanduser(ipdir)) |
|
284 | ipdir = os.path.normpath(os.path.expanduser(ipdir)) | |
285 |
|
285 | |||
286 | if os.path.exists(ipdir) and not _writable_dir(ipdir): |
|
286 | if os.path.exists(ipdir) and not _writable_dir(ipdir): | |
287 | # ipdir exists, but is not writable |
|
287 | # ipdir exists, but is not writable | |
288 | warnings.warn("IPython dir '%s' is not a writable location," |
|
288 | warnings.warn("IPython dir '%s' is not a writable location," | |
289 | " using a temp directory."%ipdir) |
|
289 | " using a temp directory."%ipdir) | |
290 | ipdir = tempfile.mkdtemp() |
|
290 | ipdir = tempfile.mkdtemp() | |
291 | elif not os.path.exists(ipdir): |
|
291 | elif not os.path.exists(ipdir): | |
292 | parent = ipdir.rsplit(os.path.sep, 1)[0] |
|
292 | parent = ipdir.rsplit(os.path.sep, 1)[0] | |
293 | if not _writable_dir(parent): |
|
293 | if not _writable_dir(parent): | |
294 | # ipdir does not exist and parent isn't writable |
|
294 | # ipdir does not exist and parent isn't writable | |
295 | warnings.warn("IPython parent '%s' is not a writable location," |
|
295 | warnings.warn("IPython parent '%s' is not a writable location," | |
296 | " using a temp directory."%parent) |
|
296 | " using a temp directory."%parent) | |
297 | ipdir = tempfile.mkdtemp() |
|
297 | ipdir = tempfile.mkdtemp() | |
298 |
|
298 | |||
299 | return py3compat.cast_unicode(ipdir, fs_encoding) |
|
299 | return py3compat.cast_unicode(ipdir, fs_encoding) | |
300 |
|
300 | |||
301 |
|
301 | |||
302 | def get_ipython_package_dir(): |
|
302 | def get_ipython_package_dir(): | |
303 | """Get the base directory where IPython itself is installed.""" |
|
303 | """Get the base directory where IPython itself is installed.""" | |
304 | ipdir = os.path.dirname(IPython.__file__) |
|
304 | ipdir = os.path.dirname(IPython.__file__) | |
305 | return py3compat.cast_unicode(ipdir, fs_encoding) |
|
305 | return py3compat.cast_unicode(ipdir, fs_encoding) | |
306 |
|
306 | |||
307 |
|
307 | |||
308 | def get_ipython_module_path(module_str): |
|
308 | def get_ipython_module_path(module_str): | |
309 | """Find the path to an IPython module in this version of IPython. |
|
309 | """Find the path to an IPython module in this version of IPython. | |
310 |
|
310 | |||
311 | This will always find the version of the module that is in this importable |
|
311 | This will always find the version of the module that is in this importable | |
312 | IPython package. This will always return the path to the ``.py`` |
|
312 | IPython package. This will always return the path to the ``.py`` | |
313 | version of the module. |
|
313 | version of the module. | |
314 | """ |
|
314 | """ | |
315 | if module_str == 'IPython': |
|
315 | if module_str == 'IPython': | |
316 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
316 | return os.path.join(get_ipython_package_dir(), '__init__.py') | |
317 | mod = import_item(module_str) |
|
317 | mod = import_item(module_str) | |
318 | the_path = mod.__file__.replace('.pyc', '.py') |
|
318 | the_path = mod.__file__.replace('.pyc', '.py') | |
319 | the_path = the_path.replace('.pyo', '.py') |
|
319 | the_path = the_path.replace('.pyo', '.py') | |
320 | return py3compat.cast_unicode(the_path, fs_encoding) |
|
320 | return py3compat.cast_unicode(the_path, fs_encoding) | |
321 |
|
321 | |||
322 | def locate_profile(profile='default'): |
|
322 | def locate_profile(profile='default'): | |
323 | """Find the path to the folder associated with a given profile. |
|
323 | """Find the path to the folder associated with a given profile. | |
324 |
|
324 | |||
325 | I.e. find $IPYTHONDIR/profile_whatever. |
|
325 | I.e. find $IPYTHONDIR/profile_whatever. | |
326 | """ |
|
326 | """ | |
327 | from IPython.core.profiledir import ProfileDir, ProfileDirError |
|
327 | from IPython.core.profiledir import ProfileDir, ProfileDirError | |
328 | try: |
|
328 | try: | |
329 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) |
|
329 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) | |
330 | except ProfileDirError: |
|
330 | except ProfileDirError: | |
331 | # IOError makes more sense when people are expecting a path |
|
331 | # IOError makes more sense when people are expecting a path | |
332 | raise IOError("Couldn't find profile %r" % profile) |
|
332 | raise IOError("Couldn't find profile %r" % profile) | |
333 | return pd.location |
|
333 | return pd.location | |
334 |
|
334 | |||
335 | def expand_path(s): |
|
335 | def expand_path(s): | |
336 | """Expand $VARS and ~names in a string, like a shell |
|
336 | """Expand $VARS and ~names in a string, like a shell | |
337 |
|
337 | |||
338 | :Examples: |
|
338 | :Examples: | |
339 |
|
339 | |||
340 | In [2]: os.environ['FOO']='test' |
|
340 | In [2]: os.environ['FOO']='test' | |
341 |
|
341 | |||
342 | In [3]: expand_path('variable FOO is $FOO') |
|
342 | In [3]: expand_path('variable FOO is $FOO') | |
343 | Out[3]: 'variable FOO is test' |
|
343 | Out[3]: 'variable FOO is test' | |
344 | """ |
|
344 | """ | |
345 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
345 | # This is a pretty subtle hack. When expand user is given a UNC path | |
346 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
346 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes | |
347 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
347 | # the $ to get (\\server\share\%username%). I think it considered $ | |
348 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
348 | # alone an empty var. But, we need the $ to remains there (it indicates | |
349 | # a hidden share). |
|
349 | # a hidden share). | |
350 | if os.name=='nt': |
|
350 | if os.name=='nt': | |
351 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
351 | s = s.replace('$\\', 'IPYTHON_TEMP') | |
352 | s = os.path.expandvars(os.path.expanduser(s)) |
|
352 | s = os.path.expandvars(os.path.expanduser(s)) | |
353 | if os.name=='nt': |
|
353 | if os.name=='nt': | |
354 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
354 | s = s.replace('IPYTHON_TEMP', '$\\') | |
355 | return s |
|
355 | return s | |
356 |
|
356 | |||
357 |
|
357 | |||
358 | def target_outdated(target,deps): |
|
358 | def target_outdated(target,deps): | |
359 | """Determine whether a target is out of date. |
|
359 | """Determine whether a target is out of date. | |
360 |
|
360 | |||
361 | target_outdated(target,deps) -> 1/0 |
|
361 | target_outdated(target,deps) -> 1/0 | |
362 |
|
362 | |||
363 | deps: list of filenames which MUST exist. |
|
363 | deps: list of filenames which MUST exist. | |
364 | target: single filename which may or may not exist. |
|
364 | target: single filename which may or may not exist. | |
365 |
|
365 | |||
366 | If target doesn't exist or is older than any file listed in deps, return |
|
366 | If target doesn't exist or is older than any file listed in deps, return | |
367 | true, otherwise return false. |
|
367 | true, otherwise return false. | |
368 | """ |
|
368 | """ | |
369 | try: |
|
369 | try: | |
370 | target_time = os.path.getmtime(target) |
|
370 | target_time = os.path.getmtime(target) | |
371 | except os.error: |
|
371 | except os.error: | |
372 | return 1 |
|
372 | return 1 | |
373 | for dep in deps: |
|
373 | for dep in deps: | |
374 | dep_time = os.path.getmtime(dep) |
|
374 | dep_time = os.path.getmtime(dep) | |
375 | if dep_time > target_time: |
|
375 | if dep_time > target_time: | |
376 | #print "For target",target,"Dep failed:",dep # dbg |
|
376 | #print "For target",target,"Dep failed:",dep # dbg | |
377 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
377 | #print "times (dep,tar):",dep_time,target_time # dbg | |
378 | return 1 |
|
378 | return 1 | |
379 | return 0 |
|
379 | return 0 | |
380 |
|
380 | |||
381 |
|
381 | |||
382 | def target_update(target,deps,cmd): |
|
382 | def target_update(target,deps,cmd): | |
383 | """Update a target with a given command given a list of dependencies. |
|
383 | """Update a target with a given command given a list of dependencies. | |
384 |
|
384 | |||
385 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
385 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
386 |
|
386 | |||
387 | This is just a wrapper around target_outdated() which calls the given |
|
387 | This is just a wrapper around target_outdated() which calls the given | |
388 | command if target is outdated.""" |
|
388 | command if target is outdated.""" | |
389 |
|
389 | |||
390 | if target_outdated(target,deps): |
|
390 | if target_outdated(target,deps): | |
391 | system(cmd) |
|
391 | system(cmd) | |
392 |
|
392 | |||
393 | def filehash(path): |
|
393 | def filehash(path): | |
394 | """Make an MD5 hash of a file, ignoring any differences in line |
|
394 | """Make an MD5 hash of a file, ignoring any differences in line | |
395 | ending characters.""" |
|
395 | ending characters.""" | |
396 | with open(path, "rU") as f: |
|
396 | with open(path, "rU") as f: | |
397 | return md5(py3compat.str_to_bytes(f.read())).hexdigest() |
|
397 | return md5(py3compat.str_to_bytes(f.read())).hexdigest() | |
398 |
|
398 | |||
399 | # If the config is unmodified from the default, we'll just delete it. |
|
399 | # If the config is unmodified from the default, we'll just delete it. | |
400 | # These are consistent for 0.10.x, thankfully. We're not going to worry about |
|
400 | # These are consistent for 0.10.x, thankfully. We're not going to worry about | |
401 | # older versions. |
|
401 | # older versions. | |
402 | old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3', |
|
402 | old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3', | |
403 | 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'} |
|
403 | 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'} | |
404 |
|
404 | |||
405 | def check_for_old_config(ipython_dir=None): |
|
405 | def check_for_old_config(ipython_dir=None): | |
406 | """Check for old config files, and present a warning if they exist. |
|
406 | """Check for old config files, and present a warning if they exist. | |
407 |
|
407 | |||
408 | A link to the docs of the new config is included in the message. |
|
408 | A link to the docs of the new config is included in the message. | |
409 |
|
409 | |||
410 | This should mitigate confusion with the transition to the new |
|
410 | This should mitigate confusion with the transition to the new | |
411 | config system in 0.11. |
|
411 | config system in 0.11. | |
412 | """ |
|
412 | """ | |
413 | if ipython_dir is None: |
|
413 | if ipython_dir is None: | |
414 | ipython_dir = get_ipython_dir() |
|
414 | ipython_dir = get_ipython_dir() | |
415 |
|
415 | |||
416 | old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py'] |
|
416 | old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py'] | |
417 | warned = False |
|
417 | warned = False | |
418 | for cfg in old_configs: |
|
418 | for cfg in old_configs: | |
419 | f = os.path.join(ipython_dir, cfg) |
|
419 | f = os.path.join(ipython_dir, cfg) | |
420 | if os.path.exists(f): |
|
420 | if os.path.exists(f): | |
421 | if filehash(f) == old_config_md5.get(cfg, ''): |
|
421 | if filehash(f) == old_config_md5.get(cfg, ''): | |
422 | os.unlink(f) |
|
422 | os.unlink(f) | |
423 | else: |
|
423 | else: | |
424 | warnings.warn("Found old IPython config file %r (modified by user)"%f) |
|
424 | warnings.warn("Found old IPython config file %r (modified by user)"%f) | |
425 | warned = True |
|
425 | warned = True | |
426 |
|
426 | |||
427 | if warned: |
|
427 | if warned: | |
428 | warnings.warn(""" |
|
428 | warnings.warn(""" | |
429 | The IPython configuration system has changed as of 0.11, and these files will |
|
429 | The IPython configuration system has changed as of 0.11, and these files will | |
430 | be ignored. See http://ipython.github.com/ipython-doc/dev/config for details |
|
430 | be ignored. See http://ipython.github.com/ipython-doc/dev/config for details | |
431 | of the new config system. |
|
431 | of the new config system. | |
432 | To start configuring IPython, do `ipython profile create`, and edit |
|
432 | To start configuring IPython, do `ipython profile create`, and edit | |
433 | `ipython_config.py` in <ipython_dir>/profile_default. |
|
433 | `ipython_config.py` in <ipython_dir>/profile_default. | |
434 | If you need to leave the old config files in place for an older version of |
|
434 | If you need to leave the old config files in place for an older version of | |
435 | IPython and want to suppress this warning message, set |
|
435 | IPython and want to suppress this warning message, set | |
436 | `c.InteractiveShellApp.ignore_old_config=True` in the new config.""") |
|
436 | `c.InteractiveShellApp.ignore_old_config=True` in the new config.""") | |
437 |
|
437 | |||
438 | def get_security_file(filename, profile='default'): |
|
438 | def get_security_file(filename, profile='default'): | |
439 | """Return the absolute path of a security file given by filename and profile |
|
439 | """Return the absolute path of a security file given by filename and profile | |
440 |
|
440 | |||
441 | This allows users and developers to find security files without |
|
441 | This allows users and developers to find security files without | |
442 | knowledge of the IPython directory structure. The search path |
|
442 | knowledge of the IPython directory structure. The search path | |
443 | will be ['.', profile.security_dir] |
|
443 | will be ['.', profile.security_dir] | |
444 |
|
444 | |||
445 | Parameters |
|
445 | Parameters | |
446 | ---------- |
|
446 | ---------- | |
447 |
|
447 | |||
448 | filename : str |
|
448 | filename : str | |
449 | The file to be found. If it is passed as an absolute path, it will |
|
449 | The file to be found. If it is passed as an absolute path, it will | |
450 | simply be returned. |
|
450 | simply be returned. | |
451 | profile : str [default: 'default'] |
|
451 | profile : str [default: 'default'] | |
452 | The name of the profile to search. Leaving this unspecified |
|
452 | The name of the profile to search. Leaving this unspecified | |
453 | The file to be found. If it is passed as an absolute path, fname will |
|
453 | The file to be found. If it is passed as an absolute path, fname will | |
454 | simply be returned. |
|
454 | simply be returned. | |
455 |
|
455 | |||
456 | Returns |
|
456 | Returns | |
457 | ------- |
|
457 | ------- | |
458 | Raises :exc:`IOError` if file not found or returns absolute path to file. |
|
458 | Raises :exc:`IOError` if file not found or returns absolute path to file. | |
459 | """ |
|
459 | """ | |
460 | # import here, because profiledir also imports from utils.path |
|
460 | # import here, because profiledir also imports from utils.path | |
461 | from IPython.core.profiledir import ProfileDir |
|
461 | from IPython.core.profiledir import ProfileDir | |
462 | try: |
|
462 | try: | |
463 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) |
|
463 | pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) | |
464 | except Exception: |
|
464 | except Exception: | |
465 | # will raise ProfileDirError if no such profile |
|
465 | # will raise ProfileDirError if no such profile | |
466 | raise IOError("Profile %r not found") |
|
466 | raise IOError("Profile %r not found") | |
467 | return filefind(filename, ['.', pd.security_dir]) |
|
467 | return filefind(filename, ['.', pd.security_dir]) | |
468 |
|
468 |
General Comments 0
You need to be logged in to leave comments.
Login now