Show More
1 | NO CONTENT: modified file chmod 100644 => 100755 |
|
NO CONTENT: modified file chmod 100644 => 100755 |
@@ -1,292 +1,297 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Fernando Perez |
|
6 | * Fernando Perez | |
7 | * Brian Granger |
|
7 | * Brian Granger | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2010 The IPython Development Team |
|
11 | # Copyright (C) 2008-2010 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | from pprint import PrettyPrinter |
|
23 | from pprint import PrettyPrinter | |
24 | pformat = PrettyPrinter().pformat |
|
24 | pformat = PrettyPrinter().pformat | |
25 |
|
25 | |||
26 | from IPython.config.configurable import Configurable |
|
26 | from IPython.config.configurable import Configurable | |
27 | from IPython.core import prompts |
|
27 | from IPython.core import prompts | |
28 | import IPython.utils.generics |
|
28 | import IPython.utils.generics | |
29 | import IPython.utils.io |
|
29 | import IPython.utils.io | |
30 | from IPython.utils.traitlets import Instance, Int |
|
30 | from IPython.utils.traitlets import Instance, Int | |
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: The DisplayHook class should be split into two classes, one that |
|
37 | # TODO: The DisplayHook class should be split into two classes, one that | |
38 | # manages the prompts and their synchronization and another that just does the |
|
38 | # manages the prompts and their synchronization and another that just does the | |
39 | # displayhook logic and calls into the prompt manager. |
|
39 | # displayhook logic and calls into the prompt manager. | |
40 |
|
40 | |||
41 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
41 | # TODO: Move the various attributes (cache_size, colors, input_sep, | |
42 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
42 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also | |
43 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
43 | # attributes of InteractiveShell. They should be on ONE object only and the | |
44 | # other objects should ask that one object for their values. |
|
44 | # other objects should ask that one object for their values. | |
45 |
|
45 | |||
46 | class DisplayHook(Configurable): |
|
46 | class DisplayHook(Configurable): | |
47 | """The custom IPython displayhook to replace sys.displayhook. |
|
47 | """The custom IPython displayhook to replace sys.displayhook. | |
48 |
|
48 | |||
49 | This class does many things, but the basic idea is that it is a callable |
|
49 | This class does many things, but the basic idea is that it is a callable | |
50 | that gets called anytime user code returns a value. |
|
50 | that gets called anytime user code returns a value. | |
51 |
|
51 | |||
52 | Currently this class does more than just the displayhook logic and that |
|
52 | Currently this class does more than just the displayhook logic and that | |
53 | extra logic should eventually be moved out of here. |
|
53 | extra logic should eventually be moved out of here. | |
54 | """ |
|
54 | """ | |
55 |
|
55 | |||
56 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
56 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
|
57 | ||||
57 | # Each call to the In[] prompt raises it by 1, even the first. |
|
58 | # Each call to the In[] prompt raises it by 1, even the first. | |
58 | prompt_count = Int(0) |
|
59 | #prompt_count = Int(0) | |
59 |
|
60 | |||
60 | def __init__(self, shell=None, cache_size=1000, |
|
61 | def __init__(self, shell=None, cache_size=1000, | |
61 | colors='NoColor', input_sep='\n', |
|
62 | colors='NoColor', input_sep='\n', | |
62 | output_sep='\n', output_sep2='', |
|
63 | output_sep='\n', output_sep2='', | |
63 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
64 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, | |
64 | config=None): |
|
65 | config=None): | |
65 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
66 | super(DisplayHook, self).__init__(shell=shell, config=config) | |
66 |
|
67 | |||
67 | cache_size_min = 3 |
|
68 | cache_size_min = 3 | |
68 | if cache_size <= 0: |
|
69 | if cache_size <= 0: | |
69 | self.do_full_cache = 0 |
|
70 | self.do_full_cache = 0 | |
70 | cache_size = 0 |
|
71 | cache_size = 0 | |
71 | elif cache_size < cache_size_min: |
|
72 | elif cache_size < cache_size_min: | |
72 | self.do_full_cache = 0 |
|
73 | self.do_full_cache = 0 | |
73 | cache_size = 0 |
|
74 | cache_size = 0 | |
74 | warn('caching was disabled (min value for cache size is %s).' % |
|
75 | warn('caching was disabled (min value for cache size is %s).' % | |
75 | cache_size_min,level=3) |
|
76 | cache_size_min,level=3) | |
76 | else: |
|
77 | else: | |
77 | self.do_full_cache = 1 |
|
78 | self.do_full_cache = 1 | |
78 |
|
79 | |||
79 | self.cache_size = cache_size |
|
80 | self.cache_size = cache_size | |
80 | self.input_sep = input_sep |
|
81 | self.input_sep = input_sep | |
81 |
|
82 | |||
82 | # we need a reference to the user-level namespace |
|
83 | # we need a reference to the user-level namespace | |
83 | self.shell = shell |
|
84 | self.shell = shell | |
84 |
|
85 | |||
85 | # Set input prompt strings and colors |
|
86 | # Set input prompt strings and colors | |
86 | if cache_size == 0: |
|
87 | if cache_size == 0: | |
87 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
88 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ | |
88 | or ps1.find(r'\N') > -1: |
|
89 | or ps1.find(r'\N') > -1: | |
89 | ps1 = '>>> ' |
|
90 | ps1 = '>>> ' | |
90 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
91 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ | |
91 | or ps2.find(r'\N') > -1: |
|
92 | or ps2.find(r'\N') > -1: | |
92 | ps2 = '... ' |
|
93 | ps2 = '... ' | |
93 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
94 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') | |
94 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
95 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') | |
95 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
96 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') | |
96 |
|
97 | |||
97 | self.color_table = prompts.PromptColors |
|
98 | self.color_table = prompts.PromptColors | |
98 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
99 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, | |
99 | pad_left=pad_left) |
|
100 | pad_left=pad_left) | |
100 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
101 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) | |
101 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
102 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, | |
102 | pad_left=pad_left) |
|
103 | pad_left=pad_left) | |
103 | self.set_colors(colors) |
|
104 | self.set_colors(colors) | |
104 |
|
105 | |||
105 | # Store the last prompt string each time, we need it for aligning |
|
106 | # Store the last prompt string each time, we need it for aligning | |
106 | # continuation and auto-rewrite prompts |
|
107 | # continuation and auto-rewrite prompts | |
107 | self.last_prompt = '' |
|
108 | self.last_prompt = '' | |
108 | self.output_sep = output_sep |
|
109 | self.output_sep = output_sep | |
109 | self.output_sep2 = output_sep2 |
|
110 | self.output_sep2 = output_sep2 | |
110 | self._,self.__,self.___ = '','','' |
|
111 | self._,self.__,self.___ = '','','' | |
111 | self.pprint_types = map(type,[(),[],{}]) |
|
112 | self.pprint_types = map(type,[(),[],{}]) | |
112 |
|
113 | |||
113 | # these are deliberately global: |
|
114 | # these are deliberately global: | |
114 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
115 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
115 | self.shell.user_ns.update(to_user_ns) |
|
116 | self.shell.user_ns.update(to_user_ns) | |
116 |
|
117 | |||
|
118 | @property | |||
|
119 | def prompt_count(self): | |||
|
120 | return self.shell.execution_count | |||
|
121 | ||||
117 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
122 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): | |
118 | if p_str is None: |
|
123 | if p_str is None: | |
119 | if self.do_full_cache: |
|
124 | if self.do_full_cache: | |
120 | return cache_def |
|
125 | return cache_def | |
121 | else: |
|
126 | else: | |
122 | return no_cache_def |
|
127 | return no_cache_def | |
123 | else: |
|
128 | else: | |
124 | return p_str |
|
129 | return p_str | |
125 |
|
130 | |||
126 | def set_colors(self, colors): |
|
131 | def set_colors(self, colors): | |
127 | """Set the active color scheme and configure colors for the three |
|
132 | """Set the active color scheme and configure colors for the three | |
128 | prompt subsystems.""" |
|
133 | prompt subsystems.""" | |
129 |
|
134 | |||
130 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
135 | # FIXME: This modifying of the global prompts.prompt_specials needs | |
131 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
136 | # to be fixed. We need to refactor all of the prompts stuff to use | |
132 | # proper configuration and traits notifications. |
|
137 | # proper configuration and traits notifications. | |
133 | if colors.lower()=='nocolor': |
|
138 | if colors.lower()=='nocolor': | |
134 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
139 | prompts.prompt_specials = prompts.prompt_specials_nocolor | |
135 | else: |
|
140 | else: | |
136 | prompts.prompt_specials = prompts.prompt_specials_color |
|
141 | prompts.prompt_specials = prompts.prompt_specials_color | |
137 |
|
142 | |||
138 | self.color_table.set_active_scheme(colors) |
|
143 | self.color_table.set_active_scheme(colors) | |
139 | self.prompt1.set_colors() |
|
144 | self.prompt1.set_colors() | |
140 | self.prompt2.set_colors() |
|
145 | self.prompt2.set_colors() | |
141 | self.prompt_out.set_colors() |
|
146 | self.prompt_out.set_colors() | |
142 |
|
147 | |||
143 | #------------------------------------------------------------------------- |
|
148 | #------------------------------------------------------------------------- | |
144 | # Methods used in __call__. Override these methods to modify the behavior |
|
149 | # Methods used in __call__. Override these methods to modify the behavior | |
145 | # of the displayhook. |
|
150 | # of the displayhook. | |
146 | #------------------------------------------------------------------------- |
|
151 | #------------------------------------------------------------------------- | |
147 |
|
152 | |||
148 | def check_for_underscore(self): |
|
153 | def check_for_underscore(self): | |
149 | """Check if the user has set the '_' variable by hand.""" |
|
154 | """Check if the user has set the '_' variable by hand.""" | |
150 | # If something injected a '_' variable in __builtin__, delete |
|
155 | # If something injected a '_' variable in __builtin__, delete | |
151 | # ipython's automatic one so we don't clobber that. gettext() in |
|
156 | # ipython's automatic one so we don't clobber that. gettext() in | |
152 | # particular uses _, so we need to stay away from it. |
|
157 | # particular uses _, so we need to stay away from it. | |
153 | if '_' in __builtin__.__dict__: |
|
158 | if '_' in __builtin__.__dict__: | |
154 | try: |
|
159 | try: | |
155 | del self.shell.user_ns['_'] |
|
160 | del self.shell.user_ns['_'] | |
156 | except KeyError: |
|
161 | except KeyError: | |
157 | pass |
|
162 | pass | |
158 |
|
163 | |||
159 | def quiet(self): |
|
164 | def quiet(self): | |
160 | """Should we silence the display hook because of ';'?""" |
|
165 | """Should we silence the display hook because of ';'?""" | |
161 | # do not print output if input ends in ';' |
|
166 | # do not print output if input ends in ';' | |
162 | try: |
|
167 | try: | |
163 | if self.shell.input_hist[self.prompt_count].endswith(';\n'): |
|
168 | if self.shell.input_hist[self.prompt_count].endswith(';\n'): | |
164 | return True |
|
169 | return True | |
165 | except IndexError: |
|
170 | except IndexError: | |
166 | # some uses of ipshellembed may fail here |
|
171 | # some uses of ipshellembed may fail here | |
167 | pass |
|
172 | pass | |
168 | return False |
|
173 | return False | |
169 |
|
174 | |||
170 | def start_displayhook(self): |
|
175 | def start_displayhook(self): | |
171 | """Start the displayhook, initializing resources.""" |
|
176 | """Start the displayhook, initializing resources.""" | |
172 | pass |
|
177 | pass | |
173 |
|
178 | |||
174 | def write_output_prompt(self): |
|
179 | def write_output_prompt(self): | |
175 | """Write the output prompt.""" |
|
180 | """Write the output prompt.""" | |
176 | # Use write, not print which adds an extra space. |
|
181 | # Use write, not print which adds an extra space. | |
177 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
182 | IPython.utils.io.Term.cout.write(self.output_sep) | |
178 | outprompt = str(self.prompt_out) |
|
183 | outprompt = str(self.prompt_out) | |
179 | if self.do_full_cache: |
|
184 | if self.do_full_cache: | |
180 | IPython.utils.io.Term.cout.write(outprompt) |
|
185 | IPython.utils.io.Term.cout.write(outprompt) | |
181 |
|
186 | |||
182 | # TODO: Make this method an extension point. The previous implementation |
|
187 | # TODO: Make this method an extension point. The previous implementation | |
183 | # has both a result_display hook as well as a result_display generic |
|
188 | # has both a result_display hook as well as a result_display generic | |
184 | # function to customize the repr on a per class basis. We need to rethink |
|
189 | # function to customize the repr on a per class basis. We need to rethink | |
185 | # the hooks mechanism before doing this though. |
|
190 | # the hooks mechanism before doing this though. | |
186 | def compute_result_repr(self, result): |
|
191 | def compute_result_repr(self, result): | |
187 | """Compute and return the repr of the object to be displayed. |
|
192 | """Compute and return the repr of the object to be displayed. | |
188 |
|
193 | |||
189 | This method only compute the string form of the repr and should NOT |
|
194 | This method only compute the string form of the repr and should NOT | |
190 | actual print or write that to a stream. This method may also transform |
|
195 | actual print or write that to a stream. This method may also transform | |
191 | the result itself, but the default implementation passes the original |
|
196 | the result itself, but the default implementation passes the original | |
192 | through. |
|
197 | through. | |
193 | """ |
|
198 | """ | |
194 | try: |
|
199 | try: | |
195 | if self.shell.pprint: |
|
200 | if self.shell.pprint: | |
196 | try: |
|
201 | try: | |
197 | result_repr = pformat(result) |
|
202 | result_repr = pformat(result) | |
198 | except: |
|
203 | except: | |
199 | # Work around possible bugs in pformat |
|
204 | # Work around possible bugs in pformat | |
200 | result_repr = repr(result) |
|
205 | result_repr = repr(result) | |
201 | if '\n' in result_repr: |
|
206 | if '\n' in result_repr: | |
202 | # So that multi-line strings line up with the left column of |
|
207 | # So that multi-line strings line up with the left column of | |
203 | # the screen, instead of having the output prompt mess up |
|
208 | # the screen, instead of having the output prompt mess up | |
204 | # their first line. |
|
209 | # their first line. | |
205 | result_repr = '\n' + result_repr |
|
210 | result_repr = '\n' + result_repr | |
206 | else: |
|
211 | else: | |
207 | result_repr = repr(result) |
|
212 | result_repr = repr(result) | |
208 | except TypeError: |
|
213 | except TypeError: | |
209 | # This happens when result.__repr__ doesn't return a string, |
|
214 | # This happens when result.__repr__ doesn't return a string, | |
210 | # such as when it returns None. |
|
215 | # such as when it returns None. | |
211 | result_repr = '\n' |
|
216 | result_repr = '\n' | |
212 | return result, result_repr |
|
217 | return result, result_repr | |
213 |
|
218 | |||
214 | def write_result_repr(self, result_repr): |
|
219 | def write_result_repr(self, result_repr): | |
215 | # We want to print because we want to always make sure we have a |
|
220 | # We want to print because we want to always make sure we have a | |
216 | # newline, even if all the prompt separators are ''. This is the |
|
221 | # newline, even if all the prompt separators are ''. This is the | |
217 | # standard IPython behavior. |
|
222 | # standard IPython behavior. | |
218 | print >>IPython.utils.io.Term.cout, result_repr |
|
223 | print >>IPython.utils.io.Term.cout, result_repr | |
219 |
|
224 | |||
220 | def update_user_ns(self, result): |
|
225 | def update_user_ns(self, result): | |
221 | """Update user_ns with various things like _, __, _1, etc.""" |
|
226 | """Update user_ns with various things like _, __, _1, etc.""" | |
222 |
|
227 | |||
223 | # Avoid recursive reference when displaying _oh/Out |
|
228 | # Avoid recursive reference when displaying _oh/Out | |
224 | if result is not self.shell.user_ns['_oh']: |
|
229 | if result is not self.shell.user_ns['_oh']: | |
225 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
230 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
226 | warn('Output cache limit (currently '+ |
|
231 | warn('Output cache limit (currently '+ | |
227 | `self.cache_size`+' entries) hit.\n' |
|
232 | `self.cache_size`+' entries) hit.\n' | |
228 | 'Flushing cache and resetting history counter...\n' |
|
233 | 'Flushing cache and resetting history counter...\n' | |
229 | 'The only history variables available will be _,__,___ and _1\n' |
|
234 | 'The only history variables available will be _,__,___ and _1\n' | |
230 | 'with the current result.') |
|
235 | 'with the current result.') | |
231 |
|
236 | |||
232 | self.flush() |
|
237 | self.flush() | |
233 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
238 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
234 | # we cause buggy behavior for things like gettext). |
|
239 | # we cause buggy behavior for things like gettext). | |
235 | if '_' not in __builtin__.__dict__: |
|
240 | if '_' not in __builtin__.__dict__: | |
236 | self.___ = self.__ |
|
241 | self.___ = self.__ | |
237 | self.__ = self._ |
|
242 | self.__ = self._ | |
238 | self._ = result |
|
243 | self._ = result | |
239 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
244 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) | |
240 |
|
245 | |||
241 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
246 | # hackish access to top-level namespace to create _1,_2... dynamically | |
242 | to_main = {} |
|
247 | to_main = {} | |
243 | if self.do_full_cache: |
|
248 | if self.do_full_cache: | |
244 | new_result = '_'+`self.prompt_count` |
|
249 | new_result = '_'+`self.prompt_count` | |
245 | to_main[new_result] = result |
|
250 | to_main[new_result] = result | |
246 | self.shell.user_ns.update(to_main) |
|
251 | self.shell.user_ns.update(to_main) | |
247 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
252 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
248 |
|
253 | |||
249 | def log_output(self, result): |
|
254 | def log_output(self, result): | |
250 | """Log the output.""" |
|
255 | """Log the output.""" | |
251 | if self.shell.logger.log_output: |
|
256 | if self.shell.logger.log_output: | |
252 | self.shell.logger.log_write(repr(result),'output') |
|
257 | self.shell.logger.log_write(repr(result), 'output') | |
253 |
|
258 | |||
254 | def finish_displayhook(self): |
|
259 | def finish_displayhook(self): | |
255 | """Finish up all displayhook activities.""" |
|
260 | """Finish up all displayhook activities.""" | |
256 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
261 | IPython.utils.io.Term.cout.write(self.output_sep2) | |
257 | IPython.utils.io.Term.cout.flush() |
|
262 | IPython.utils.io.Term.cout.flush() | |
258 |
|
263 | |||
259 | def __call__(self, result=None): |
|
264 | def __call__(self, result=None): | |
260 | """Printing with history cache management. |
|
265 | """Printing with history cache management. | |
261 |
|
266 | |||
262 | This is invoked everytime the interpreter needs to print, and is |
|
267 | This is invoked everytime the interpreter needs to print, and is | |
263 | activated by setting the variable sys.displayhook to it. |
|
268 | activated by setting the variable sys.displayhook to it. | |
264 | """ |
|
269 | """ | |
265 | self.check_for_underscore() |
|
270 | self.check_for_underscore() | |
266 | if result is not None and not self.quiet(): |
|
271 | if result is not None and not self.quiet(): | |
267 | self.start_displayhook() |
|
272 | self.start_displayhook() | |
268 | self.write_output_prompt() |
|
273 | self.write_output_prompt() | |
269 | result, result_repr = self.compute_result_repr(result) |
|
274 | result, result_repr = self.compute_result_repr(result) | |
270 | self.write_result_repr(result_repr) |
|
275 | self.write_result_repr(result_repr) | |
271 | self.update_user_ns(result) |
|
276 | self.update_user_ns(result) | |
272 | self.log_output(result) |
|
277 | self.log_output(result) | |
273 | self.finish_displayhook() |
|
278 | self.finish_displayhook() | |
274 |
|
279 | |||
275 | def flush(self): |
|
280 | def flush(self): | |
276 | if not self.do_full_cache: |
|
281 | if not self.do_full_cache: | |
277 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
282 | raise ValueError,"You shouldn't have reached the cache flush "\ | |
278 | "if full caching is not enabled!" |
|
283 | "if full caching is not enabled!" | |
279 | # delete auto-generated vars from global namespace |
|
284 | # delete auto-generated vars from global namespace | |
280 |
|
285 | |||
281 | for n in range(1,self.prompt_count + 1): |
|
286 | for n in range(1,self.prompt_count + 1): | |
282 | key = '_'+`n` |
|
287 | key = '_'+`n` | |
283 | try: |
|
288 | try: | |
284 | del self.shell.user_ns[key] |
|
289 | del self.shell.user_ns[key] | |
285 | except: pass |
|
290 | except: pass | |
286 | self.shell.user_ns['_oh'].clear() |
|
291 | self.shell.user_ns['_oh'].clear() | |
287 |
|
292 | |||
288 | if '_' not in __builtin__.__dict__: |
|
293 | if '_' not in __builtin__.__dict__: | |
289 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
294 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
290 | import gc |
|
295 | import gc | |
291 | gc.collect() # xxx needed? |
|
296 | gc.collect() # xxx needed? | |
292 |
|
297 |
@@ -1,283 +1,506 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
|||
2 |
|
|
1 | """ History related magics and functionality """ | |
|
2 | #----------------------------------------------------------------------------- | |||
|
3 | # Copyright (C) 2010 The IPython Development Team. | |||
|
4 | # | |||
|
5 | # Distributed under the terms of the BSD License. | |||
|
6 | # | |||
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |||
|
8 | #----------------------------------------------------------------------------- | |||
|
9 | ||||
|
10 | #----------------------------------------------------------------------------- | |||
|
11 | # Imports | |||
|
12 | #----------------------------------------------------------------------------- | |||
|
13 | from __future__ import print_function | |||
3 |
|
14 | |||
4 | # Stdlib imports |
|
15 | # Stdlib imports | |
5 | import fnmatch |
|
16 | import fnmatch | |
6 | import os |
|
17 | import os | |
|
18 | import sys | |||
7 |
|
19 | |||
|
20 | # Our own packages | |||
8 | import IPython.utils.io |
|
21 | import IPython.utils.io | |
|
22 | ||||
|
23 | from IPython.core import ipapi | |||
|
24 | from IPython.core.inputlist import InputList | |||
|
25 | from IPython.utils.pickleshare import PickleShareDB | |||
9 | from IPython.utils.io import ask_yes_no |
|
26 | from IPython.utils.io import ask_yes_no | |
10 | from IPython.utils.warn import warn |
|
27 | from IPython.utils.warn import warn | |
11 | from IPython.core import ipapi |
|
28 | ||
|
29 | #----------------------------------------------------------------------------- | |||
|
30 | # Classes and functions | |||
|
31 | #----------------------------------------------------------------------------- | |||
|
32 | ||||
|
33 | class HistoryManager(object): | |||
|
34 | """A class to organize all history-related functionality in one place. | |||
|
35 | """ | |||
|
36 | # Public interface | |||
|
37 | ||||
|
38 | # An instance of the IPython shell we are attached to | |||
|
39 | shell = None | |||
|
40 | # An InputList instance to hold processed history | |||
|
41 | input_hist = None | |||
|
42 | # An InputList instance to hold raw history (as typed by user) | |||
|
43 | input_hist_raw = None | |||
|
44 | # A list of directories visited during session | |||
|
45 | dir_hist = None | |||
|
46 | # A dict of output history, keyed with ints from the shell's execution count | |||
|
47 | output_hist = None | |||
|
48 | # String with path to the history file | |||
|
49 | hist_file = None | |||
|
50 | # PickleShareDB instance holding the raw data for the shadow history | |||
|
51 | shadow_db = None | |||
|
52 | # ShadowHist instance with the actual shadow history | |||
|
53 | shadow_hist = None | |||
|
54 | ||||
|
55 | # Private interface | |||
|
56 | # Variables used to store the three last inputs from the user. On each new | |||
|
57 | # history update, we populate the user's namespace with these, shifted as | |||
|
58 | # necessary. | |||
|
59 | _i00, _i, _ii, _iii = '','','','' | |||
|
60 | ||||
|
61 | def __init__(self, shell): | |||
|
62 | """Create a new history manager associated with a shell instance. | |||
|
63 | """ | |||
|
64 | # We need a pointer back to the shell for various tasks. | |||
|
65 | self.shell = shell | |||
|
66 | ||||
|
67 | # List of input with multi-line handling. | |||
|
68 | self.input_hist = InputList() | |||
|
69 | # This one will hold the 'raw' input history, without any | |||
|
70 | # pre-processing. This will allow users to retrieve the input just as | |||
|
71 | # it was exactly typed in by the user, with %hist -r. | |||
|
72 | self.input_hist_raw = InputList() | |||
|
73 | ||||
|
74 | # list of visited directories | |||
|
75 | try: | |||
|
76 | self.dir_hist = [os.getcwd()] | |||
|
77 | except OSError: | |||
|
78 | self.dir_hist = [] | |||
|
79 | ||||
|
80 | # dict of output history | |||
|
81 | self.output_hist = {} | |||
|
82 | ||||
|
83 | # Now the history file | |||
|
84 | if shell.profile: | |||
|
85 | histfname = 'history-%s' % shell.profile | |||
|
86 | else: | |||
|
87 | histfname = 'history' | |||
|
88 | self.hist_file = os.path.join(shell.ipython_dir, histfname) | |||
|
89 | ||||
|
90 | # Objects related to shadow history management | |||
|
91 | self._init_shadow_hist() | |||
|
92 | ||||
|
93 | self._i00, self._i, self._ii, self._iii = '','','','' | |||
|
94 | ||||
|
95 | # Object is fully initialized, we can now call methods on it. | |||
|
96 | ||||
|
97 | # Fill the history zero entry, user counter starts at 1 | |||
|
98 | self.store_inputs('\n', '\n') | |||
|
99 | ||||
|
100 | # For backwards compatibility, we must put these back in the shell | |||
|
101 | # object, until we've removed all direct uses of the history objects in | |||
|
102 | # the shell itself. | |||
|
103 | shell.input_hist = self.input_hist | |||
|
104 | shell.input_hist_raw = self.input_hist_raw | |||
|
105 | shell.output_hist = self.output_hist | |||
|
106 | shell.dir_hist = self.dir_hist | |||
|
107 | shell.histfile = self.hist_file | |||
|
108 | shell.shadowhist = self.shadow_hist | |||
|
109 | shell.db = self.shadow_db | |||
|
110 | ||||
|
111 | def _init_shadow_hist(self): | |||
|
112 | try: | |||
|
113 | self.shadow_db = PickleShareDB(os.path.join( | |||
|
114 | self.shell.ipython_dir, 'db')) | |||
|
115 | except UnicodeDecodeError: | |||
|
116 | print("Your ipython_dir can't be decoded to unicode!") | |||
|
117 | print("Please set HOME environment variable to something that") | |||
|
118 | print(r"only has ASCII characters, e.g. c:\home") | |||
|
119 | print("Now it is", self.ipython_dir) | |||
|
120 | sys.exit() | |||
|
121 | self.shadow_hist = ShadowHist(self.shadow_db) | |||
|
122 | ||||
|
123 | def save_hist(self): | |||
|
124 | """Save input history to a file (via readline library).""" | |||
|
125 | ||||
|
126 | try: | |||
|
127 | self.shell.readline.write_history_file(self.hist_file) | |||
|
128 | except: | |||
|
129 | print('Unable to save IPython command history to file: ' + | |||
|
130 | `self.hist_file`) | |||
|
131 | ||||
|
132 | def reload_hist(self): | |||
|
133 | """Reload the input history from disk file.""" | |||
|
134 | ||||
|
135 | try: | |||
|
136 | self.shell.readline.clear_history() | |||
|
137 | self.shell.readline.read_history_file(self.hist_file) | |||
|
138 | except AttributeError: | |||
|
139 | pass | |||
|
140 | ||||
|
141 | def get_history(self, index=None, raw=False, output=True): | |||
|
142 | """Get the history list. | |||
|
143 | ||||
|
144 | Get the input and output history. | |||
|
145 | ||||
|
146 | Parameters | |||
|
147 | ---------- | |||
|
148 | index : n or (n1, n2) or None | |||
|
149 | If n, then the last entries. If a tuple, then all in | |||
|
150 | range(n1, n2). If None, then all entries. Raises IndexError if | |||
|
151 | the format of index is incorrect. | |||
|
152 | raw : bool | |||
|
153 | If True, return the raw input. | |||
|
154 | output : bool | |||
|
155 | If True, then return the output as well. | |||
|
156 | ||||
|
157 | Returns | |||
|
158 | ------- | |||
|
159 | If output is True, then return a dict of tuples, keyed by the prompt | |||
|
160 | numbers and with values of (input, output). If output is False, then | |||
|
161 | a dict, keyed by the prompt number with the values of input. Raises | |||
|
162 | IndexError if no history is found. | |||
|
163 | """ | |||
|
164 | if raw: | |||
|
165 | input_hist = self.input_hist_raw | |||
|
166 | else: | |||
|
167 | input_hist = self.input_hist | |||
|
168 | if output: | |||
|
169 | output_hist = self.output_hist | |||
|
170 | n = len(input_hist) | |||
|
171 | if index is None: | |||
|
172 | start=0; stop=n | |||
|
173 | elif isinstance(index, int): | |||
|
174 | start=n-index; stop=n | |||
|
175 | elif isinstance(index, tuple) and len(index) == 2: | |||
|
176 | start=index[0]; stop=index[1] | |||
|
177 | else: | |||
|
178 | raise IndexError('Not a valid index for the input history: %r' | |||
|
179 | % index) | |||
|
180 | hist = {} | |||
|
181 | for i in range(start, stop): | |||
|
182 | if output: | |||
|
183 | hist[i] = (input_hist[i], output_hist.get(i)) | |||
|
184 | else: | |||
|
185 | hist[i] = input_hist[i] | |||
|
186 | if not hist: | |||
|
187 | raise IndexError('No history for range of indices: %r' % index) | |||
|
188 | return hist | |||
|
189 | ||||
|
190 | def store_inputs(self, source, source_raw=None): | |||
|
191 | """Store source and raw input in history and create input cache | |||
|
192 | variables _i*. | |||
|
193 | ||||
|
194 | Parameters | |||
|
195 | ---------- | |||
|
196 | source : str | |||
|
197 | Python input. | |||
|
198 | ||||
|
199 | source_raw : str, optional | |||
|
200 | If given, this is the raw input without any IPython transformations | |||
|
201 | applied to it. If not given, ``source`` is used. | |||
|
202 | """ | |||
|
203 | if source_raw is None: | |||
|
204 | source_raw = source | |||
|
205 | self.input_hist.append(source) | |||
|
206 | self.input_hist_raw.append(source_raw) | |||
|
207 | self.shadow_hist.add(source) | |||
|
208 | ||||
|
209 | # update the auto _i variables | |||
|
210 | self._iii = self._ii | |||
|
211 | self._ii = self._i | |||
|
212 | self._i = self._i00 | |||
|
213 | self._i00 = source_raw | |||
|
214 | ||||
|
215 | # hackish access to user namespace to create _i1,_i2... dynamically | |||
|
216 | new_i = '_i%s' % self.shell.execution_count | |||
|
217 | to_main = {'_i': self._i, | |||
|
218 | '_ii': self._ii, | |||
|
219 | '_iii': self._iii, | |||
|
220 | new_i : self._i00 } | |||
|
221 | self.shell.user_ns.update(to_main) | |||
|
222 | ||||
|
223 | def sync_inputs(self): | |||
|
224 | """Ensure raw and translated histories have same length.""" | |||
|
225 | if len(self.input_hist) != len (self.input_hist_raw): | |||
|
226 | self.input_hist_raw = InputList(self.input_hist) | |||
|
227 | ||||
|
228 | def reset(self): | |||
|
229 | """Clear all histories managed by this object.""" | |||
|
230 | self.input_hist[:] = [] | |||
|
231 | self.input_hist_raw[:] = [] | |||
|
232 | self.output_hist.clear() | |||
|
233 | # The directory history can't be completely empty | |||
|
234 | self.dir_hist[:] = [os.getcwd()] | |||
|
235 | ||||
12 |
|
236 | |||
13 | def magic_history(self, parameter_s = ''): |
|
237 | def magic_history(self, parameter_s = ''): | |
14 | """Print input history (_i<n> variables), with most recent last. |
|
238 | """Print input history (_i<n> variables), with most recent last. | |
15 |
|
239 | |||
16 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
240 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
17 | %history n -> print at most n inputs\\ |
|
241 | %history n -> print at most n inputs\\ | |
18 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
242 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
19 |
|
243 | |||
20 | By default, input history is printed without line numbers so it can be |
|
244 | By default, input history is printed without line numbers so it can be | |
21 | directly pasted into an editor. |
|
245 | directly pasted into an editor. | |
22 |
|
246 | |||
23 | With -n, each input's number <n> is shown, and is accessible as the |
|
247 | With -n, each input's number <n> is shown, and is accessible as the | |
24 | automatically generated variable _i<n> as well as In[<n>]. Multi-line |
|
248 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
25 | statements are printed starting at a new line for easy copy/paste. |
|
249 | statements are printed starting at a new line for easy copy/paste. | |
26 |
|
250 | |||
27 | Options: |
|
251 | Options: | |
28 |
|
252 | |||
29 | -n: print line numbers for each input. |
|
253 | -n: print line numbers for each input. | |
30 | This feature is only available if numbered prompts are in use. |
|
254 | This feature is only available if numbered prompts are in use. | |
31 |
|
255 | |||
32 | -o: also print outputs for each input. |
|
256 | -o: also print outputs for each input. | |
33 |
|
257 | |||
34 | -p: print classic '>>>' python prompts before each input. This is useful |
|
258 | -p: print classic '>>>' python prompts before each input. This is useful | |
35 | for making documentation, and in conjunction with -o, for producing |
|
259 | for making documentation, and in conjunction with -o, for producing | |
36 | doctest-ready output. |
|
260 | doctest-ready output. | |
37 |
|
261 | |||
38 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
262 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | |
39 |
|
263 | |||
40 | -t: print the 'translated' history, as IPython understands it. IPython |
|
264 | -t: print the 'translated' history, as IPython understands it. IPython | |
41 | filters your input and converts it all into valid Python source before |
|
265 | filters your input and converts it all into valid Python source before | |
42 | executing it (things like magics or aliases are turned into function |
|
266 | executing it (things like magics or aliases are turned into function | |
43 | calls, for example). With this option, you'll see the native history |
|
267 | calls, for example). With this option, you'll see the native history | |
44 | instead of the user-entered version: '%cd /' will be seen as |
|
268 | instead of the user-entered version: '%cd /' will be seen as | |
45 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
269 | 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
46 |
|
270 | |||
47 | -g: treat the arg as a pattern to grep for in (full) history. |
|
271 | -g: treat the arg as a pattern to grep for in (full) history. | |
48 | This includes the "shadow history" (almost all commands ever written). |
|
272 | This includes the "shadow history" (almost all commands ever written). | |
49 | Use '%hist -g' to show full shadow history (may be very long). |
|
273 | Use '%hist -g' to show full shadow history (may be very long). | |
50 | In shadow history, every index nuwber starts with 0. |
|
274 | In shadow history, every index nuwber starts with 0. | |
51 |
|
275 | |||
52 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
276 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
53 | the given file. The file is always overwritten, though IPython asks for |
|
277 | the given file. The file is always overwritten, though IPython asks for | |
54 | confirmation first if it already exists. |
|
278 | confirmation first if it already exists. | |
55 | """ |
|
279 | """ | |
56 |
|
280 | |||
57 | if not self.shell.displayhook.do_full_cache: |
|
281 | if not self.shell.displayhook.do_full_cache: | |
58 |
print |
|
282 | print('This feature is only available if numbered prompts are in use.') | |
59 | return |
|
283 | return | |
60 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') |
|
284 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') | |
61 |
|
285 | |||
62 | # Check if output to specific file was requested. |
|
286 | # Check if output to specific file was requested. | |
63 | try: |
|
287 | try: | |
64 | outfname = opts['f'] |
|
288 | outfname = opts['f'] | |
65 | except KeyError: |
|
289 | except KeyError: | |
66 | outfile = IPython.utils.io.Term.cout # default |
|
290 | outfile = IPython.utils.io.Term.cout # default | |
67 | # We don't want to close stdout at the end! |
|
291 | # We don't want to close stdout at the end! | |
68 | close_at_end = False |
|
292 | close_at_end = False | |
69 | else: |
|
293 | else: | |
70 | if os.path.exists(outfname): |
|
294 | if os.path.exists(outfname): | |
71 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
295 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
72 |
print |
|
296 | print('Aborting.') | |
73 | return |
|
297 | return | |
74 |
|
298 | |||
75 | outfile = open(outfname,'w') |
|
299 | outfile = open(outfname,'w') | |
76 | close_at_end = True |
|
300 | close_at_end = True | |
77 |
|
301 | |||
78 | if 't' in opts: |
|
302 | if 't' in opts: | |
79 | input_hist = self.shell.input_hist |
|
303 | input_hist = self.shell.input_hist | |
80 | elif 'r' in opts: |
|
304 | elif 'r' in opts: | |
81 | input_hist = self.shell.input_hist_raw |
|
305 | input_hist = self.shell.input_hist_raw | |
82 | else: |
|
306 | else: | |
83 | # Raw history is the default |
|
307 | # Raw history is the default | |
84 | input_hist = self.shell.input_hist_raw |
|
308 | input_hist = self.shell.input_hist_raw | |
85 |
|
309 | |||
86 | default_length = 40 |
|
310 | default_length = 40 | |
87 | pattern = None |
|
311 | pattern = None | |
88 | if 'g' in opts: |
|
312 | if 'g' in opts: | |
89 | init = 1 |
|
313 | init = 1 | |
90 | final = len(input_hist) |
|
314 | final = len(input_hist) | |
91 | parts = parameter_s.split(None, 1) |
|
315 | parts = parameter_s.split(None, 1) | |
92 | if len(parts) == 1: |
|
316 | if len(parts) == 1: | |
93 | parts += '*' |
|
317 | parts += '*' | |
94 | head, pattern = parts |
|
318 | head, pattern = parts | |
95 | pattern = "*" + pattern + "*" |
|
319 | pattern = "*" + pattern + "*" | |
96 | elif len(args) == 0: |
|
320 | elif len(args) == 0: | |
97 | final = len(input_hist)-1 |
|
321 | final = len(input_hist)-1 | |
98 | init = max(1,final-default_length) |
|
322 | init = max(1,final-default_length) | |
99 | elif len(args) == 1: |
|
323 | elif len(args) == 1: | |
100 | final = len(input_hist) |
|
324 | final = len(input_hist) | |
101 | init = max(1, final-int(args[0])) |
|
325 | init = max(1, final-int(args[0])) | |
102 | elif len(args) == 2: |
|
326 | elif len(args) == 2: | |
103 | init, final = map(int, args) |
|
327 | init, final = map(int, args) | |
104 | else: |
|
328 | else: | |
105 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
329 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
106 | print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__ |
|
330 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) | |
107 | return |
|
331 | return | |
108 |
|
332 | |||
109 | width = len(str(final)) |
|
333 | width = len(str(final)) | |
110 | line_sep = ['','\n'] |
|
334 | line_sep = ['','\n'] | |
111 | print_nums = 'n' in opts |
|
335 | print_nums = 'n' in opts | |
112 | print_outputs = 'o' in opts |
|
336 | print_outputs = 'o' in opts | |
113 | pyprompts = 'p' in opts |
|
337 | pyprompts = 'p' in opts | |
114 |
|
338 | |||
115 | found = False |
|
339 | found = False | |
116 | if pattern is not None: |
|
340 | if pattern is not None: | |
117 | sh = self.shell.shadowhist.all() |
|
341 | sh = self.shell.shadowhist.all() | |
118 | for idx, s in sh: |
|
342 | for idx, s in sh: | |
119 | if fnmatch.fnmatch(s, pattern): |
|
343 | if fnmatch.fnmatch(s, pattern): | |
120 |
print |
|
344 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) | |
121 | found = True |
|
345 | found = True | |
122 |
|
346 | |||
123 | if found: |
|
347 | if found: | |
124 |
print |
|
348 | print("===", file=outfile) | |
125 | print >> outfile, \ |
|
349 | print("shadow history ends, fetch by %rep <number> (must start with 0)", | |
126 | "shadow history ends, fetch by %rep <number> (must start with 0)" |
|
350 | file=outfile) | |
127 |
print |
|
351 | print("=== start of normal history ===", file=outfile) | |
128 |
|
352 | |||
129 | for in_num in range(init, final): |
|
353 | for in_num in range(init, final): | |
130 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
354 | # Print user history with tabs expanded to 4 spaces. The GUI clients | |
131 | # use hard tabs for easier usability in auto-indented code, but we want |
|
355 | # use hard tabs for easier usability in auto-indented code, but we want | |
132 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
356 | # to produce PEP-8 compliant history for safe pasting into an editor. | |
133 | inline = input_hist[in_num].expandtabs(4) |
|
357 | inline = input_hist[in_num].expandtabs(4) | |
134 |
|
358 | |||
135 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
359 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
136 | continue |
|
360 | continue | |
137 |
|
361 | |||
138 | multiline = int(inline.count('\n') > 1) |
|
362 | multiline = int(inline.count('\n') > 1) | |
139 | if print_nums: |
|
363 | if print_nums: | |
140 | print >> outfile, \ |
|
364 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), | |
141 | '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), |
|
365 | file=outfile) | |
142 | if pyprompts: |
|
366 | if pyprompts: | |
143 |
print |
|
367 | print('>>>', file=outfile) | |
144 | if multiline: |
|
368 | if multiline: | |
145 | lines = inline.splitlines() |
|
369 | lines = inline.splitlines() | |
146 |
print |
|
370 | print('\n... '.join(lines), file=outfile) | |
147 |
print |
|
371 | print('... ', file=outfile) | |
148 | else: |
|
372 | else: | |
149 |
print |
|
373 | print(inline, end='', file=outfile) | |
150 | else: |
|
374 | else: | |
151 |
print |
|
375 | print(inline,end='', file=outfile) | |
152 | if print_outputs: |
|
376 | if print_outputs: | |
153 | output = self.shell.output_hist.get(in_num) |
|
377 | output = self.shell.output_hist.get(in_num) | |
154 | if output is not None: |
|
378 | if output is not None: | |
155 |
print |
|
379 | print(repr(output), file=outfile) | |
156 |
|
380 | |||
157 | if close_at_end: |
|
381 | if close_at_end: | |
158 | outfile.close() |
|
382 | outfile.close() | |
159 |
|
383 | |||
160 |
|
384 | |||
161 | def magic_hist(self, parameter_s=''): |
|
385 | def magic_hist(self, parameter_s=''): | |
162 | """Alternate name for %history.""" |
|
386 | """Alternate name for %history.""" | |
163 | return self.magic_history(parameter_s) |
|
387 | return self.magic_history(parameter_s) | |
164 |
|
388 | |||
165 |
|
389 | |||
166 | def rep_f(self, arg): |
|
390 | def rep_f(self, arg): | |
167 | r""" Repeat a command, or get command to input line for editing |
|
391 | r""" Repeat a command, or get command to input line for editing | |
168 |
|
392 | |||
169 | - %rep (no arguments): |
|
393 | - %rep (no arguments): | |
170 |
|
394 | |||
171 | Place a string version of last computation result (stored in the special '_' |
|
395 | Place a string version of last computation result (stored in the special '_' | |
172 | variable) to the next input prompt. Allows you to create elaborate command |
|
396 | variable) to the next input prompt. Allows you to create elaborate command | |
173 | lines without using copy-paste:: |
|
397 | lines without using copy-paste:: | |
174 |
|
398 | |||
175 | $ l = ["hei", "vaan"] |
|
399 | $ l = ["hei", "vaan"] | |
176 | $ "".join(l) |
|
400 | $ "".join(l) | |
177 | ==> heivaan |
|
401 | ==> heivaan | |
178 | $ %rep |
|
402 | $ %rep | |
179 | $ heivaan_ <== cursor blinking |
|
403 | $ heivaan_ <== cursor blinking | |
180 |
|
404 | |||
181 | %rep 45 |
|
405 | %rep 45 | |
182 |
|
406 | |||
183 | Place history line 45 to next input prompt. Use %hist to find out the |
|
407 | Place history line 45 to next input prompt. Use %hist to find out the | |
184 | number. |
|
408 | number. | |
185 |
|
409 | |||
186 | %rep 1-4 6-7 3 |
|
410 | %rep 1-4 6-7 3 | |
187 |
|
411 | |||
188 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
412 | Repeat the specified lines immediately. Input slice syntax is the same as | |
189 | in %macro and %save. |
|
413 | in %macro and %save. | |
190 |
|
414 | |||
191 | %rep foo |
|
415 | %rep foo | |
192 |
|
416 | |||
193 | Place the most recent line that has the substring "foo" to next input. |
|
417 | Place the most recent line that has the substring "foo" to next input. | |
194 | (e.g. 'svn ci -m foobar'). |
|
418 | (e.g. 'svn ci -m foobar'). | |
195 | """ |
|
419 | """ | |
196 |
|
420 | |||
197 | opts,args = self.parse_options(arg,'',mode='list') |
|
421 | opts,args = self.parse_options(arg,'',mode='list') | |
198 | if not args: |
|
422 | if not args: | |
199 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
423 | self.set_next_input(str(self.shell.user_ns["_"])) | |
200 | return |
|
424 | return | |
201 |
|
425 | |||
202 | if len(args) == 1 and not '-' in args[0]: |
|
426 | if len(args) == 1 and not '-' in args[0]: | |
203 | arg = args[0] |
|
427 | arg = args[0] | |
204 | if len(arg) > 1 and arg.startswith('0'): |
|
428 | if len(arg) > 1 and arg.startswith('0'): | |
205 | # get from shadow hist |
|
429 | # get from shadow hist | |
206 | num = int(arg[1:]) |
|
430 | num = int(arg[1:]) | |
207 | line = self.shell.shadowhist.get(num) |
|
431 | line = self.shell.shadowhist.get(num) | |
208 | self.set_next_input(str(line)) |
|
432 | self.set_next_input(str(line)) | |
209 | return |
|
433 | return | |
210 | try: |
|
434 | try: | |
211 | num = int(args[0]) |
|
435 | num = int(args[0]) | |
212 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) |
|
436 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) | |
213 | return |
|
437 | return | |
214 | except ValueError: |
|
438 | except ValueError: | |
215 | pass |
|
439 | pass | |
216 |
|
440 | |||
217 | for h in reversed(self.shell.input_hist_raw): |
|
441 | for h in reversed(self.shell.input_hist_raw): | |
218 | if 'rep' in h: |
|
442 | if 'rep' in h: | |
219 | continue |
|
443 | continue | |
220 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
444 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
221 | self.set_next_input(str(h).rstrip()) |
|
445 | self.set_next_input(str(h).rstrip()) | |
222 | return |
|
446 | return | |
223 |
|
447 | |||
224 | try: |
|
448 | try: | |
225 | lines = self.extract_input_slices(args, True) |
|
449 | lines = self.extract_input_slices(args, True) | |
226 |
print |
|
450 | print("lines", lines) | |
227 |
self.run |
|
451 | self.run_cell(lines) | |
228 | except ValueError: |
|
452 | except ValueError: | |
229 |
print |
|
453 | print("Not found in recent history:", args) | |
230 |
|
454 | |||
231 |
|
455 | |||
232 | _sentinel = object() |
|
456 | _sentinel = object() | |
233 |
|
457 | |||
234 | class ShadowHist(object): |
|
458 | class ShadowHist(object): | |
235 | def __init__(self, db): |
|
459 | def __init__(self, db): | |
236 | # cmd => idx mapping |
|
460 | # cmd => idx mapping | |
237 | self.curidx = 0 |
|
461 | self.curidx = 0 | |
238 | self.db = db |
|
462 | self.db = db | |
239 | self.disabled = False |
|
463 | self.disabled = False | |
240 |
|
464 | |||
241 | def inc_idx(self): |
|
465 | def inc_idx(self): | |
242 | idx = self.db.get('shadowhist_idx', 1) |
|
466 | idx = self.db.get('shadowhist_idx', 1) | |
243 | self.db['shadowhist_idx'] = idx + 1 |
|
467 | self.db['shadowhist_idx'] = idx + 1 | |
244 | return idx |
|
468 | return idx | |
245 |
|
469 | |||
246 | def add(self, ent): |
|
470 | def add(self, ent): | |
247 | if self.disabled: |
|
471 | if self.disabled: | |
248 | return |
|
472 | return | |
249 | try: |
|
473 | try: | |
250 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
474 | old = self.db.hget('shadowhist', ent, _sentinel) | |
251 | if old is not _sentinel: |
|
475 | if old is not _sentinel: | |
252 | return |
|
476 | return | |
253 | newidx = self.inc_idx() |
|
477 | newidx = self.inc_idx() | |
254 |
#print |
|
478 | #print("new", newidx) # dbg | |
255 | self.db.hset('shadowhist',ent, newidx) |
|
479 | self.db.hset('shadowhist',ent, newidx) | |
256 | except: |
|
480 | except: | |
257 | ipapi.get().showtraceback() |
|
481 | ipapi.get().showtraceback() | |
258 |
print |
|
482 | print("WARNING: disabling shadow history") | |
259 | self.disabled = True |
|
483 | self.disabled = True | |
260 |
|
484 | |||
261 | def all(self): |
|
485 | def all(self): | |
262 | d = self.db.hdict('shadowhist') |
|
486 | d = self.db.hdict('shadowhist') | |
263 | items = [(i,s) for (s,i) in d.iteritems()] |
|
487 | items = [(i,s) for (s,i) in d.iteritems()] | |
264 | items.sort() |
|
488 | items.sort() | |
265 | return items |
|
489 | return items | |
266 |
|
490 | |||
267 | def get(self, idx): |
|
491 | def get(self, idx): | |
268 | all = self.all() |
|
492 | all = self.all() | |
269 |
|
493 | |||
270 | for k, v in all: |
|
494 | for k, v in all: | |
271 | #print k,v |
|
|||
272 | if k == idx: |
|
495 | if k == idx: | |
273 | return v |
|
496 | return v | |
274 |
|
497 | |||
275 |
|
498 | |||
276 | def init_ipython(ip): |
|
499 | def init_ipython(ip): | |
277 | ip.define_magic("rep",rep_f) |
|
500 | ip.define_magic("rep",rep_f) | |
278 | ip.define_magic("hist",magic_hist) |
|
501 | ip.define_magic("hist",magic_hist) | |
279 | ip.define_magic("history",magic_history) |
|
502 | ip.define_magic("history",magic_history) | |
280 |
|
503 | |||
281 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
504 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
282 | #import ipy_completers |
|
505 | #import ipy_completers | |
283 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
506 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,263 +1,263 b'' | |||||
1 | """hooks for IPython. |
|
1 | """hooks for IPython. | |
2 |
|
2 | |||
3 | In Python, it is possible to overwrite any method of any object if you really |
|
3 | In Python, it is possible to overwrite any method of any object if you really | |
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to | |
5 | be overwritten by users for customization purposes. This module defines the |
|
5 | be overwritten by users for customization purposes. This module defines the | |
6 | default versions of all such hooks, which get used by IPython if not |
|
6 | default versions of all such hooks, which get used by IPython if not | |
7 | overridden by the user. |
|
7 | overridden by the user. | |
8 |
|
8 | |||
9 | hooks are simple functions, but they should be declared with 'self' as their |
|
9 | hooks are simple functions, but they should be declared with 'self' as their | |
10 | first argument, because when activated they are registered into IPython as |
|
10 | first argument, because when activated they are registered into IPython as | |
11 | instance methods. The self argument will be the IPython running instance |
|
11 | instance methods. The self argument will be the IPython running instance | |
12 | itself, so hooks have full access to the entire IPython object. |
|
12 | itself, so hooks have full access to the entire IPython object. | |
13 |
|
13 | |||
14 | If you wish to define a new hook and activate it, you need to put the |
|
14 | If you wish to define a new hook and activate it, you need to put the | |
15 | necessary code into a python file which can be either imported or execfile()'d |
|
15 | necessary code into a python file which can be either imported or execfile()'d | |
16 | from within your ipythonrc configuration. |
|
16 | from within your ipythonrc configuration. | |
17 |
|
17 | |||
18 | For example, suppose that you have a module called 'myiphooks' in your |
|
18 | For example, suppose that you have a module called 'myiphooks' in your | |
19 | PYTHONPATH, which contains the following definition: |
|
19 | PYTHONPATH, which contains the following definition: | |
20 |
|
20 | |||
21 | import os |
|
21 | import os | |
22 | from IPython.core import ipapi |
|
22 | from IPython.core import ipapi | |
23 | ip = ipapi.get() |
|
23 | ip = ipapi.get() | |
24 |
|
24 | |||
25 | def calljed(self,filename, linenum): |
|
25 | def calljed(self,filename, linenum): | |
26 | "My editor hook calls the jed editor directly." |
|
26 | "My editor hook calls the jed editor directly." | |
27 | print "Calling my own editor, jed ..." |
|
27 | print "Calling my own editor, jed ..." | |
28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: | |
29 | raise TryNext() |
|
29 | raise TryNext() | |
30 |
|
30 | |||
31 | ip.set_hook('editor', calljed) |
|
31 | ip.set_hook('editor', calljed) | |
32 |
|
32 | |||
33 | You can then enable the functionality by doing 'import myiphooks' |
|
33 | You can then enable the functionality by doing 'import myiphooks' | |
34 | somewhere in your configuration files or ipython command line. |
|
34 | somewhere in your configuration files or ipython command line. | |
35 | """ |
|
35 | """ | |
36 |
|
36 | |||
37 | #***************************************************************************** |
|
37 | #***************************************************************************** | |
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> | |
39 | # |
|
39 | # | |
40 | # Distributed under the terms of the BSD License. The full license is in |
|
40 | # Distributed under the terms of the BSD License. The full license is in | |
41 | # the file COPYING, distributed as part of this software. |
|
41 | # the file COPYING, distributed as part of this software. | |
42 | #***************************************************************************** |
|
42 | #***************************************************************************** | |
43 |
|
43 | |||
44 | import os, bisect |
|
44 | import os, bisect | |
45 | import sys |
|
45 | import sys | |
46 |
|
46 | |||
47 | from IPython.core.error import TryNext |
|
47 | from IPython.core.error import TryNext | |
48 | import IPython.utils.io |
|
48 | import IPython.utils.io | |
49 |
|
49 | |||
50 | # List here all the default hooks. For now it's just the editor functions |
|
50 | # List here all the default hooks. For now it's just the editor functions | |
51 | # but over time we'll move here all the public API for user-accessible things. |
|
51 | # but over time we'll move here all the public API for user-accessible things. | |
52 |
|
52 | |||
53 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', |
|
53 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', | |
54 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
54 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', | |
55 | 'generate_prompt', 'show_in_pager','pre_prompt_hook', |
|
55 | 'generate_prompt', 'show_in_pager','pre_prompt_hook', | |
56 | 'pre_runcode_hook', 'clipboard_get'] |
|
56 | 'pre_run_code_hook', 'clipboard_get'] | |
57 |
|
57 | |||
58 | def editor(self,filename, linenum=None): |
|
58 | def editor(self,filename, linenum=None): | |
59 | """Open the default editor at the given filename and linenumber. |
|
59 | """Open the default editor at the given filename and linenumber. | |
60 |
|
60 | |||
61 | This is IPython's default editor hook, you can use it as an example to |
|
61 | This is IPython's default editor hook, you can use it as an example to | |
62 | write your own modified one. To set your own editor function as the |
|
62 | write your own modified one. To set your own editor function as the | |
63 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
63 | new editor hook, call ip.set_hook('editor',yourfunc).""" | |
64 |
|
64 | |||
65 | # IPython configures a default editor at startup by reading $EDITOR from |
|
65 | # IPython configures a default editor at startup by reading $EDITOR from | |
66 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
66 | # the environment, and falling back on vi (unix) or notepad (win32). | |
67 | editor = self.editor |
|
67 | editor = self.editor | |
68 |
|
68 | |||
69 | # marker for at which line to open the file (for existing objects) |
|
69 | # marker for at which line to open the file (for existing objects) | |
70 | if linenum is None or editor=='notepad': |
|
70 | if linenum is None or editor=='notepad': | |
71 | linemark = '' |
|
71 | linemark = '' | |
72 | else: |
|
72 | else: | |
73 | linemark = '+%d' % int(linenum) |
|
73 | linemark = '+%d' % int(linenum) | |
74 |
|
74 | |||
75 | # Enclose in quotes if necessary and legal |
|
75 | # Enclose in quotes if necessary and legal | |
76 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
76 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': | |
77 | editor = '"%s"' % editor |
|
77 | editor = '"%s"' % editor | |
78 |
|
78 | |||
79 | # Call the actual editor |
|
79 | # Call the actual editor | |
80 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
80 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: | |
81 | raise TryNext() |
|
81 | raise TryNext() | |
82 |
|
82 | |||
83 | import tempfile |
|
83 | import tempfile | |
84 | def fix_error_editor(self,filename,linenum,column,msg): |
|
84 | def fix_error_editor(self,filename,linenum,column,msg): | |
85 | """Open the editor at the given filename, linenumber, column and |
|
85 | """Open the editor at the given filename, linenumber, column and | |
86 | show an error message. This is used for correcting syntax errors. |
|
86 | show an error message. This is used for correcting syntax errors. | |
87 | The current implementation only has special support for the VIM editor, |
|
87 | The current implementation only has special support for the VIM editor, | |
88 | and falls back on the 'editor' hook if VIM is not used. |
|
88 | and falls back on the 'editor' hook if VIM is not used. | |
89 |
|
89 | |||
90 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
90 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, | |
91 | """ |
|
91 | """ | |
92 | def vim_quickfix_file(): |
|
92 | def vim_quickfix_file(): | |
93 | t = tempfile.NamedTemporaryFile() |
|
93 | t = tempfile.NamedTemporaryFile() | |
94 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
94 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) | |
95 | t.flush() |
|
95 | t.flush() | |
96 | return t |
|
96 | return t | |
97 | if os.path.basename(self.editor) != 'vim': |
|
97 | if os.path.basename(self.editor) != 'vim': | |
98 | self.hooks.editor(filename,linenum) |
|
98 | self.hooks.editor(filename,linenum) | |
99 | return |
|
99 | return | |
100 | t = vim_quickfix_file() |
|
100 | t = vim_quickfix_file() | |
101 | try: |
|
101 | try: | |
102 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
102 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): | |
103 | raise TryNext() |
|
103 | raise TryNext() | |
104 | finally: |
|
104 | finally: | |
105 | t.close() |
|
105 | t.close() | |
106 |
|
106 | |||
107 |
|
107 | |||
108 | def synchronize_with_editor(self, filename, linenum, column): |
|
108 | def synchronize_with_editor(self, filename, linenum, column): | |
109 | pass |
|
109 | pass | |
110 |
|
110 | |||
111 |
|
111 | |||
112 | class CommandChainDispatcher: |
|
112 | class CommandChainDispatcher: | |
113 | """ Dispatch calls to a chain of commands until some func can handle it |
|
113 | """ Dispatch calls to a chain of commands until some func can handle it | |
114 |
|
114 | |||
115 | Usage: instantiate, execute "add" to add commands (with optional |
|
115 | Usage: instantiate, execute "add" to add commands (with optional | |
116 | priority), execute normally via f() calling mechanism. |
|
116 | priority), execute normally via f() calling mechanism. | |
117 |
|
117 | |||
118 | """ |
|
118 | """ | |
119 | def __init__(self,commands=None): |
|
119 | def __init__(self,commands=None): | |
120 | if commands is None: |
|
120 | if commands is None: | |
121 | self.chain = [] |
|
121 | self.chain = [] | |
122 | else: |
|
122 | else: | |
123 | self.chain = commands |
|
123 | self.chain = commands | |
124 |
|
124 | |||
125 |
|
125 | |||
126 | def __call__(self,*args, **kw): |
|
126 | def __call__(self,*args, **kw): | |
127 | """ Command chain is called just like normal func. |
|
127 | """ Command chain is called just like normal func. | |
128 |
|
128 | |||
129 | This will call all funcs in chain with the same args as were given to this |
|
129 | This will call all funcs in chain with the same args as were given to this | |
130 | function, and return the result of first func that didn't raise |
|
130 | function, and return the result of first func that didn't raise | |
131 | TryNext """ |
|
131 | TryNext """ | |
132 |
|
132 | |||
133 | for prio,cmd in self.chain: |
|
133 | for prio,cmd in self.chain: | |
134 | #print "prio",prio,"cmd",cmd #dbg |
|
134 | #print "prio",prio,"cmd",cmd #dbg | |
135 | try: |
|
135 | try: | |
136 | return cmd(*args, **kw) |
|
136 | return cmd(*args, **kw) | |
137 | except TryNext, exc: |
|
137 | except TryNext, exc: | |
138 | if exc.args or exc.kwargs: |
|
138 | if exc.args or exc.kwargs: | |
139 | args = exc.args |
|
139 | args = exc.args | |
140 | kw = exc.kwargs |
|
140 | kw = exc.kwargs | |
141 | # if no function will accept it, raise TryNext up to the caller |
|
141 | # if no function will accept it, raise TryNext up to the caller | |
142 | raise TryNext |
|
142 | raise TryNext | |
143 |
|
143 | |||
144 | def __str__(self): |
|
144 | def __str__(self): | |
145 | return str(self.chain) |
|
145 | return str(self.chain) | |
146 |
|
146 | |||
147 | def add(self, func, priority=0): |
|
147 | def add(self, func, priority=0): | |
148 | """ Add a func to the cmd chain with given priority """ |
|
148 | """ Add a func to the cmd chain with given priority """ | |
149 | bisect.insort(self.chain,(priority,func)) |
|
149 | bisect.insort(self.chain,(priority,func)) | |
150 |
|
150 | |||
151 | def __iter__(self): |
|
151 | def __iter__(self): | |
152 | """ Return all objects in chain. |
|
152 | """ Return all objects in chain. | |
153 |
|
153 | |||
154 | Handy if the objects are not callable. |
|
154 | Handy if the objects are not callable. | |
155 | """ |
|
155 | """ | |
156 | return iter(self.chain) |
|
156 | return iter(self.chain) | |
157 |
|
157 | |||
158 |
|
158 | |||
159 | def result_display(self,arg): |
|
159 | def result_display(self,arg): | |
160 | """ Default display hook. |
|
160 | """ Default display hook. | |
161 |
|
161 | |||
162 | Called for displaying the result to the user. |
|
162 | Called for displaying the result to the user. | |
163 | """ |
|
163 | """ | |
164 |
|
164 | |||
165 | if self.pprint: |
|
165 | if self.pprint: | |
166 | try: |
|
166 | try: | |
167 | out = pformat(arg) |
|
167 | out = pformat(arg) | |
168 | except: |
|
168 | except: | |
169 | # Work around possible bugs in pformat |
|
169 | # Work around possible bugs in pformat | |
170 | out = repr(arg) |
|
170 | out = repr(arg) | |
171 | if '\n' in out: |
|
171 | if '\n' in out: | |
172 | # So that multi-line strings line up with the left column of |
|
172 | # So that multi-line strings line up with the left column of | |
173 | # the screen, instead of having the output prompt mess up |
|
173 | # the screen, instead of having the output prompt mess up | |
174 | # their first line. |
|
174 | # their first line. | |
175 | IPython.utils.io.Term.cout.write('\n') |
|
175 | IPython.utils.io.Term.cout.write('\n') | |
176 | print >>IPython.utils.io.Term.cout, out |
|
176 | print >>IPython.utils.io.Term.cout, out | |
177 | else: |
|
177 | else: | |
178 | # By default, the interactive prompt uses repr() to display results, |
|
178 | # By default, the interactive prompt uses repr() to display results, | |
179 | # so we should honor this. Users who'd rather use a different |
|
179 | # so we should honor this. Users who'd rather use a different | |
180 | # mechanism can easily override this hook. |
|
180 | # mechanism can easily override this hook. | |
181 | print >>IPython.utils.io.Term.cout, repr(arg) |
|
181 | print >>IPython.utils.io.Term.cout, repr(arg) | |
182 | # the default display hook doesn't manipulate the value to put in history |
|
182 | # the default display hook doesn't manipulate the value to put in history | |
183 | return None |
|
183 | return None | |
184 |
|
184 | |||
185 |
|
185 | |||
186 | def input_prefilter(self,line): |
|
186 | def input_prefilter(self,line): | |
187 | """ Default input prefilter |
|
187 | """ Default input prefilter | |
188 |
|
188 | |||
189 | This returns the line as unchanged, so that the interpreter |
|
189 | This returns the line as unchanged, so that the interpreter | |
190 | knows that nothing was done and proceeds with "classic" prefiltering |
|
190 | knows that nothing was done and proceeds with "classic" prefiltering | |
191 | (%magics, !shell commands etc.). |
|
191 | (%magics, !shell commands etc.). | |
192 |
|
192 | |||
193 | Note that leading whitespace is not passed to this hook. Prefilter |
|
193 | Note that leading whitespace is not passed to this hook. Prefilter | |
194 | can't alter indentation. |
|
194 | can't alter indentation. | |
195 |
|
195 | |||
196 | """ |
|
196 | """ | |
197 | #print "attempt to rewrite",line #dbg |
|
197 | #print "attempt to rewrite",line #dbg | |
198 | return line |
|
198 | return line | |
199 |
|
199 | |||
200 |
|
200 | |||
201 | def shutdown_hook(self): |
|
201 | def shutdown_hook(self): | |
202 | """ default shutdown hook |
|
202 | """ default shutdown hook | |
203 |
|
203 | |||
204 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
204 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done | |
205 | """ |
|
205 | """ | |
206 |
|
206 | |||
207 | #print "default shutdown hook ok" # dbg |
|
207 | #print "default shutdown hook ok" # dbg | |
208 | return |
|
208 | return | |
209 |
|
209 | |||
210 |
|
210 | |||
211 | def late_startup_hook(self): |
|
211 | def late_startup_hook(self): | |
212 | """ Executed after ipython has been constructed and configured |
|
212 | """ Executed after ipython has been constructed and configured | |
213 |
|
213 | |||
214 | """ |
|
214 | """ | |
215 | #print "default startup hook ok" # dbg |
|
215 | #print "default startup hook ok" # dbg | |
216 |
|
216 | |||
217 |
|
217 | |||
218 | def generate_prompt(self, is_continuation): |
|
218 | def generate_prompt(self, is_continuation): | |
219 | """ calculate and return a string with the prompt to display """ |
|
219 | """ calculate and return a string with the prompt to display """ | |
220 | if is_continuation: |
|
220 | if is_continuation: | |
221 | return str(self.displayhook.prompt2) |
|
221 | return str(self.displayhook.prompt2) | |
222 | return str(self.displayhook.prompt1) |
|
222 | return str(self.displayhook.prompt1) | |
223 |
|
223 | |||
224 |
|
224 | |||
225 | def show_in_pager(self,s): |
|
225 | def show_in_pager(self,s): | |
226 | """ Run a string through pager """ |
|
226 | """ Run a string through pager """ | |
227 | # raising TryNext here will use the default paging functionality |
|
227 | # raising TryNext here will use the default paging functionality | |
228 | raise TryNext |
|
228 | raise TryNext | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | def pre_prompt_hook(self): |
|
231 | def pre_prompt_hook(self): | |
232 | """ Run before displaying the next prompt |
|
232 | """ Run before displaying the next prompt | |
233 |
|
233 | |||
234 | Use this e.g. to display output from asynchronous operations (in order |
|
234 | Use this e.g. to display output from asynchronous operations (in order | |
235 | to not mess up text entry) |
|
235 | to not mess up text entry) | |
236 | """ |
|
236 | """ | |
237 |
|
237 | |||
238 | return None |
|
238 | return None | |
239 |
|
239 | |||
240 |
|
240 | |||
241 | def pre_runcode_hook(self): |
|
241 | def pre_run_code_hook(self): | |
242 | """ Executed before running the (prefiltered) code in IPython """ |
|
242 | """ Executed before running the (prefiltered) code in IPython """ | |
243 | return None |
|
243 | return None | |
244 |
|
244 | |||
245 |
|
245 | |||
246 | def clipboard_get(self): |
|
246 | def clipboard_get(self): | |
247 | """ Get text from the clipboard. |
|
247 | """ Get text from the clipboard. | |
248 | """ |
|
248 | """ | |
249 | from IPython.lib.clipboard import ( |
|
249 | from IPython.lib.clipboard import ( | |
250 | osx_clipboard_get, tkinter_clipboard_get, |
|
250 | osx_clipboard_get, tkinter_clipboard_get, | |
251 | win32_clipboard_get |
|
251 | win32_clipboard_get | |
252 | ) |
|
252 | ) | |
253 | if sys.platform == 'win32': |
|
253 | if sys.platform == 'win32': | |
254 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
254 | chain = [win32_clipboard_get, tkinter_clipboard_get] | |
255 | elif sys.platform == 'darwin': |
|
255 | elif sys.platform == 'darwin': | |
256 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
256 | chain = [osx_clipboard_get, tkinter_clipboard_get] | |
257 | else: |
|
257 | else: | |
258 | chain = [tkinter_clipboard_get] |
|
258 | chain = [tkinter_clipboard_get] | |
259 | dispatcher = CommandChainDispatcher() |
|
259 | dispatcher = CommandChainDispatcher() | |
260 | for func in chain: |
|
260 | for func in chain: | |
261 | dispatcher.add(func) |
|
261 | dispatcher.add(func) | |
262 | text = dispatcher() |
|
262 | text = dispatcher() | |
263 | return text |
|
263 | return text |
@@ -1,986 +1,1010 b'' | |||||
1 | """Analysis of text input into executable blocks. |
|
1 | """Analysis of text input into executable blocks. | |
2 |
|
2 | |||
3 | The main class in this module, :class:`InputSplitter`, is designed to break |
|
3 | The main class in this module, :class:`InputSplitter`, is designed to break | |
4 | input from either interactive, line-by-line environments or block-based ones, |
|
4 | input from either interactive, line-by-line environments or block-based ones, | |
5 | into standalone blocks that can be executed by Python as 'single' statements |
|
5 | into standalone blocks that can be executed by Python as 'single' statements | |
6 | (thus triggering sys.displayhook). |
|
6 | (thus triggering sys.displayhook). | |
7 |
|
7 | |||
8 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but |
|
8 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but | |
9 | with full support for the extended IPython syntax (magics, system calls, etc). |
|
9 | with full support for the extended IPython syntax (magics, system calls, etc). | |
10 |
|
10 | |||
11 | For more details, see the class docstring below. |
|
11 | For more details, see the class docstring below. | |
12 |
|
12 | |||
13 | Syntax Transformations |
|
13 | Syntax Transformations | |
14 | ---------------------- |
|
14 | ---------------------- | |
15 |
|
15 | |||
16 | One of the main jobs of the code in this file is to apply all syntax |
|
16 | One of the main jobs of the code in this file is to apply all syntax | |
17 | transformations that make up 'the IPython language', i.e. magics, shell |
|
17 | transformations that make up 'the IPython language', i.e. magics, shell | |
18 | escapes, etc. All transformations should be implemented as *fully stateless* |
|
18 | escapes, etc. All transformations should be implemented as *fully stateless* | |
19 | entities, that simply take one line as their input and return a line. |
|
19 | entities, that simply take one line as their input and return a line. | |
20 | Internally for implementation purposes they may be a normal function or a |
|
20 | Internally for implementation purposes they may be a normal function or a | |
21 | callable object, but the only input they receive will be a single line and they |
|
21 | callable object, but the only input they receive will be a single line and they | |
22 | should only return a line, without holding any data-dependent state between |
|
22 | should only return a line, without holding any data-dependent state between | |
23 | calls. |
|
23 | calls. | |
24 |
|
24 | |||
25 | As an example, the EscapedTransformer is a class so we can more clearly group |
|
25 | As an example, the EscapedTransformer is a class so we can more clearly group | |
26 | together the functionality of dispatching to individual functions based on the |
|
26 | together the functionality of dispatching to individual functions based on the | |
27 | starting escape character, but the only method for public use is its call |
|
27 | starting escape character, but the only method for public use is its call | |
28 | method. |
|
28 | method. | |
29 |
|
29 | |||
30 |
|
30 | |||
31 | ToDo |
|
31 | ToDo | |
32 | ---- |
|
32 | ---- | |
33 |
|
33 | |||
34 | - Should we make push() actually raise an exception once push_accepts_more() |
|
34 | - Should we make push() actually raise an exception once push_accepts_more() | |
35 | returns False? |
|
35 | returns False? | |
36 |
|
36 | |||
37 | - Naming cleanups. The tr_* names aren't the most elegant, though now they are |
|
37 | - Naming cleanups. The tr_* names aren't the most elegant, though now they are | |
38 | at least just attributes of a class so not really very exposed. |
|
38 | at least just attributes of a class so not really very exposed. | |
39 |
|
39 | |||
40 | - Think about the best way to support dynamic things: automagic, autocall, |
|
40 | - Think about the best way to support dynamic things: automagic, autocall, | |
41 | macros, etc. |
|
41 | macros, etc. | |
42 |
|
42 | |||
43 | - Think of a better heuristic for the application of the transforms in |
|
43 | - Think of a better heuristic for the application of the transforms in | |
44 | IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea: |
|
44 | IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea: | |
45 | track indentation change events (indent, dedent, nothing) and apply them only |
|
45 | track indentation change events (indent, dedent, nothing) and apply them only | |
46 | if the indentation went up, but not otherwise. |
|
46 | if the indentation went up, but not otherwise. | |
47 |
|
47 | |||
48 | - Think of the cleanest way for supporting user-specified transformations (the |
|
48 | - Think of the cleanest way for supporting user-specified transformations (the | |
49 | user prefilters we had before). |
|
49 | user prefilters we had before). | |
50 |
|
50 | |||
51 | Authors |
|
51 | Authors | |
52 | ------- |
|
52 | ------- | |
53 |
|
53 | |||
54 | * Fernando Perez |
|
54 | * Fernando Perez | |
55 | * Brian Granger |
|
55 | * Brian Granger | |
56 | """ |
|
56 | """ | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 | # Copyright (C) 2010 The IPython Development Team |
|
58 | # Copyright (C) 2010 The IPython Development Team | |
59 | # |
|
59 | # | |
60 | # Distributed under the terms of the BSD License. The full license is in |
|
60 | # Distributed under the terms of the BSD License. The full license is in | |
61 | # the file COPYING, distributed as part of this software. |
|
61 | # the file COPYING, distributed as part of this software. | |
62 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
63 | from __future__ import print_function |
|
63 | from __future__ import print_function | |
64 |
|
64 | |||
65 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
66 | # Imports |
|
66 | # Imports | |
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 | # stdlib |
|
68 | # stdlib | |
69 | import codeop |
|
69 | import codeop | |
70 | import re |
|
70 | import re | |
71 | import sys |
|
71 | import sys | |
72 |
|
72 | |||
73 | # IPython modules |
|
73 | # IPython modules | |
74 | from IPython.utils.text import make_quoted_expr |
|
74 | from IPython.utils.text import make_quoted_expr | |
75 |
|
75 | |||
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | # Globals |
|
77 | # Globals | |
78 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | # The escape sequences that define the syntax transformations IPython will |
|
80 | # The escape sequences that define the syntax transformations IPython will | |
81 | # apply to user input. These can NOT be just changed here: many regular |
|
81 | # apply to user input. These can NOT be just changed here: many regular | |
82 | # expressions and other parts of the code may use their hardcoded values, and |
|
82 | # expressions and other parts of the code may use their hardcoded values, and | |
83 | # for all intents and purposes they constitute the 'IPython syntax', so they |
|
83 | # for all intents and purposes they constitute the 'IPython syntax', so they | |
84 | # should be considered fixed. |
|
84 | # should be considered fixed. | |
85 |
|
85 | |||
86 | ESC_SHELL = '!' # Send line to underlying system shell |
|
86 | ESC_SHELL = '!' # Send line to underlying system shell | |
87 | ESC_SH_CAP = '!!' # Send line to system shell and capture output |
|
87 | ESC_SH_CAP = '!!' # Send line to system shell and capture output | |
88 | ESC_HELP = '?' # Find information about object |
|
88 | ESC_HELP = '?' # Find information about object | |
89 | ESC_HELP2 = '??' # Find extra-detailed information about object |
|
89 | ESC_HELP2 = '??' # Find extra-detailed information about object | |
90 | ESC_MAGIC = '%' # Call magic function |
|
90 | ESC_MAGIC = '%' # Call magic function | |
91 | ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call |
|
91 | ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call | |
92 | ESC_QUOTE2 = ';' # Quote all args as a single string, call |
|
92 | ESC_QUOTE2 = ';' # Quote all args as a single string, call | |
93 | ESC_PAREN = '/' # Call first argument with rest of line as arguments |
|
93 | ESC_PAREN = '/' # Call first argument with rest of line as arguments | |
94 |
|
94 | |||
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 | # Utilities |
|
96 | # Utilities | |
97 | #----------------------------------------------------------------------------- |
|
97 | #----------------------------------------------------------------------------- | |
98 |
|
98 | |||
99 | # FIXME: These are general-purpose utilities that later can be moved to the |
|
99 | # FIXME: These are general-purpose utilities that later can be moved to the | |
100 | # general ward. Kept here for now because we're being very strict about test |
|
100 | # general ward. Kept here for now because we're being very strict about test | |
101 | # coverage with this code, and this lets us ensure that we keep 100% coverage |
|
101 | # coverage with this code, and this lets us ensure that we keep 100% coverage | |
102 | # while developing. |
|
102 | # while developing. | |
103 |
|
103 | |||
104 | # compiled regexps for autoindent management |
|
104 | # compiled regexps for autoindent management | |
105 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
105 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
106 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') |
|
106 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') | |
107 |
|
107 | |||
108 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' |
|
108 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' | |
109 | # before pure comments |
|
109 | # before pure comments | |
110 | comment_line_re = re.compile('^\s*\#') |
|
110 | comment_line_re = re.compile('^\s*\#') | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def num_ini_spaces(s): |
|
113 | def num_ini_spaces(s): | |
114 | """Return the number of initial spaces in a string. |
|
114 | """Return the number of initial spaces in a string. | |
115 |
|
115 | |||
116 | Note that tabs are counted as a single space. For now, we do *not* support |
|
116 | Note that tabs are counted as a single space. For now, we do *not* support | |
117 | mixing of tabs and spaces in the user's input. |
|
117 | mixing of tabs and spaces in the user's input. | |
118 |
|
118 | |||
119 | Parameters |
|
119 | Parameters | |
120 | ---------- |
|
120 | ---------- | |
121 | s : string |
|
121 | s : string | |
122 |
|
122 | |||
123 | Returns |
|
123 | Returns | |
124 | ------- |
|
124 | ------- | |
125 | n : int |
|
125 | n : int | |
126 | """ |
|
126 | """ | |
127 |
|
127 | |||
128 | ini_spaces = ini_spaces_re.match(s) |
|
128 | ini_spaces = ini_spaces_re.match(s) | |
129 | if ini_spaces: |
|
129 | if ini_spaces: | |
130 | return ini_spaces.end() |
|
130 | return ini_spaces.end() | |
131 | else: |
|
131 | else: | |
132 | return 0 |
|
132 | return 0 | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | def remove_comments(src): |
|
135 | def remove_comments(src): | |
136 | """Remove all comments from input source. |
|
136 | """Remove all comments from input source. | |
137 |
|
137 | |||
138 | Note: comments are NOT recognized inside of strings! |
|
138 | Note: comments are NOT recognized inside of strings! | |
139 |
|
139 | |||
140 | Parameters |
|
140 | Parameters | |
141 | ---------- |
|
141 | ---------- | |
142 | src : string |
|
142 | src : string | |
143 | A single or multiline input string. |
|
143 | A single or multiline input string. | |
144 |
|
144 | |||
145 | Returns |
|
145 | Returns | |
146 | ------- |
|
146 | ------- | |
147 | String with all Python comments removed. |
|
147 | String with all Python comments removed. | |
148 | """ |
|
148 | """ | |
149 |
|
149 | |||
150 | return re.sub('#.*', '', src) |
|
150 | return re.sub('#.*', '', src) | |
151 |
|
151 | |||
152 |
|
152 | |||
153 | def get_input_encoding(): |
|
153 | def get_input_encoding(): | |
154 | """Return the default standard input encoding. |
|
154 | """Return the default standard input encoding. | |
155 |
|
155 | |||
156 | If sys.stdin has no encoding, 'ascii' is returned.""" |
|
156 | If sys.stdin has no encoding, 'ascii' is returned.""" | |
157 | # There are strange environments for which sys.stdin.encoding is None. We |
|
157 | # There are strange environments for which sys.stdin.encoding is None. We | |
158 | # ensure that a valid encoding is returned. |
|
158 | # ensure that a valid encoding is returned. | |
159 | encoding = getattr(sys.stdin, 'encoding', None) |
|
159 | encoding = getattr(sys.stdin, 'encoding', None) | |
160 | if encoding is None: |
|
160 | if encoding is None: | |
161 | encoding = 'ascii' |
|
161 | encoding = 'ascii' | |
162 | return encoding |
|
162 | return encoding | |
163 |
|
163 | |||
164 | #----------------------------------------------------------------------------- |
|
164 | #----------------------------------------------------------------------------- | |
165 | # Classes and functions for normal Python syntax handling |
|
165 | # Classes and functions for normal Python syntax handling | |
166 | #----------------------------------------------------------------------------- |
|
166 | #----------------------------------------------------------------------------- | |
167 |
|
167 | |||
168 | # HACK! This implementation, written by Robert K a while ago using the |
|
168 | # HACK! This implementation, written by Robert K a while ago using the | |
169 | # compiler module, is more robust than the other one below, but it expects its |
|
169 | # compiler module, is more robust than the other one below, but it expects its | |
170 | # input to be pure python (no ipython syntax). For now we're using it as a |
|
170 | # input to be pure python (no ipython syntax). For now we're using it as a | |
171 | # second-pass splitter after the first pass transforms the input to pure |
|
171 | # second-pass splitter after the first pass transforms the input to pure | |
172 | # python. |
|
172 | # python. | |
173 |
|
173 | |||
174 | def split_blocks(python): |
|
174 | def split_blocks(python): | |
175 | """ Split multiple lines of code into discrete commands that can be |
|
175 | """ Split multiple lines of code into discrete commands that can be | |
176 | executed singly. |
|
176 | executed singly. | |
177 |
|
177 | |||
178 | Parameters |
|
178 | Parameters | |
179 | ---------- |
|
179 | ---------- | |
180 | python : str |
|
180 | python : str | |
181 | Pure, exec'able Python code. |
|
181 | Pure, exec'able Python code. | |
182 |
|
182 | |||
183 | Returns |
|
183 | Returns | |
184 | ------- |
|
184 | ------- | |
185 | commands : list of str |
|
185 | commands : list of str | |
186 | Separate commands that can be exec'ed independently. |
|
186 | Separate commands that can be exec'ed independently. | |
187 | """ |
|
187 | """ | |
188 |
|
188 | |||
189 | import compiler |
|
189 | import compiler | |
190 |
|
190 | |||
191 | # compiler.parse treats trailing spaces after a newline as a |
|
191 | # compiler.parse treats trailing spaces after a newline as a | |
192 | # SyntaxError. This is different than codeop.CommandCompiler, which |
|
192 | # SyntaxError. This is different than codeop.CommandCompiler, which | |
193 | # will compile the trailng spaces just fine. We simply strip any |
|
193 | # will compile the trailng spaces just fine. We simply strip any | |
194 | # trailing whitespace off. Passing a string with trailing whitespace |
|
194 | # trailing whitespace off. Passing a string with trailing whitespace | |
195 | # to exec will fail however. There seems to be some inconsistency in |
|
195 | # to exec will fail however. There seems to be some inconsistency in | |
196 | # how trailing whitespace is handled, but this seems to work. |
|
196 | # how trailing whitespace is handled, but this seems to work. | |
197 | python_ori = python # save original in case we bail on error |
|
197 | python_ori = python # save original in case we bail on error | |
198 | python = python.strip() |
|
198 | python = python.strip() | |
199 |
|
199 | |||
200 | # The compiler module does not like unicode. We need to convert |
|
200 | # The compiler module does not like unicode. We need to convert | |
201 | # it encode it: |
|
201 | # it encode it: | |
202 | if isinstance(python, unicode): |
|
202 | if isinstance(python, unicode): | |
203 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 |
|
203 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 | |
204 | # encode string. |
|
204 | # encode string. | |
205 | python = '\xef\xbb\xbf' + python.encode('utf-8') |
|
205 | python = '\xef\xbb\xbf' + python.encode('utf-8') | |
206 |
|
206 | |||
207 | # The compiler module will parse the code into an abstract syntax tree. |
|
207 | # The compiler module will parse the code into an abstract syntax tree. | |
208 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! |
|
208 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! | |
209 | try: |
|
209 | try: | |
210 | ast = compiler.parse(python) |
|
210 | ast = compiler.parse(python) | |
211 | except: |
|
211 | except: | |
212 | return [python_ori] |
|
212 | return [python_ori] | |
213 |
|
213 | |||
214 | # Uncomment to help debug the ast tree |
|
214 | # Uncomment to help debug the ast tree | |
215 | # for n in ast.node: |
|
215 | # for n in ast.node: | |
216 | # print n.lineno,'->',n |
|
216 | # print n.lineno,'->',n | |
217 |
|
217 | |||
218 | # Each separate command is available by iterating over ast.node. The |
|
218 | # Each separate command is available by iterating over ast.node. The | |
219 | # lineno attribute is the line number (1-indexed) beginning the commands |
|
219 | # lineno attribute is the line number (1-indexed) beginning the commands | |
220 | # suite. |
|
220 | # suite. | |
221 | # lines ending with ";" yield a Discard Node that doesn't have a lineno |
|
221 | # lines ending with ";" yield a Discard Node that doesn't have a lineno | |
222 | # attribute. These nodes can and should be discarded. But there are |
|
222 | # attribute. These nodes can and should be discarded. But there are | |
223 | # other situations that cause Discard nodes that shouldn't be discarded. |
|
223 | # other situations that cause Discard nodes that shouldn't be discarded. | |
224 | # We might eventually discover other cases where lineno is None and have |
|
224 | # We might eventually discover other cases where lineno is None and have | |
225 | # to put in a more sophisticated test. |
|
225 | # to put in a more sophisticated test. | |
226 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] |
|
226 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] | |
227 |
|
227 | |||
228 | # When we finally get the slices, we will need to slice all the way to |
|
228 | # When we finally get the slices, we will need to slice all the way to | |
229 | # the end even though we don't have a line number for it. Fortunately, |
|
229 | # the end even though we don't have a line number for it. Fortunately, | |
230 | # None does the job nicely. |
|
230 | # None does the job nicely. | |
231 | linenos.append(None) |
|
231 | linenos.append(None) | |
232 |
|
232 | |||
233 | # Same problem at the other end: sometimes the ast tree has its |
|
233 | # Same problem at the other end: sometimes the ast tree has its | |
234 | # first complete statement not starting on line 0. In this case |
|
234 | # first complete statement not starting on line 0. In this case | |
235 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! |
|
235 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! | |
236 | linenos[0] = 0 |
|
236 | linenos[0] = 0 | |
237 |
|
237 | |||
238 | lines = python.splitlines() |
|
238 | lines = python.splitlines() | |
239 |
|
239 | |||
240 | # Create a list of atomic commands. |
|
240 | # Create a list of atomic commands. | |
241 | cmds = [] |
|
241 | cmds = [] | |
242 | for i, j in zip(linenos[:-1], linenos[1:]): |
|
242 | for i, j in zip(linenos[:-1], linenos[1:]): | |
243 | cmd = lines[i:j] |
|
243 | cmd = lines[i:j] | |
244 | if cmd: |
|
244 | if cmd: | |
245 | cmds.append('\n'.join(cmd)+'\n') |
|
245 | cmds.append('\n'.join(cmd)+'\n') | |
246 |
|
246 | |||
247 | return cmds |
|
247 | return cmds | |
248 |
|
248 | |||
249 |
|
249 | |||
250 | class InputSplitter(object): |
|
250 | class InputSplitter(object): | |
251 | """An object that can split Python source input in executable blocks. |
|
251 | """An object that can split Python source input in executable blocks. | |
252 |
|
252 | |||
253 | This object is designed to be used in one of two basic modes: |
|
253 | This object is designed to be used in one of two basic modes: | |
254 |
|
254 | |||
255 | 1. By feeding it python source line-by-line, using :meth:`push`. In this |
|
255 | 1. By feeding it python source line-by-line, using :meth:`push`. In this | |
256 | mode, it will return on each push whether the currently pushed code |
|
256 | mode, it will return on each push whether the currently pushed code | |
257 | could be executed already. In addition, it provides a method called |
|
257 | could be executed already. In addition, it provides a method called | |
258 | :meth:`push_accepts_more` that can be used to query whether more input |
|
258 | :meth:`push_accepts_more` that can be used to query whether more input | |
259 | can be pushed into a single interactive block. |
|
259 | can be pushed into a single interactive block. | |
260 |
|
260 | |||
261 | 2. By calling :meth:`split_blocks` with a single, multiline Python string, |
|
261 | 2. By calling :meth:`split_blocks` with a single, multiline Python string, | |
262 | that is then split into blocks each of which can be executed |
|
262 | that is then split into blocks each of which can be executed | |
263 | interactively as a single statement. |
|
263 | interactively as a single statement. | |
264 |
|
264 | |||
265 | This is a simple example of how an interactive terminal-based client can use |
|
265 | This is a simple example of how an interactive terminal-based client can use | |
266 | this tool:: |
|
266 | this tool:: | |
267 |
|
267 | |||
268 | isp = InputSplitter() |
|
268 | isp = InputSplitter() | |
269 | while isp.push_accepts_more(): |
|
269 | while isp.push_accepts_more(): | |
270 | indent = ' '*isp.indent_spaces |
|
270 | indent = ' '*isp.indent_spaces | |
271 | prompt = '>>> ' + indent |
|
271 | prompt = '>>> ' + indent | |
272 | line = indent + raw_input(prompt) |
|
272 | line = indent + raw_input(prompt) | |
273 | isp.push(line) |
|
273 | isp.push(line) | |
274 | print 'Input source was:\n', isp.source_reset(), |
|
274 | print 'Input source was:\n', isp.source_reset(), | |
275 | """ |
|
275 | """ | |
276 | # Number of spaces of indentation computed from input that has been pushed |
|
276 | # Number of spaces of indentation computed from input that has been pushed | |
277 | # so far. This is the attributes callers should query to get the current |
|
277 | # so far. This is the attributes callers should query to get the current | |
278 | # indentation level, in order to provide auto-indent facilities. |
|
278 | # indentation level, in order to provide auto-indent facilities. | |
279 | indent_spaces = 0 |
|
279 | indent_spaces = 0 | |
280 | # String, indicating the default input encoding. It is computed by default |
|
280 | # String, indicating the default input encoding. It is computed by default | |
281 | # at initialization time via get_input_encoding(), but it can be reset by a |
|
281 | # at initialization time via get_input_encoding(), but it can be reset by a | |
282 | # client with specific knowledge of the encoding. |
|
282 | # client with specific knowledge of the encoding. | |
283 | encoding = '' |
|
283 | encoding = '' | |
284 | # String where the current full source input is stored, properly encoded. |
|
284 | # String where the current full source input is stored, properly encoded. | |
285 | # Reading this attribute is the normal way of querying the currently pushed |
|
285 | # Reading this attribute is the normal way of querying the currently pushed | |
286 | # source code, that has been properly encoded. |
|
286 | # source code, that has been properly encoded. | |
287 | source = '' |
|
287 | source = '' | |
288 | # Code object corresponding to the current source. It is automatically |
|
288 | # Code object corresponding to the current source. It is automatically | |
289 | # synced to the source, so it can be queried at any time to obtain the code |
|
289 | # synced to the source, so it can be queried at any time to obtain the code | |
290 | # object; it will be None if the source doesn't compile to valid Python. |
|
290 | # object; it will be None if the source doesn't compile to valid Python. | |
291 | code = None |
|
291 | code = None | |
292 | # Input mode |
|
292 | # Input mode | |
293 | input_mode = 'line' |
|
293 | input_mode = 'line' | |
294 |
|
294 | |||
295 | # Private attributes |
|
295 | # Private attributes | |
296 |
|
296 | |||
297 | # List with lines of input accumulated so far |
|
297 | # List with lines of input accumulated so far | |
298 | _buffer = None |
|
298 | _buffer = None | |
299 | # Command compiler |
|
299 | # Command compiler | |
300 | _compile = None |
|
300 | _compile = None | |
301 | # Mark when input has changed indentation all the way back to flush-left |
|
301 | # Mark when input has changed indentation all the way back to flush-left | |
302 | _full_dedent = False |
|
302 | _full_dedent = False | |
303 | # Boolean indicating whether the current block is complete |
|
303 | # Boolean indicating whether the current block is complete | |
304 | _is_complete = None |
|
304 | _is_complete = None | |
305 |
|
305 | |||
306 | def __init__(self, input_mode=None): |
|
306 | def __init__(self, input_mode=None): | |
307 | """Create a new InputSplitter instance. |
|
307 | """Create a new InputSplitter instance. | |
308 |
|
308 | |||
309 | Parameters |
|
309 | Parameters | |
310 | ---------- |
|
310 | ---------- | |
311 | input_mode : str |
|
311 | input_mode : str | |
312 |
|
312 | |||
313 | One of ['line', 'cell']; default is 'line'. |
|
313 | One of ['line', 'cell']; default is 'line'. | |
314 |
|
314 | |||
315 | The input_mode parameter controls how new inputs are used when fed via |
|
315 | The input_mode parameter controls how new inputs are used when fed via | |
316 | the :meth:`push` method: |
|
316 | the :meth:`push` method: | |
317 |
|
317 | |||
318 | - 'line': meant for line-oriented clients, inputs are appended one at a |
|
318 | - 'line': meant for line-oriented clients, inputs are appended one at a | |
319 | time to the internal buffer and the whole buffer is compiled. |
|
319 | time to the internal buffer and the whole buffer is compiled. | |
320 |
|
320 | |||
321 | - 'cell': meant for clients that can edit multi-line 'cells' of text at |
|
321 | - 'cell': meant for clients that can edit multi-line 'cells' of text at | |
322 | a time. A cell can contain one or more blocks that can be compile in |
|
322 | a time. A cell can contain one or more blocks that can be compile in | |
323 | 'single' mode by Python. In this mode, each new input new input |
|
323 | 'single' mode by Python. In this mode, each new input new input | |
324 | completely replaces all prior inputs. Cell mode is thus equivalent |
|
324 | completely replaces all prior inputs. Cell mode is thus equivalent | |
325 | to prepending a full reset() to every push() call. |
|
325 | to prepending a full reset() to every push() call. | |
326 | """ |
|
326 | """ | |
327 | self._buffer = [] |
|
327 | self._buffer = [] | |
328 | self._compile = codeop.CommandCompiler() |
|
328 | self._compile = codeop.CommandCompiler() | |
329 | self.encoding = get_input_encoding() |
|
329 | self.encoding = get_input_encoding() | |
330 | self.input_mode = InputSplitter.input_mode if input_mode is None \ |
|
330 | self.input_mode = InputSplitter.input_mode if input_mode is None \ | |
331 | else input_mode |
|
331 | else input_mode | |
332 |
|
332 | |||
333 | def reset(self): |
|
333 | def reset(self): | |
334 | """Reset the input buffer and associated state.""" |
|
334 | """Reset the input buffer and associated state.""" | |
335 | self.indent_spaces = 0 |
|
335 | self.indent_spaces = 0 | |
336 | self._buffer[:] = [] |
|
336 | self._buffer[:] = [] | |
337 | self.source = '' |
|
337 | self.source = '' | |
338 | self.code = None |
|
338 | self.code = None | |
339 | self._is_complete = False |
|
339 | self._is_complete = False | |
340 | self._full_dedent = False |
|
340 | self._full_dedent = False | |
341 |
|
341 | |||
342 | def source_reset(self): |
|
342 | def source_reset(self): | |
343 | """Return the input source and perform a full reset. |
|
343 | """Return the input source and perform a full reset. | |
344 | """ |
|
344 | """ | |
345 | out = self.source |
|
345 | out = self.source | |
346 | self.reset() |
|
346 | self.reset() | |
347 | return out |
|
347 | return out | |
348 |
|
348 | |||
349 | def push(self, lines): |
|
349 | def push(self, lines): | |
350 | """Push one ore more lines of input. |
|
350 | """Push one ore more lines of input. | |
351 |
|
351 | |||
352 | This stores the given lines and returns a status code indicating |
|
352 | This stores the given lines and returns a status code indicating | |
353 | whether the code forms a complete Python block or not. |
|
353 | whether the code forms a complete Python block or not. | |
354 |
|
354 | |||
355 | Any exceptions generated in compilation are swallowed, but if an |
|
355 | Any exceptions generated in compilation are swallowed, but if an | |
356 | exception was produced, the method returns True. |
|
356 | exception was produced, the method returns True. | |
357 |
|
357 | |||
358 | Parameters |
|
358 | Parameters | |
359 | ---------- |
|
359 | ---------- | |
360 | lines : string |
|
360 | lines : string | |
361 | One or more lines of Python input. |
|
361 | One or more lines of Python input. | |
362 |
|
362 | |||
363 | Returns |
|
363 | Returns | |
364 | ------- |
|
364 | ------- | |
365 | is_complete : boolean |
|
365 | is_complete : boolean | |
366 | True if the current input source (the result of the current input |
|
366 | True if the current input source (the result of the current input | |
367 | plus prior inputs) forms a complete Python execution block. Note that |
|
367 | plus prior inputs) forms a complete Python execution block. Note that | |
368 | this value is also stored as a private attribute (_is_complete), so it |
|
368 | this value is also stored as a private attribute (_is_complete), so it | |
369 | can be queried at any time. |
|
369 | can be queried at any time. | |
370 | """ |
|
370 | """ | |
371 | if self.input_mode == 'cell': |
|
371 | if self.input_mode == 'cell': | |
372 | self.reset() |
|
372 | self.reset() | |
373 |
|
373 | |||
374 | # If the source code has leading blanks, add 'if 1:\n' to it |
|
|||
375 | # this allows execution of indented pasted code. It is tempting |
|
|||
376 | # to add '\n' at the end of source to run commands like ' a=1' |
|
|||
377 | # directly, but this fails for more complicated scenarios |
|
|||
378 |
|
||||
379 | if not self._buffer and lines[:1] in [' ', '\t'] and \ |
|
|||
380 | not comment_line_re.match(lines): |
|
|||
381 | lines = 'if 1:\n%s' % lines |
|
|||
382 |
|
||||
383 | self._store(lines) |
|
374 | self._store(lines) | |
384 | source = self.source |
|
375 | source = self.source | |
385 |
|
376 | |||
386 | # Before calling _compile(), reset the code object to None so that if an |
|
377 | # Before calling _compile(), reset the code object to None so that if an | |
387 | # exception is raised in compilation, we don't mislead by having |
|
378 | # exception is raised in compilation, we don't mislead by having | |
388 | # inconsistent code/source attributes. |
|
379 | # inconsistent code/source attributes. | |
389 | self.code, self._is_complete = None, None |
|
380 | self.code, self._is_complete = None, None | |
390 |
|
381 | |||
391 | # Honor termination lines properly |
|
382 | # Honor termination lines properly | |
392 | if source.rstrip().endswith('\\'): |
|
383 | if source.rstrip().endswith('\\'): | |
393 | return False |
|
384 | return False | |
394 |
|
385 | |||
395 | self._update_indent(lines) |
|
386 | self._update_indent(lines) | |
396 | try: |
|
387 | try: | |
397 | self.code = self._compile(source) |
|
388 | self.code = self._compile(source) | |
398 | # Invalid syntax can produce any of a number of different errors from |
|
389 | # Invalid syntax can produce any of a number of different errors from | |
399 | # inside the compiler, so we have to catch them all. Syntax errors |
|
390 | # inside the compiler, so we have to catch them all. Syntax errors | |
400 | # immediately produce a 'ready' block, so the invalid Python can be |
|
391 | # immediately produce a 'ready' block, so the invalid Python can be | |
401 | # sent to the kernel for evaluation with possible ipython |
|
392 | # sent to the kernel for evaluation with possible ipython | |
402 | # special-syntax conversion. |
|
393 | # special-syntax conversion. | |
403 | except (SyntaxError, OverflowError, ValueError, TypeError, |
|
394 | except (SyntaxError, OverflowError, ValueError, TypeError, | |
404 | MemoryError): |
|
395 | MemoryError): | |
405 | self._is_complete = True |
|
396 | self._is_complete = True | |
406 | else: |
|
397 | else: | |
407 | # Compilation didn't produce any exceptions (though it may not have |
|
398 | # Compilation didn't produce any exceptions (though it may not have | |
408 | # given a complete code object) |
|
399 | # given a complete code object) | |
409 | self._is_complete = self.code is not None |
|
400 | self._is_complete = self.code is not None | |
410 |
|
401 | |||
411 | return self._is_complete |
|
402 | return self._is_complete | |
412 |
|
403 | |||
413 | def push_accepts_more(self): |
|
404 | def push_accepts_more(self): | |
414 | """Return whether a block of interactive input can accept more input. |
|
405 | """Return whether a block of interactive input can accept more input. | |
415 |
|
406 | |||
416 | This method is meant to be used by line-oriented frontends, who need to |
|
407 | This method is meant to be used by line-oriented frontends, who need to | |
417 | guess whether a block is complete or not based solely on prior and |
|
408 | guess whether a block is complete or not based solely on prior and | |
418 | current input lines. The InputSplitter considers it has a complete |
|
409 | current input lines. The InputSplitter considers it has a complete | |
419 | interactive block and will not accept more input only when either a |
|
410 | interactive block and will not accept more input only when either a | |
420 | SyntaxError is raised, or *all* of the following are true: |
|
411 | SyntaxError is raised, or *all* of the following are true: | |
421 |
|
412 | |||
422 | 1. The input compiles to a complete statement. |
|
413 | 1. The input compiles to a complete statement. | |
423 |
|
414 | |||
424 | 2. The indentation level is flush-left (because if we are indented, |
|
415 | 2. The indentation level is flush-left (because if we are indented, | |
425 | like inside a function definition or for loop, we need to keep |
|
416 | like inside a function definition or for loop, we need to keep | |
426 | reading new input). |
|
417 | reading new input). | |
427 |
|
418 | |||
428 | 3. There is one extra line consisting only of whitespace. |
|
419 | 3. There is one extra line consisting only of whitespace. | |
429 |
|
420 | |||
430 | Because of condition #3, this method should be used only by |
|
421 | Because of condition #3, this method should be used only by | |
431 | *line-oriented* frontends, since it means that intermediate blank lines |
|
422 | *line-oriented* frontends, since it means that intermediate blank lines | |
432 | are not allowed in function definitions (or any other indented block). |
|
423 | are not allowed in function definitions (or any other indented block). | |
433 |
|
424 | |||
434 | Block-oriented frontends that have a separate keyboard event to |
|
425 | Block-oriented frontends that have a separate keyboard event to | |
435 | indicate execution should use the :meth:`split_blocks` method instead. |
|
426 | indicate execution should use the :meth:`split_blocks` method instead. | |
436 |
|
427 | |||
437 | If the current input produces a syntax error, this method immediately |
|
428 | If the current input produces a syntax error, this method immediately | |
438 | returns False but does *not* raise the syntax error exception, as |
|
429 | returns False but does *not* raise the syntax error exception, as | |
439 | typically clients will want to send invalid syntax to an execution |
|
430 | typically clients will want to send invalid syntax to an execution | |
440 | backend which might convert the invalid syntax into valid Python via |
|
431 | backend which might convert the invalid syntax into valid Python via | |
441 | one of the dynamic IPython mechanisms. |
|
432 | one of the dynamic IPython mechanisms. | |
442 | """ |
|
433 | """ | |
443 |
|
434 | |||
444 | # With incomplete input, unconditionally accept more |
|
435 | # With incomplete input, unconditionally accept more | |
445 | if not self._is_complete: |
|
436 | if not self._is_complete: | |
446 | return True |
|
437 | return True | |
447 |
|
438 | |||
448 | # If we already have complete input and we're flush left, the answer |
|
439 | # If we already have complete input and we're flush left, the answer | |
449 | # depends. In line mode, we're done. But in cell mode, we need to |
|
440 | # depends. In line mode, we're done. But in cell mode, we need to | |
450 | # check how many blocks the input so far compiles into, because if |
|
441 | # check how many blocks the input so far compiles into, because if | |
451 | # there's already more than one full independent block of input, then |
|
442 | # there's already more than one full independent block of input, then | |
452 | # the client has entered full 'cell' mode and is feeding lines that |
|
443 | # the client has entered full 'cell' mode and is feeding lines that | |
453 | # each is complete. In this case we should then keep accepting. |
|
444 | # each is complete. In this case we should then keep accepting. | |
454 | # The Qt terminal-like console does precisely this, to provide the |
|
445 | # The Qt terminal-like console does precisely this, to provide the | |
455 | # convenience of terminal-like input of single expressions, but |
|
446 | # convenience of terminal-like input of single expressions, but | |
456 | # allowing the user (with a separate keystroke) to switch to 'cell' |
|
447 | # allowing the user (with a separate keystroke) to switch to 'cell' | |
457 | # mode and type multiple expressions in one shot. |
|
448 | # mode and type multiple expressions in one shot. | |
458 | if self.indent_spaces==0: |
|
449 | if self.indent_spaces==0: | |
459 | if self.input_mode=='line': |
|
450 | if self.input_mode=='line': | |
460 | return False |
|
451 | return False | |
461 | else: |
|
452 | else: | |
462 | nblocks = len(split_blocks(''.join(self._buffer))) |
|
453 | nblocks = len(split_blocks(''.join(self._buffer))) | |
463 | if nblocks==1: |
|
454 | if nblocks==1: | |
464 | return False |
|
455 | return False | |
465 |
|
456 | |||
466 | # When input is complete, then termination is marked by an extra blank |
|
457 | # When input is complete, then termination is marked by an extra blank | |
467 | # line at the end. |
|
458 | # line at the end. | |
468 | last_line = self.source.splitlines()[-1] |
|
459 | last_line = self.source.splitlines()[-1] | |
469 | return bool(last_line and not last_line.isspace()) |
|
460 | return bool(last_line and not last_line.isspace()) | |
470 |
|
461 | |||
471 | def split_blocks(self, lines): |
|
462 | def split_blocks(self, lines): | |
472 | """Split a multiline string into multiple input blocks. |
|
463 | """Split a multiline string into multiple input blocks. | |
473 |
|
464 | |||
474 | Note: this method starts by performing a full reset(). |
|
465 | Note: this method starts by performing a full reset(). | |
475 |
|
466 | |||
476 | Parameters |
|
467 | Parameters | |
477 | ---------- |
|
468 | ---------- | |
478 | lines : str |
|
469 | lines : str | |
479 | A possibly multiline string. |
|
470 | A possibly multiline string. | |
480 |
|
471 | |||
481 | Returns |
|
472 | Returns | |
482 | ------- |
|
473 | ------- | |
483 | blocks : list |
|
474 | blocks : list | |
484 | A list of strings, each possibly multiline. Each string corresponds |
|
475 | A list of strings, each possibly multiline. Each string corresponds | |
485 | to a single block that can be compiled in 'single' mode (unless it |
|
476 | to a single block that can be compiled in 'single' mode (unless it | |
486 | has a syntax error).""" |
|
477 | has a syntax error).""" | |
487 |
|
478 | |||
488 | # This code is fairly delicate. If you make any changes here, make |
|
479 | # This code is fairly delicate. If you make any changes here, make | |
489 | # absolutely sure that you do run the full test suite and ALL tests |
|
480 | # absolutely sure that you do run the full test suite and ALL tests | |
490 | # pass. |
|
481 | # pass. | |
491 |
|
482 | |||
492 | self.reset() |
|
483 | self.reset() | |
493 | blocks = [] |
|
484 | blocks = [] | |
494 |
|
485 | |||
495 | # Reversed copy so we can use pop() efficiently and consume the input |
|
486 | # Reversed copy so we can use pop() efficiently and consume the input | |
496 | # as a stack |
|
487 | # as a stack | |
497 | lines = lines.splitlines()[::-1] |
|
488 | lines = lines.splitlines()[::-1] | |
498 | # Outer loop over all input |
|
489 | # Outer loop over all input | |
499 | while lines: |
|
490 | while lines: | |
500 | #print 'Current lines:', lines # dbg |
|
491 | #print 'Current lines:', lines # dbg | |
501 | # Inner loop to build each block |
|
492 | # Inner loop to build each block | |
502 | while True: |
|
493 | while True: | |
503 | # Safety exit from inner loop |
|
494 | # Safety exit from inner loop | |
504 | if not lines: |
|
495 | if not lines: | |
505 | break |
|
496 | break | |
506 | # Grab next line but don't push it yet |
|
497 | # Grab next line but don't push it yet | |
507 | next_line = lines.pop() |
|
498 | next_line = lines.pop() | |
508 | # Blank/empty lines are pushed as-is |
|
499 | # Blank/empty lines are pushed as-is | |
509 | if not next_line or next_line.isspace(): |
|
500 | if not next_line or next_line.isspace(): | |
510 | self.push(next_line) |
|
501 | self.push(next_line) | |
511 | continue |
|
502 | continue | |
512 |
|
503 | |||
513 | # Check indentation changes caused by the *next* line |
|
504 | # Check indentation changes caused by the *next* line | |
514 | indent_spaces, _full_dedent = self._find_indent(next_line) |
|
505 | indent_spaces, _full_dedent = self._find_indent(next_line) | |
515 |
|
506 | |||
516 | # If the next line causes a dedent, it can be for two differnt |
|
507 | # If the next line causes a dedent, it can be for two differnt | |
517 | # reasons: either an explicit de-dent by the user or a |
|
508 | # reasons: either an explicit de-dent by the user or a | |
518 | # return/raise/pass statement. These MUST be handled |
|
509 | # return/raise/pass statement. These MUST be handled | |
519 | # separately: |
|
510 | # separately: | |
520 | # |
|
511 | # | |
521 | # 1. the first case is only detected when the actual explicit |
|
512 | # 1. the first case is only detected when the actual explicit | |
522 | # dedent happens, and that would be the *first* line of a *new* |
|
513 | # dedent happens, and that would be the *first* line of a *new* | |
523 | # block. Thus, we must put the line back into the input buffer |
|
514 | # block. Thus, we must put the line back into the input buffer | |
524 | # so that it starts a new block on the next pass. |
|
515 | # so that it starts a new block on the next pass. | |
525 | # |
|
516 | # | |
526 | # 2. the second case is detected in the line before the actual |
|
517 | # 2. the second case is detected in the line before the actual | |
527 | # dedent happens, so , we consume the line and we can break out |
|
518 | # dedent happens, so , we consume the line and we can break out | |
528 | # to start a new block. |
|
519 | # to start a new block. | |
529 |
|
520 | |||
530 | # Case 1, explicit dedent causes a break. |
|
521 | # Case 1, explicit dedent causes a break. | |
531 | # Note: check that we weren't on the very last line, else we'll |
|
522 | # Note: check that we weren't on the very last line, else we'll | |
532 | # enter an infinite loop adding/removing the last line. |
|
523 | # enter an infinite loop adding/removing the last line. | |
533 | if _full_dedent and lines and not next_line.startswith(' '): |
|
524 | if _full_dedent and lines and not next_line.startswith(' '): | |
534 | lines.append(next_line) |
|
525 | lines.append(next_line) | |
535 | break |
|
526 | break | |
536 |
|
527 | |||
537 | # Otherwise any line is pushed |
|
528 | # Otherwise any line is pushed | |
538 | self.push(next_line) |
|
529 | self.push(next_line) | |
539 |
|
530 | |||
540 | # Case 2, full dedent with full block ready: |
|
531 | # Case 2, full dedent with full block ready: | |
541 | if _full_dedent or \ |
|
532 | if _full_dedent or \ | |
542 | self.indent_spaces==0 and not self.push_accepts_more(): |
|
533 | self.indent_spaces==0 and not self.push_accepts_more(): | |
543 | break |
|
534 | break | |
544 | # Form the new block with the current source input |
|
535 | # Form the new block with the current source input | |
545 | blocks.append(self.source_reset()) |
|
536 | blocks.append(self.source_reset()) | |
546 |
|
537 | |||
547 | #return blocks |
|
538 | #return blocks | |
548 | # HACK!!! Now that our input is in blocks but guaranteed to be pure |
|
539 | # HACK!!! Now that our input is in blocks but guaranteed to be pure | |
549 | # python syntax, feed it back a second time through the AST-based |
|
540 | # python syntax, feed it back a second time through the AST-based | |
550 | # splitter, which is more accurate than ours. |
|
541 | # splitter, which is more accurate than ours. | |
551 | return split_blocks(''.join(blocks)) |
|
542 | return split_blocks(''.join(blocks)) | |
552 |
|
543 | |||
553 | #------------------------------------------------------------------------ |
|
544 | #------------------------------------------------------------------------ | |
554 | # Private interface |
|
545 | # Private interface | |
555 | #------------------------------------------------------------------------ |
|
546 | #------------------------------------------------------------------------ | |
556 |
|
547 | |||
557 | def _find_indent(self, line): |
|
548 | def _find_indent(self, line): | |
558 | """Compute the new indentation level for a single line. |
|
549 | """Compute the new indentation level for a single line. | |
559 |
|
550 | |||
560 | Parameters |
|
551 | Parameters | |
561 | ---------- |
|
552 | ---------- | |
562 | line : str |
|
553 | line : str | |
563 | A single new line of non-whitespace, non-comment Python input. |
|
554 | A single new line of non-whitespace, non-comment Python input. | |
564 |
|
555 | |||
565 | Returns |
|
556 | Returns | |
566 | ------- |
|
557 | ------- | |
567 | indent_spaces : int |
|
558 | indent_spaces : int | |
568 | New value for the indent level (it may be equal to self.indent_spaces |
|
559 | New value for the indent level (it may be equal to self.indent_spaces | |
569 | if indentation doesn't change. |
|
560 | if indentation doesn't change. | |
570 |
|
561 | |||
571 | full_dedent : boolean |
|
562 | full_dedent : boolean | |
572 | Whether the new line causes a full flush-left dedent. |
|
563 | Whether the new line causes a full flush-left dedent. | |
573 | """ |
|
564 | """ | |
574 | indent_spaces = self.indent_spaces |
|
565 | indent_spaces = self.indent_spaces | |
575 | full_dedent = self._full_dedent |
|
566 | full_dedent = self._full_dedent | |
576 |
|
567 | |||
577 | inisp = num_ini_spaces(line) |
|
568 | inisp = num_ini_spaces(line) | |
578 | if inisp < indent_spaces: |
|
569 | if inisp < indent_spaces: | |
579 | indent_spaces = inisp |
|
570 | indent_spaces = inisp | |
580 | if indent_spaces <= 0: |
|
571 | if indent_spaces <= 0: | |
581 | #print 'Full dedent in text',self.source # dbg |
|
572 | #print 'Full dedent in text',self.source # dbg | |
582 | full_dedent = True |
|
573 | full_dedent = True | |
583 |
|
574 | |||
584 | if line[-1] == ':': |
|
575 | if line[-1] == ':': | |
585 | indent_spaces += 4 |
|
576 | indent_spaces += 4 | |
586 | elif dedent_re.match(line): |
|
577 | elif dedent_re.match(line): | |
587 | indent_spaces -= 4 |
|
578 | indent_spaces -= 4 | |
588 | if indent_spaces <= 0: |
|
579 | if indent_spaces <= 0: | |
589 | full_dedent = True |
|
580 | full_dedent = True | |
590 |
|
581 | |||
591 | # Safety |
|
582 | # Safety | |
592 | if indent_spaces < 0: |
|
583 | if indent_spaces < 0: | |
593 | indent_spaces = 0 |
|
584 | indent_spaces = 0 | |
594 | #print 'safety' # dbg |
|
585 | #print 'safety' # dbg | |
595 |
|
586 | |||
596 | return indent_spaces, full_dedent |
|
587 | return indent_spaces, full_dedent | |
597 |
|
|
588 | ||
598 | def _update_indent(self, lines): |
|
589 | def _update_indent(self, lines): | |
599 | for line in remove_comments(lines).splitlines(): |
|
590 | for line in remove_comments(lines).splitlines(): | |
600 | if line and not line.isspace(): |
|
591 | if line and not line.isspace(): | |
601 | self.indent_spaces, self._full_dedent = self._find_indent(line) |
|
592 | self.indent_spaces, self._full_dedent = self._find_indent(line) | |
602 |
|
593 | |||
603 | def _store(self, lines): |
|
594 | def _store(self, lines, buffer=None, store='source'): | |
604 | """Store one or more lines of input. |
|
595 | """Store one or more lines of input. | |
605 |
|
596 | |||
606 | If input lines are not newline-terminated, a newline is automatically |
|
597 | If input lines are not newline-terminated, a newline is automatically | |
607 | appended.""" |
|
598 | appended.""" | |
608 |
|
599 | |||
|
600 | if buffer is None: | |||
|
601 | buffer = self._buffer | |||
|
602 | ||||
609 | if lines.endswith('\n'): |
|
603 | if lines.endswith('\n'): | |
610 |
|
|
604 | buffer.append(lines) | |
611 | else: |
|
605 | else: | |
612 |
|
|
606 | buffer.append(lines+'\n') | |
613 | self._set_source() |
|
607 | setattr(self, store, self._set_source(buffer)) | |
614 |
|
608 | |||
615 | def _set_source(self): |
|
609 | def _set_source(self, buffer): | |
616 |
|
|
610 | return ''.join(buffer).encode(self.encoding) | |
617 |
|
611 | |||
618 |
|
612 | |||
619 | #----------------------------------------------------------------------------- |
|
613 | #----------------------------------------------------------------------------- | |
620 | # Functions and classes for IPython-specific syntactic support |
|
614 | # Functions and classes for IPython-specific syntactic support | |
621 | #----------------------------------------------------------------------------- |
|
615 | #----------------------------------------------------------------------------- | |
622 |
|
616 | |||
623 | # RegExp for splitting line contents into pre-char//first word-method//rest. |
|
617 | # RegExp for splitting line contents into pre-char//first word-method//rest. | |
624 | # For clarity, each group in on one line. |
|
618 | # For clarity, each group in on one line. | |
625 |
|
619 | |||
626 | line_split = re.compile(""" |
|
620 | line_split = re.compile(""" | |
627 | ^(\s*) # any leading space |
|
621 | ^(\s*) # any leading space | |
628 | ([,;/%]|!!?|\?\??) # escape character or characters |
|
622 | ([,;/%]|!!?|\?\??) # escape character or characters | |
629 | \s*(%?[\w\.\*]*) # function/method, possibly with leading % |
|
623 | \s*(%?[\w\.\*]*) # function/method, possibly with leading % | |
630 | # to correctly treat things like '?%magic' |
|
624 | # to correctly treat things like '?%magic' | |
631 | (\s+.*$|$) # rest of line |
|
625 | (\s+.*$|$) # rest of line | |
632 | """, re.VERBOSE) |
|
626 | """, re.VERBOSE) | |
633 |
|
627 | |||
634 |
|
628 | |||
635 | def split_user_input(line): |
|
629 | def split_user_input(line): | |
636 | """Split user input into early whitespace, esc-char, function part and rest. |
|
630 | """Split user input into early whitespace, esc-char, function part and rest. | |
637 |
|
631 | |||
638 | This is currently handles lines with '=' in them in a very inconsistent |
|
632 | This is currently handles lines with '=' in them in a very inconsistent | |
639 | manner. |
|
633 | manner. | |
640 |
|
634 | |||
641 | Examples |
|
635 | Examples | |
642 | ======== |
|
636 | ======== | |
643 | >>> split_user_input('x=1') |
|
637 | >>> split_user_input('x=1') | |
644 | ('', '', 'x=1', '') |
|
638 | ('', '', 'x=1', '') | |
645 | >>> split_user_input('?') |
|
639 | >>> split_user_input('?') | |
646 | ('', '?', '', '') |
|
640 | ('', '?', '', '') | |
647 | >>> split_user_input('??') |
|
641 | >>> split_user_input('??') | |
648 | ('', '??', '', '') |
|
642 | ('', '??', '', '') | |
649 | >>> split_user_input(' ?') |
|
643 | >>> split_user_input(' ?') | |
650 | (' ', '?', '', '') |
|
644 | (' ', '?', '', '') | |
651 | >>> split_user_input(' ??') |
|
645 | >>> split_user_input(' ??') | |
652 | (' ', '??', '', '') |
|
646 | (' ', '??', '', '') | |
653 | >>> split_user_input('??x') |
|
647 | >>> split_user_input('??x') | |
654 | ('', '??', 'x', '') |
|
648 | ('', '??', 'x', '') | |
655 | >>> split_user_input('?x=1') |
|
649 | >>> split_user_input('?x=1') | |
656 | ('', '', '?x=1', '') |
|
650 | ('', '', '?x=1', '') | |
657 | >>> split_user_input('!ls') |
|
651 | >>> split_user_input('!ls') | |
658 | ('', '!', 'ls', '') |
|
652 | ('', '!', 'ls', '') | |
659 | >>> split_user_input(' !ls') |
|
653 | >>> split_user_input(' !ls') | |
660 | (' ', '!', 'ls', '') |
|
654 | (' ', '!', 'ls', '') | |
661 | >>> split_user_input('!!ls') |
|
655 | >>> split_user_input('!!ls') | |
662 | ('', '!!', 'ls', '') |
|
656 | ('', '!!', 'ls', '') | |
663 | >>> split_user_input(' !!ls') |
|
657 | >>> split_user_input(' !!ls') | |
664 | (' ', '!!', 'ls', '') |
|
658 | (' ', '!!', 'ls', '') | |
665 | >>> split_user_input(',ls') |
|
659 | >>> split_user_input(',ls') | |
666 | ('', ',', 'ls', '') |
|
660 | ('', ',', 'ls', '') | |
667 | >>> split_user_input(';ls') |
|
661 | >>> split_user_input(';ls') | |
668 | ('', ';', 'ls', '') |
|
662 | ('', ';', 'ls', '') | |
669 | >>> split_user_input(' ;ls') |
|
663 | >>> split_user_input(' ;ls') | |
670 | (' ', ';', 'ls', '') |
|
664 | (' ', ';', 'ls', '') | |
671 | >>> split_user_input('f.g(x)') |
|
665 | >>> split_user_input('f.g(x)') | |
672 | ('', '', 'f.g(x)', '') |
|
666 | ('', '', 'f.g(x)', '') | |
673 | >>> split_user_input('f.g (x)') |
|
667 | >>> split_user_input('f.g (x)') | |
674 | ('', '', 'f.g', '(x)') |
|
668 | ('', '', 'f.g', '(x)') | |
675 | >>> split_user_input('?%hist') |
|
669 | >>> split_user_input('?%hist') | |
676 | ('', '?', '%hist', '') |
|
670 | ('', '?', '%hist', '') | |
677 | >>> split_user_input('?x*') |
|
671 | >>> split_user_input('?x*') | |
678 | ('', '?', 'x*', '') |
|
672 | ('', '?', 'x*', '') | |
679 | """ |
|
673 | """ | |
680 | match = line_split.match(line) |
|
674 | match = line_split.match(line) | |
681 | if match: |
|
675 | if match: | |
682 | lspace, esc, fpart, rest = match.groups() |
|
676 | lspace, esc, fpart, rest = match.groups() | |
683 | else: |
|
677 | else: | |
684 | # print "match failed for line '%s'" % line |
|
678 | # print "match failed for line '%s'" % line | |
685 | try: |
|
679 | try: | |
686 | fpart, rest = line.split(None, 1) |
|
680 | fpart, rest = line.split(None, 1) | |
687 | except ValueError: |
|
681 | except ValueError: | |
688 | # print "split failed for line '%s'" % line |
|
682 | # print "split failed for line '%s'" % line | |
689 | fpart, rest = line,'' |
|
683 | fpart, rest = line,'' | |
690 | lspace = re.match('^(\s*)(.*)', line).groups()[0] |
|
684 | lspace = re.match('^(\s*)(.*)', line).groups()[0] | |
691 | esc = '' |
|
685 | esc = '' | |
692 |
|
686 | |||
693 | # fpart has to be a valid python identifier, so it better be only pure |
|
687 | # fpart has to be a valid python identifier, so it better be only pure | |
694 | # ascii, no unicode: |
|
688 | # ascii, no unicode: | |
695 | try: |
|
689 | try: | |
696 | fpart = fpart.encode('ascii') |
|
690 | fpart = fpart.encode('ascii') | |
697 | except UnicodeEncodeError: |
|
691 | except UnicodeEncodeError: | |
698 | lspace = unicode(lspace) |
|
692 | lspace = unicode(lspace) | |
699 | rest = fpart + u' ' + rest |
|
693 | rest = fpart + u' ' + rest | |
700 | fpart = u'' |
|
694 | fpart = u'' | |
701 |
|
695 | |||
702 | #print 'line:<%s>' % line # dbg |
|
696 | #print 'line:<%s>' % line # dbg | |
703 | #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg |
|
697 | #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg | |
704 | return lspace, esc, fpart.strip(), rest.lstrip() |
|
698 | return lspace, esc, fpart.strip(), rest.lstrip() | |
705 |
|
699 | |||
706 |
|
700 | |||
707 | # The escaped translators ALL receive a line where their own escape has been |
|
701 | # The escaped translators ALL receive a line where their own escape has been | |
708 | # stripped. Only '?' is valid at the end of the line, all others can only be |
|
702 | # stripped. Only '?' is valid at the end of the line, all others can only be | |
709 | # placed at the start. |
|
703 | # placed at the start. | |
710 |
|
704 | |||
711 | class LineInfo(object): |
|
705 | class LineInfo(object): | |
712 | """A single line of input and associated info. |
|
706 | """A single line of input and associated info. | |
713 |
|
707 | |||
714 | This is a utility class that mostly wraps the output of |
|
708 | This is a utility class that mostly wraps the output of | |
715 | :func:`split_user_input` into a convenient object to be passed around |
|
709 | :func:`split_user_input` into a convenient object to be passed around | |
716 | during input transformations. |
|
710 | during input transformations. | |
717 |
|
711 | |||
718 | Includes the following as properties: |
|
712 | Includes the following as properties: | |
719 |
|
713 | |||
720 | line |
|
714 | line | |
721 | The original, raw line |
|
715 | The original, raw line | |
722 |
|
716 | |||
723 | lspace |
|
717 | lspace | |
724 | Any early whitespace before actual text starts. |
|
718 | Any early whitespace before actual text starts. | |
725 |
|
719 | |||
726 | esc |
|
720 | esc | |
727 | The initial esc character (or characters, for double-char escapes like |
|
721 | The initial esc character (or characters, for double-char escapes like | |
728 | '??' or '!!'). |
|
722 | '??' or '!!'). | |
729 |
|
723 | |||
730 | fpart |
|
724 | fpart | |
731 | The 'function part', which is basically the maximal initial sequence |
|
725 | The 'function part', which is basically the maximal initial sequence | |
732 | of valid python identifiers and the '.' character. This is what is |
|
726 | of valid python identifiers and the '.' character. This is what is | |
733 | checked for alias and magic transformations, used for auto-calling, |
|
727 | checked for alias and magic transformations, used for auto-calling, | |
734 | etc. |
|
728 | etc. | |
735 |
|
729 | |||
736 | rest |
|
730 | rest | |
737 | Everything else on the line. |
|
731 | Everything else on the line. | |
738 | """ |
|
732 | """ | |
739 | def __init__(self, line): |
|
733 | def __init__(self, line): | |
740 | self.line = line |
|
734 | self.line = line | |
741 | self.lspace, self.esc, self.fpart, self.rest = \ |
|
735 | self.lspace, self.esc, self.fpart, self.rest = \ | |
742 | split_user_input(line) |
|
736 | split_user_input(line) | |
743 |
|
737 | |||
744 | def __str__(self): |
|
738 | def __str__(self): | |
745 | return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc, |
|
739 | return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc, | |
746 | self.fpart, self.rest) |
|
740 | self.fpart, self.rest) | |
747 |
|
741 | |||
748 |
|
742 | |||
749 | # Transformations of the special syntaxes that don't rely on an explicit escape |
|
743 | # Transformations of the special syntaxes that don't rely on an explicit escape | |
750 | # character but instead on patterns on the input line |
|
744 | # character but instead on patterns on the input line | |
751 |
|
745 | |||
752 | # The core transformations are implemented as standalone functions that can be |
|
746 | # The core transformations are implemented as standalone functions that can be | |
753 | # tested and validated in isolation. Each of these uses a regexp, we |
|
747 | # tested and validated in isolation. Each of these uses a regexp, we | |
754 | # pre-compile these and keep them close to each function definition for clarity |
|
748 | # pre-compile these and keep them close to each function definition for clarity | |
755 |
|
749 | |||
756 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
750 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
757 | r'\s*=\s*!\s*(?P<cmd>.*)') |
|
751 | r'\s*=\s*!\s*(?P<cmd>.*)') | |
758 |
|
752 | |||
759 | def transform_assign_system(line): |
|
753 | def transform_assign_system(line): | |
760 | """Handle the `files = !ls` syntax.""" |
|
754 | """Handle the `files = !ls` syntax.""" | |
761 | m = _assign_system_re.match(line) |
|
755 | m = _assign_system_re.match(line) | |
762 | if m is not None: |
|
756 | if m is not None: | |
763 | cmd = m.group('cmd') |
|
757 | cmd = m.group('cmd') | |
764 | lhs = m.group('lhs') |
|
758 | lhs = m.group('lhs') | |
765 | expr = make_quoted_expr(cmd) |
|
759 | expr = make_quoted_expr(cmd) | |
766 | new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr) |
|
760 | new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr) | |
767 | return new_line |
|
761 | return new_line | |
768 | return line |
|
762 | return line | |
769 |
|
763 | |||
770 |
|
764 | |||
771 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
765 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
772 | r'\s*=\s*%\s*(?P<cmd>.*)') |
|
766 | r'\s*=\s*%\s*(?P<cmd>.*)') | |
773 |
|
767 | |||
774 | def transform_assign_magic(line): |
|
768 | def transform_assign_magic(line): | |
775 | """Handle the `a = %who` syntax.""" |
|
769 | """Handle the `a = %who` syntax.""" | |
776 | m = _assign_magic_re.match(line) |
|
770 | m = _assign_magic_re.match(line) | |
777 | if m is not None: |
|
771 | if m is not None: | |
778 | cmd = m.group('cmd') |
|
772 | cmd = m.group('cmd') | |
779 | lhs = m.group('lhs') |
|
773 | lhs = m.group('lhs') | |
780 | expr = make_quoted_expr(cmd) |
|
774 | expr = make_quoted_expr(cmd) | |
781 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
775 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
782 | return new_line |
|
776 | return new_line | |
783 | return line |
|
777 | return line | |
784 |
|
778 | |||
785 |
|
779 | |||
786 | _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )') |
|
780 | _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )') | |
787 |
|
781 | |||
788 | def transform_classic_prompt(line): |
|
782 | def transform_classic_prompt(line): | |
789 | """Handle inputs that start with '>>> ' syntax.""" |
|
783 | """Handle inputs that start with '>>> ' syntax.""" | |
790 |
|
784 | |||
791 | if not line or line.isspace(): |
|
785 | if not line or line.isspace(): | |
792 | return line |
|
786 | return line | |
793 | m = _classic_prompt_re.match(line) |
|
787 | m = _classic_prompt_re.match(line) | |
794 | if m: |
|
788 | if m: | |
795 | return line[len(m.group(0)):] |
|
789 | return line[len(m.group(0)):] | |
796 | else: |
|
790 | else: | |
797 | return line |
|
791 | return line | |
798 |
|
792 | |||
799 |
|
793 | |||
800 | _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
794 | _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
801 |
|
795 | |||
802 | def transform_ipy_prompt(line): |
|
796 | def transform_ipy_prompt(line): | |
803 | """Handle inputs that start classic IPython prompt syntax.""" |
|
797 | """Handle inputs that start classic IPython prompt syntax.""" | |
804 |
|
798 | |||
805 | if not line or line.isspace(): |
|
799 | if not line or line.isspace(): | |
806 | return line |
|
800 | return line | |
807 | #print 'LINE: %r' % line # dbg |
|
801 | #print 'LINE: %r' % line # dbg | |
808 | m = _ipy_prompt_re.match(line) |
|
802 | m = _ipy_prompt_re.match(line) | |
809 | if m: |
|
803 | if m: | |
810 | #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg |
|
804 | #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg | |
811 | return line[len(m.group(0)):] |
|
805 | return line[len(m.group(0)):] | |
812 | else: |
|
806 | else: | |
813 | return line |
|
807 | return line | |
814 |
|
808 | |||
815 |
|
809 | |||
816 | class EscapedTransformer(object): |
|
810 | class EscapedTransformer(object): | |
817 | """Class to transform lines that are explicitly escaped out.""" |
|
811 | """Class to transform lines that are explicitly escaped out.""" | |
818 |
|
812 | |||
819 | def __init__(self): |
|
813 | def __init__(self): | |
820 | tr = { ESC_SHELL : self._tr_system, |
|
814 | tr = { ESC_SHELL : self._tr_system, | |
821 | ESC_SH_CAP : self._tr_system2, |
|
815 | ESC_SH_CAP : self._tr_system2, | |
822 | ESC_HELP : self._tr_help, |
|
816 | ESC_HELP : self._tr_help, | |
823 | ESC_HELP2 : self._tr_help, |
|
817 | ESC_HELP2 : self._tr_help, | |
824 | ESC_MAGIC : self._tr_magic, |
|
818 | ESC_MAGIC : self._tr_magic, | |
825 | ESC_QUOTE : self._tr_quote, |
|
819 | ESC_QUOTE : self._tr_quote, | |
826 | ESC_QUOTE2 : self._tr_quote2, |
|
820 | ESC_QUOTE2 : self._tr_quote2, | |
827 | ESC_PAREN : self._tr_paren } |
|
821 | ESC_PAREN : self._tr_paren } | |
828 | self.tr = tr |
|
822 | self.tr = tr | |
829 |
|
823 | |||
830 | # Support for syntax transformations that use explicit escapes typed by the |
|
824 | # Support for syntax transformations that use explicit escapes typed by the | |
831 | # user at the beginning of a line |
|
825 | # user at the beginning of a line | |
832 | @staticmethod |
|
826 | @staticmethod | |
833 | def _tr_system(line_info): |
|
827 | def _tr_system(line_info): | |
834 | "Translate lines escaped with: !" |
|
828 | "Translate lines escaped with: !" | |
835 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) |
|
829 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) | |
836 | return '%sget_ipython().system(%s)' % (line_info.lspace, |
|
830 | return '%sget_ipython().system(%s)' % (line_info.lspace, | |
837 | make_quoted_expr(cmd)) |
|
831 | make_quoted_expr(cmd)) | |
838 |
|
832 | |||
839 | @staticmethod |
|
833 | @staticmethod | |
840 | def _tr_system2(line_info): |
|
834 | def _tr_system2(line_info): | |
841 | "Translate lines escaped with: !!" |
|
835 | "Translate lines escaped with: !!" | |
842 | cmd = line_info.line.lstrip()[2:] |
|
836 | cmd = line_info.line.lstrip()[2:] | |
843 | return '%sget_ipython().getoutput(%s)' % (line_info.lspace, |
|
837 | return '%sget_ipython().getoutput(%s)' % (line_info.lspace, | |
844 | make_quoted_expr(cmd)) |
|
838 | make_quoted_expr(cmd)) | |
845 |
|
839 | |||
846 | @staticmethod |
|
840 | @staticmethod | |
847 | def _tr_help(line_info): |
|
841 | def _tr_help(line_info): | |
848 | "Translate lines escaped with: ?/??" |
|
842 | "Translate lines escaped with: ?/??" | |
849 | # A naked help line should just fire the intro help screen |
|
843 | # A naked help line should just fire the intro help screen | |
850 | if not line_info.line[1:]: |
|
844 | if not line_info.line[1:]: | |
851 | return 'get_ipython().show_usage()' |
|
845 | return 'get_ipython().show_usage()' | |
852 |
|
846 | |||
853 | # There may be one or two '?' at the end, move them to the front so that |
|
847 | # There may be one or two '?' at the end, move them to the front so that | |
854 | # the rest of the logic can assume escapes are at the start |
|
848 | # the rest of the logic can assume escapes are at the start | |
855 | l_ori = line_info |
|
849 | l_ori = line_info | |
856 | line = line_info.line |
|
850 | line = line_info.line | |
857 | if line.endswith('?'): |
|
851 | if line.endswith('?'): | |
858 | line = line[-1] + line[:-1] |
|
852 | line = line[-1] + line[:-1] | |
859 | if line.endswith('?'): |
|
853 | if line.endswith('?'): | |
860 | line = line[-1] + line[:-1] |
|
854 | line = line[-1] + line[:-1] | |
861 | line_info = LineInfo(line) |
|
855 | line_info = LineInfo(line) | |
862 |
|
856 | |||
863 | # From here on, simply choose which level of detail to get, and |
|
857 | # From here on, simply choose which level of detail to get, and | |
864 | # special-case the psearch syntax |
|
858 | # special-case the psearch syntax | |
865 | pinfo = 'pinfo' # default |
|
859 | pinfo = 'pinfo' # default | |
866 | if '*' in line_info.line: |
|
860 | if '*' in line_info.line: | |
867 | pinfo = 'psearch' |
|
861 | pinfo = 'psearch' | |
868 | elif line_info.esc == '??': |
|
862 | elif line_info.esc == '??': | |
869 | pinfo = 'pinfo2' |
|
863 | pinfo = 'pinfo2' | |
870 |
|
864 | |||
871 | tpl = '%sget_ipython().magic("%s %s")' |
|
865 | tpl = '%sget_ipython().magic("%s %s")' | |
872 | return tpl % (line_info.lspace, pinfo, |
|
866 | return tpl % (line_info.lspace, pinfo, | |
873 | ' '.join([line_info.fpart, line_info.rest]).strip()) |
|
867 | ' '.join([line_info.fpart, line_info.rest]).strip()) | |
874 |
|
868 | |||
875 | @staticmethod |
|
869 | @staticmethod | |
876 | def _tr_magic(line_info): |
|
870 | def _tr_magic(line_info): | |
877 | "Translate lines escaped with: %" |
|
871 | "Translate lines escaped with: %" | |
878 | tpl = '%sget_ipython().magic(%s)' |
|
872 | tpl = '%sget_ipython().magic(%s)' | |
879 | cmd = make_quoted_expr(' '.join([line_info.fpart, |
|
873 | cmd = make_quoted_expr(' '.join([line_info.fpart, | |
880 | line_info.rest]).strip()) |
|
874 | line_info.rest]).strip()) | |
881 | return tpl % (line_info.lspace, cmd) |
|
875 | return tpl % (line_info.lspace, cmd) | |
882 |
|
876 | |||
883 | @staticmethod |
|
877 | @staticmethod | |
884 | def _tr_quote(line_info): |
|
878 | def _tr_quote(line_info): | |
885 | "Translate lines escaped with: ," |
|
879 | "Translate lines escaped with: ," | |
886 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, |
|
880 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, | |
887 | '", "'.join(line_info.rest.split()) ) |
|
881 | '", "'.join(line_info.rest.split()) ) | |
888 |
|
882 | |||
889 | @staticmethod |
|
883 | @staticmethod | |
890 | def _tr_quote2(line_info): |
|
884 | def _tr_quote2(line_info): | |
891 | "Translate lines escaped with: ;" |
|
885 | "Translate lines escaped with: ;" | |
892 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, |
|
886 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, | |
893 | line_info.rest) |
|
887 | line_info.rest) | |
894 |
|
888 | |||
895 | @staticmethod |
|
889 | @staticmethod | |
896 | def _tr_paren(line_info): |
|
890 | def _tr_paren(line_info): | |
897 | "Translate lines escaped with: /" |
|
891 | "Translate lines escaped with: /" | |
898 | return '%s%s(%s)' % (line_info.lspace, line_info.fpart, |
|
892 | return '%s%s(%s)' % (line_info.lspace, line_info.fpart, | |
899 | ", ".join(line_info.rest.split())) |
|
893 | ", ".join(line_info.rest.split())) | |
900 |
|
894 | |||
901 | def __call__(self, line): |
|
895 | def __call__(self, line): | |
902 | """Class to transform lines that are explicitly escaped out. |
|
896 | """Class to transform lines that are explicitly escaped out. | |
903 |
|
897 | |||
904 | This calls the above _tr_* static methods for the actual line |
|
898 | This calls the above _tr_* static methods for the actual line | |
905 | translations.""" |
|
899 | translations.""" | |
906 |
|
900 | |||
907 | # Empty lines just get returned unmodified |
|
901 | # Empty lines just get returned unmodified | |
908 | if not line or line.isspace(): |
|
902 | if not line or line.isspace(): | |
909 | return line |
|
903 | return line | |
910 |
|
904 | |||
911 | # Get line endpoints, where the escapes can be |
|
905 | # Get line endpoints, where the escapes can be | |
912 | line_info = LineInfo(line) |
|
906 | line_info = LineInfo(line) | |
913 |
|
907 | |||
914 | # If the escape is not at the start, only '?' needs to be special-cased. |
|
908 | # If the escape is not at the start, only '?' needs to be special-cased. | |
915 | # All other escapes are only valid at the start |
|
909 | # All other escapes are only valid at the start | |
916 | if not line_info.esc in self.tr: |
|
910 | if not line_info.esc in self.tr: | |
917 | if line.endswith(ESC_HELP): |
|
911 | if line.endswith(ESC_HELP): | |
918 | return self._tr_help(line_info) |
|
912 | return self._tr_help(line_info) | |
919 | else: |
|
913 | else: | |
920 | # If we don't recognize the escape, don't modify the line |
|
914 | # If we don't recognize the escape, don't modify the line | |
921 | return line |
|
915 | return line | |
922 |
|
916 | |||
923 | return self.tr[line_info.esc](line_info) |
|
917 | return self.tr[line_info.esc](line_info) | |
924 |
|
918 | |||
925 |
|
919 | |||
926 | # A function-looking object to be used by the rest of the code. The purpose of |
|
920 | # A function-looking object to be used by the rest of the code. The purpose of | |
927 | # the class in this case is to organize related functionality, more than to |
|
921 | # the class in this case is to organize related functionality, more than to | |
928 | # manage state. |
|
922 | # manage state. | |
929 | transform_escaped = EscapedTransformer() |
|
923 | transform_escaped = EscapedTransformer() | |
930 |
|
924 | |||
931 |
|
925 | |||
932 | class IPythonInputSplitter(InputSplitter): |
|
926 | class IPythonInputSplitter(InputSplitter): | |
933 | """An input splitter that recognizes all of IPython's special syntax.""" |
|
927 | """An input splitter that recognizes all of IPython's special syntax.""" | |
934 |
|
928 | |||
|
929 | # String with raw, untransformed input. | |||
|
930 | source_raw = '' | |||
|
931 | ||||
|
932 | # Private attributes | |||
|
933 | ||||
|
934 | # List with lines of raw input accumulated so far. | |||
|
935 | _buffer_raw = None | |||
|
936 | ||||
|
937 | def __init__(self, input_mode=None): | |||
|
938 | InputSplitter.__init__(self, input_mode) | |||
|
939 | self._buffer_raw = [] | |||
|
940 | ||||
|
941 | def reset(self): | |||
|
942 | """Reset the input buffer and associated state.""" | |||
|
943 | InputSplitter.reset(self) | |||
|
944 | self._buffer_raw[:] = [] | |||
|
945 | self.source_raw = '' | |||
|
946 | ||||
|
947 | def source_raw_reset(self): | |||
|
948 | """Return input and raw source and perform a full reset. | |||
|
949 | """ | |||
|
950 | out = self.source | |||
|
951 | out_r = self.source_raw | |||
|
952 | self.reset() | |||
|
953 | return out, out_r | |||
|
954 | ||||
935 | def push(self, lines): |
|
955 | def push(self, lines): | |
936 | """Push one or more lines of IPython input. |
|
956 | """Push one or more lines of IPython input. | |
937 | """ |
|
957 | """ | |
938 | if not lines: |
|
958 | if not lines: | |
939 | return super(IPythonInputSplitter, self).push(lines) |
|
959 | return super(IPythonInputSplitter, self).push(lines) | |
940 |
|
960 | |||
941 | lines_list = lines.splitlines() |
|
961 | lines_list = lines.splitlines() | |
942 |
|
962 | |||
943 | transforms = [transform_escaped, transform_assign_system, |
|
963 | transforms = [transform_escaped, transform_assign_system, | |
944 | transform_assign_magic, transform_ipy_prompt, |
|
964 | transform_assign_magic, transform_ipy_prompt, | |
945 | transform_classic_prompt] |
|
965 | transform_classic_prompt] | |
946 |
|
966 | |||
947 | # Transform logic |
|
967 | # Transform logic | |
948 | # |
|
968 | # | |
949 | # We only apply the line transformers to the input if we have either no |
|
969 | # We only apply the line transformers to the input if we have either no | |
950 | # input yet, or complete input, or if the last line of the buffer ends |
|
970 | # input yet, or complete input, or if the last line of the buffer ends | |
951 | # with ':' (opening an indented block). This prevents the accidental |
|
971 | # with ':' (opening an indented block). This prevents the accidental | |
952 | # transformation of escapes inside multiline expressions like |
|
972 | # transformation of escapes inside multiline expressions like | |
953 | # triple-quoted strings or parenthesized expressions. |
|
973 | # triple-quoted strings or parenthesized expressions. | |
954 | # |
|
974 | # | |
955 | # The last heuristic, while ugly, ensures that the first line of an |
|
975 | # The last heuristic, while ugly, ensures that the first line of an | |
956 | # indented block is correctly transformed. |
|
976 | # indented block is correctly transformed. | |
957 | # |
|
977 | # | |
958 | # FIXME: try to find a cleaner approach for this last bit. |
|
978 | # FIXME: try to find a cleaner approach for this last bit. | |
959 |
|
979 | |||
960 | # If we were in 'block' mode, since we're going to pump the parent |
|
980 | # If we were in 'block' mode, since we're going to pump the parent | |
961 | # class by hand line by line, we need to temporarily switch out to |
|
981 | # class by hand line by line, we need to temporarily switch out to | |
962 | # 'line' mode, do a single manual reset and then feed the lines one |
|
982 | # 'line' mode, do a single manual reset and then feed the lines one | |
963 | # by one. Note that this only matters if the input has more than one |
|
983 | # by one. Note that this only matters if the input has more than one | |
964 | # line. |
|
984 | # line. | |
965 | changed_input_mode = False |
|
985 | changed_input_mode = False | |
966 |
|
986 | |||
967 |
if |
|
987 | if self.input_mode == 'cell': | |
968 | self.reset() |
|
988 | self.reset() | |
969 | changed_input_mode = True |
|
989 | changed_input_mode = True | |
970 | saved_input_mode = 'cell' |
|
990 | saved_input_mode = 'cell' | |
971 | self.input_mode = 'line' |
|
991 | self.input_mode = 'line' | |
972 |
|
992 | |||
|
993 | # Store raw source before applying any transformations to it. Note | |||
|
994 | # that this must be done *after* the reset() call that would otherwise | |||
|
995 | # flush the buffer. | |||
|
996 | self._store(lines, self._buffer_raw, 'source_raw') | |||
|
997 | ||||
973 | try: |
|
998 | try: | |
974 | push = super(IPythonInputSplitter, self).push |
|
999 | push = super(IPythonInputSplitter, self).push | |
975 | for line in lines_list: |
|
1000 | for line in lines_list: | |
976 | if self._is_complete or not self._buffer or \ |
|
1001 | if self._is_complete or not self._buffer or \ | |
977 | (self._buffer and self._buffer[-1].rstrip().endswith(':')): |
|
1002 | (self._buffer and self._buffer[-1].rstrip().endswith(':')): | |
978 | for f in transforms: |
|
1003 | for f in transforms: | |
979 | line = f(line) |
|
1004 | line = f(line) | |
980 |
|
1005 | |||
981 | out = push(line) |
|
1006 | out = push(line) | |
982 | finally: |
|
1007 | finally: | |
983 | if changed_input_mode: |
|
1008 | if changed_input_mode: | |
984 | self.input_mode = saved_input_mode |
|
1009 | self.input_mode = saved_input_mode | |
985 |
|
||||
986 | return out |
|
1010 | return out |
@@ -1,263 +1,215 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | """Logger class for IPython's logging facilities. | |
2 | """ |
|
|||
3 | Logger class for IPython's logging facilities. |
|
|||
4 | """ |
|
2 | """ | |
5 |
|
3 | |||
6 | #***************************************************************************** |
|
4 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
9 | # |
|
7 | # | |
10 | # 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 | |
11 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
12 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
13 |
|
11 | |||
14 | #**************************************************************************** |
|
12 | #**************************************************************************** | |
15 | # Modules and globals |
|
13 | # Modules and globals | |
16 |
|
14 | |||
17 | # Python standard modules |
|
15 | # Python standard modules | |
18 | import glob |
|
16 | import glob | |
19 | import os |
|
17 | import os | |
20 | import time |
|
18 | import time | |
21 |
|
19 | |||
22 | #**************************************************************************** |
|
20 | #**************************************************************************** | |
23 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from |
|
21 | # FIXME: This class isn't a mixin anymore, but it still needs attributes from | |
24 | # ipython and does input cache management. Finish cleanup later... |
|
22 | # ipython and does input cache management. Finish cleanup later... | |
25 |
|
23 | |||
26 | class Logger(object): |
|
24 | class Logger(object): | |
27 | """A Logfile class with different policies for file creation""" |
|
25 | """A Logfile class with different policies for file creation""" | |
28 |
|
26 | |||
29 |
def __init__(self, |
|
27 | def __init__(self, home_dir, logfname='Logger.log', loghead='', | |
30 |
|
28 | logmode='over'): | ||
31 | self._i00,self._i,self._ii,self._iii = '','','','' |
|
|||
32 |
|
29 | |||
33 | # this is the full ipython instance, we need some attributes from it |
|
30 | # 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... |
|
31 | # which won't exist until later. What a mess, clean up later... | |
35 |
self. |
|
32 | self.home_dir = home_dir | |
36 |
|
33 | |||
37 | self.logfname = logfname |
|
34 | self.logfname = logfname | |
38 | self.loghead = loghead |
|
35 | self.loghead = loghead | |
39 | self.logmode = logmode |
|
36 | self.logmode = logmode | |
40 | self.logfile = None |
|
37 | self.logfile = None | |
41 |
|
38 | |||
42 | # Whether to log raw or processed input |
|
39 | # Whether to log raw or processed input | |
43 | self.log_raw_input = False |
|
40 | self.log_raw_input = False | |
44 |
|
41 | |||
45 | # whether to also log output |
|
42 | # whether to also log output | |
46 | self.log_output = False |
|
43 | self.log_output = False | |
47 |
|
44 | |||
48 | # whether to put timestamps before each log entry |
|
45 | # whether to put timestamps before each log entry | |
49 | self.timestamp = False |
|
46 | self.timestamp = False | |
50 |
|
47 | |||
51 | # activity control flags |
|
48 | # activity control flags | |
52 | self.log_active = False |
|
49 | self.log_active = False | |
53 |
|
50 | |||
54 | # logmode is a validated property |
|
51 | # logmode is a validated property | |
55 | def _set_mode(self,mode): |
|
52 | def _set_mode(self,mode): | |
56 | if mode not in ['append','backup','global','over','rotate']: |
|
53 | if mode not in ['append','backup','global','over','rotate']: | |
57 | raise ValueError,'invalid log mode %s given' % mode |
|
54 | raise ValueError,'invalid log mode %s given' % mode | |
58 | self._logmode = mode |
|
55 | self._logmode = mode | |
59 |
|
56 | |||
60 | def _get_mode(self): |
|
57 | def _get_mode(self): | |
61 | return self._logmode |
|
58 | return self._logmode | |
62 |
|
59 | |||
63 | logmode = property(_get_mode,_set_mode) |
|
60 | logmode = property(_get_mode,_set_mode) | |
64 |
|
61 | |||
65 | def logstart(self,logfname=None,loghead=None,logmode=None, |
|
62 | def logstart(self,logfname=None,loghead=None,logmode=None, | |
66 | log_output=False,timestamp=False,log_raw_input=False): |
|
63 | log_output=False,timestamp=False,log_raw_input=False): | |
67 | """Generate a new log-file with a default header. |
|
64 | """Generate a new log-file with a default header. | |
68 |
|
65 | |||
69 | Raises RuntimeError if the log has already been started""" |
|
66 | Raises RuntimeError if the log has already been started""" | |
70 |
|
67 | |||
71 | if self.logfile is not None: |
|
68 | if self.logfile is not None: | |
72 | raise RuntimeError('Log file is already active: %s' % |
|
69 | raise RuntimeError('Log file is already active: %s' % | |
73 | self.logfname) |
|
70 | self.logfname) | |
74 |
|
71 | |||
75 | self.log_active = True |
|
72 | self.log_active = True | |
76 |
|
73 | |||
77 | # The parameters can override constructor defaults |
|
74 | # The parameters can override constructor defaults | |
78 | if logfname is not None: self.logfname = logfname |
|
75 | if logfname is not None: self.logfname = logfname | |
79 | if loghead is not None: self.loghead = loghead |
|
76 | if loghead is not None: self.loghead = loghead | |
80 | if logmode is not None: self.logmode = logmode |
|
77 | if logmode is not None: self.logmode = logmode | |
81 |
|
78 | |||
82 | # Parameters not part of the constructor |
|
79 | # Parameters not part of the constructor | |
83 | self.timestamp = timestamp |
|
80 | self.timestamp = timestamp | |
84 | self.log_output = log_output |
|
81 | self.log_output = log_output | |
85 | self.log_raw_input = log_raw_input |
|
82 | self.log_raw_input = log_raw_input | |
86 |
|
83 | |||
87 | # init depending on the log mode requested |
|
84 | # init depending on the log mode requested | |
88 | isfile = os.path.isfile |
|
85 | isfile = os.path.isfile | |
89 | logmode = self.logmode |
|
86 | logmode = self.logmode | |
90 |
|
87 | |||
91 | if logmode == 'append': |
|
88 | if logmode == 'append': | |
92 | self.logfile = open(self.logfname,'a') |
|
89 | self.logfile = open(self.logfname,'a') | |
93 |
|
90 | |||
94 | elif logmode == 'backup': |
|
91 | elif logmode == 'backup': | |
95 | if isfile(self.logfname): |
|
92 | if isfile(self.logfname): | |
96 | backup_logname = self.logfname+'~' |
|
93 | backup_logname = self.logfname+'~' | |
97 | # Manually remove any old backup, since os.rename may fail |
|
94 | # Manually remove any old backup, since os.rename may fail | |
98 | # under Windows. |
|
95 | # under Windows. | |
99 | if isfile(backup_logname): |
|
96 | if isfile(backup_logname): | |
100 | os.remove(backup_logname) |
|
97 | os.remove(backup_logname) | |
101 | os.rename(self.logfname,backup_logname) |
|
98 | os.rename(self.logfname,backup_logname) | |
102 | self.logfile = open(self.logfname,'w') |
|
99 | self.logfile = open(self.logfname,'w') | |
103 |
|
100 | |||
104 | elif logmode == 'global': |
|
101 | elif logmode == 'global': | |
105 |
self.logfname = os.path.join(self. |
|
102 | self.logfname = os.path.join(self.home_dir,self.logfname) | |
106 | self.logfile = open(self.logfname, 'a') |
|
103 | self.logfile = open(self.logfname, 'a') | |
107 |
|
104 | |||
108 | elif logmode == 'over': |
|
105 | elif logmode == 'over': | |
109 | if isfile(self.logfname): |
|
106 | if isfile(self.logfname): | |
110 | os.remove(self.logfname) |
|
107 | os.remove(self.logfname) | |
111 | self.logfile = open(self.logfname,'w') |
|
108 | self.logfile = open(self.logfname,'w') | |
112 |
|
109 | |||
113 | elif logmode == 'rotate': |
|
110 | elif logmode == 'rotate': | |
114 | if isfile(self.logfname): |
|
111 | if isfile(self.logfname): | |
115 | if isfile(self.logfname+'.001~'): |
|
112 | if isfile(self.logfname+'.001~'): | |
116 | old = glob.glob(self.logfname+'.*~') |
|
113 | old = glob.glob(self.logfname+'.*~') | |
117 | old.sort() |
|
114 | old.sort() | |
118 | old.reverse() |
|
115 | old.reverse() | |
119 | for f in old: |
|
116 | for f in old: | |
120 | root, ext = os.path.splitext(f) |
|
117 | root, ext = os.path.splitext(f) | |
121 | num = int(ext[1:-1])+1 |
|
118 | num = int(ext[1:-1])+1 | |
122 | os.rename(f, root+'.'+`num`.zfill(3)+'~') |
|
119 | os.rename(f, root+'.'+`num`.zfill(3)+'~') | |
123 | os.rename(self.logfname, self.logfname+'.001~') |
|
120 | os.rename(self.logfname, self.logfname+'.001~') | |
124 | self.logfile = open(self.logfname,'w') |
|
121 | self.logfile = open(self.logfname,'w') | |
125 |
|
122 | |||
126 | if logmode != 'append': |
|
123 | if logmode != 'append': | |
127 | self.logfile.write(self.loghead) |
|
124 | self.logfile.write(self.loghead) | |
128 |
|
125 | |||
129 | self.logfile.flush() |
|
126 | self.logfile.flush() | |
130 |
|
127 | |||
131 | def switch_log(self,val): |
|
128 | def switch_log(self,val): | |
132 | """Switch logging on/off. val should be ONLY a boolean.""" |
|
129 | """Switch logging on/off. val should be ONLY a boolean.""" | |
133 |
|
130 | |||
134 | if val not in [False,True,0,1]: |
|
131 | if val not in [False,True,0,1]: | |
135 | raise ValueError, \ |
|
132 | raise ValueError, \ | |
136 | 'Call switch_log ONLY with a boolean argument, not with:',val |
|
133 | 'Call switch_log ONLY with a boolean argument, not with:',val | |
137 |
|
134 | |||
138 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} |
|
135 | label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} | |
139 |
|
136 | |||
140 | if self.logfile is None: |
|
137 | if self.logfile is None: | |
141 | print """ |
|
138 | print """ | |
142 | Logging hasn't been started yet (use logstart for that). |
|
139 | Logging hasn't been started yet (use logstart for that). | |
143 |
|
140 | |||
144 | %logon/%logoff are for temporarily starting and stopping logging for a logfile |
|
141 | %logon/%logoff are for temporarily starting and stopping logging for a logfile | |
145 | which already exists. But you must first start the logging process with |
|
142 | which already exists. But you must first start the logging process with | |
146 | %logstart (optionally giving a logfile name).""" |
|
143 | %logstart (optionally giving a logfile name).""" | |
147 |
|
144 | |||
148 | else: |
|
145 | else: | |
149 | if self.log_active == val: |
|
146 | if self.log_active == val: | |
150 | print 'Logging is already',label[val] |
|
147 | print 'Logging is already',label[val] | |
151 | else: |
|
148 | else: | |
152 | print 'Switching logging',label[val] |
|
149 | print 'Switching logging',label[val] | |
153 | self.log_active = not self.log_active |
|
150 | self.log_active = not self.log_active | |
154 | self.log_active_out = self.log_active |
|
151 | self.log_active_out = self.log_active | |
155 |
|
152 | |||
156 | def logstate(self): |
|
153 | def logstate(self): | |
157 | """Print a status message about the logger.""" |
|
154 | """Print a status message about the logger.""" | |
158 | if self.logfile is None: |
|
155 | if self.logfile is None: | |
159 | print 'Logging has not been activated.' |
|
156 | print 'Logging has not been activated.' | |
160 | else: |
|
157 | else: | |
161 | state = self.log_active and 'active' or 'temporarily suspended' |
|
158 | state = self.log_active and 'active' or 'temporarily suspended' | |
162 | print 'Filename :',self.logfname |
|
159 | print 'Filename :',self.logfname | |
163 | print 'Mode :',self.logmode |
|
160 | print 'Mode :',self.logmode | |
164 | print 'Output logging :',self.log_output |
|
161 | print 'Output logging :',self.log_output | |
165 | print 'Raw input log :',self.log_raw_input |
|
162 | print 'Raw input log :',self.log_raw_input | |
166 | print 'Timestamping :',self.timestamp |
|
163 | print 'Timestamping :',self.timestamp | |
167 | print 'State :',state |
|
164 | print 'State :',state | |
168 |
|
165 | |||
169 |
def log(self, |
|
166 | def log(self, line_mod, line_ori): | |
170 | """Write the line to a log and create input cache variables _i*. |
|
167 | """Write the sources to a log. | |
171 |
|
168 | |||
172 | Inputs: |
|
169 | Inputs: | |
173 |
|
170 | |||
174 | - line_ori: unmodified input line from the user. This is not |
|
|||
175 | necessarily valid Python. |
|
|||
176 |
|
||||
177 | - line_mod: possibly modified input, such as the transformations made |
|
171 | - line_mod: possibly modified input, such as the transformations made | |
178 | by input prefilters or input handlers of various kinds. This should |
|
172 | by input prefilters or input handlers of various kinds. This should | |
179 | always be valid Python. |
|
173 | always be valid Python. | |
180 |
|
174 | |||
181 | - continuation: if True, indicates this is part of multi-line input.""" |
|
175 | - line_ori: unmodified input line from the user. This is not | |
182 |
|
176 | necessarily valid Python. | ||
183 | # update the auto _i tables |
|
177 | """ | |
184 | #print '***logging line',line_mod # dbg |
|
|||
185 | #print '***cache_count', self.shell.displayhook.prompt_count # dbg |
|
|||
186 | try: |
|
|||
187 | input_hist = self.shell.user_ns['_ih'] |
|
|||
188 | except: |
|
|||
189 | #print 'userns:',self.shell.user_ns.keys() # dbg |
|
|||
190 | return |
|
|||
191 |
|
||||
192 | out_cache = self.shell.displayhook |
|
|||
193 |
|
||||
194 | # add blank lines if the input cache fell out of sync. |
|
|||
195 | if out_cache.do_full_cache and \ |
|
|||
196 | out_cache.prompt_count +1 > len(input_hist): |
|
|||
197 | input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist))) |
|
|||
198 |
|
||||
199 | if not continuation and line_mod: |
|
|||
200 | self._iii = self._ii |
|
|||
201 | self._ii = self._i |
|
|||
202 | self._i = self._i00 |
|
|||
203 | # put back the final \n of every input line |
|
|||
204 | self._i00 = line_mod+'\n' |
|
|||
205 | #print 'Logging input:<%s>' % line_mod # dbg |
|
|||
206 | input_hist.append(self._i00) |
|
|||
207 | #print '---[%s]' % (len(input_hist)-1,) # dbg |
|
|||
208 |
|
||||
209 | # hackish access to top-level namespace to create _i1,_i2... dynamically |
|
|||
210 | to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii} |
|
|||
211 | if self.shell.displayhook.do_full_cache: |
|
|||
212 | in_num = self.shell.displayhook.prompt_count |
|
|||
213 |
|
||||
214 | # but if the opposite is true (a macro can produce multiple inputs |
|
|||
215 | # with no output display called), then bring the output counter in |
|
|||
216 | # sync: |
|
|||
217 | last_num = len(input_hist)-1 |
|
|||
218 | if in_num != last_num: |
|
|||
219 | in_num = self.shell.displayhook.prompt_count = last_num |
|
|||
220 | new_i = '_i%s' % in_num |
|
|||
221 | if continuation: |
|
|||
222 | self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod) |
|
|||
223 | input_hist[in_num] = self._i00 |
|
|||
224 | to_main[new_i] = self._i00 |
|
|||
225 | self.shell.user_ns.update(to_main) |
|
|||
226 |
|
178 | |||
227 | # Write the log line, but decide which one according to the |
|
179 | # Write the log line, but decide which one according to the | |
228 | # log_raw_input flag, set when the log is started. |
|
180 | # log_raw_input flag, set when the log is started. | |
229 | if self.log_raw_input: |
|
181 | if self.log_raw_input: | |
230 | self.log_write(line_ori) |
|
182 | self.log_write(line_ori) | |
231 | else: |
|
183 | else: | |
232 | self.log_write(line_mod) |
|
184 | self.log_write(line_mod) | |
233 |
|
185 | |||
234 | def log_write(self,data,kind='input'): |
|
186 | def log_write(self, data, kind='input'): | |
235 | """Write data to the log file, if active""" |
|
187 | """Write data to the log file, if active""" | |
236 |
|
188 | |||
237 | #print 'data: %r' % data # dbg |
|
189 | #print 'data: %r' % data # dbg | |
238 | if self.log_active and data: |
|
190 | if self.log_active and data: | |
239 | write = self.logfile.write |
|
191 | write = self.logfile.write | |
240 | if kind=='input': |
|
192 | if kind=='input': | |
241 | if self.timestamp: |
|
193 | if self.timestamp: | |
242 | write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', |
|
194 | write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', | |
243 | time.localtime())) |
|
195 | time.localtime())) | |
244 |
write( |
|
196 | write(data) | |
245 | elif kind=='output' and self.log_output: |
|
197 | elif kind=='output' and self.log_output: | |
246 | odata = '\n'.join(['#[Out]# %s' % s |
|
198 | odata = '\n'.join(['#[Out]# %s' % s | |
247 |
for s in data.split( |
|
199 | for s in data.splitlines()]) | |
248 | write('%s\n' % odata) |
|
200 | write('%s\n' % odata) | |
249 | self.logfile.flush() |
|
201 | self.logfile.flush() | |
250 |
|
202 | |||
251 | def logstop(self): |
|
203 | def logstop(self): | |
252 | """Fully stop logging and close log file. |
|
204 | """Fully stop logging and close log file. | |
253 |
|
205 | |||
254 | In order to start logging again, a new logstart() call needs to be |
|
206 | In order to start logging again, a new logstart() call needs to be | |
255 | made, possibly (though not necessarily) with a new filename, mode and |
|
207 | made, possibly (though not necessarily) with a new filename, mode and | |
256 | other options.""" |
|
208 | other options.""" | |
257 |
|
209 | |||
258 | self.logfile.close() |
|
210 | self.logfile.close() | |
259 | self.logfile = None |
|
211 | self.logfile = None | |
260 | self.log_active = False |
|
212 | self.log_active = False | |
261 |
|
213 | |||
262 | # For backwards compatibility, in case anyone was using this. |
|
214 | # For backwards compatibility, in case anyone was using this. | |
263 | close_log = logstop |
|
215 | close_log = logstop |
@@ -1,41 +1,39 b'' | |||||
1 | """Support for interactive macros in IPython""" |
|
1 | """Support for interactive macros in IPython""" | |
2 |
|
2 | |||
3 | #***************************************************************************** |
|
3 | #***************************************************************************** | |
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 |
|
9 | |||
10 | import IPython.utils.io |
|
10 | import IPython.utils.io | |
11 | from IPython.core.autocall import IPyAutocall |
|
11 | from IPython.core.autocall import IPyAutocall | |
12 |
|
12 | |||
13 | class Macro(IPyAutocall): |
|
13 | class Macro(IPyAutocall): | |
14 | """Simple class to store the value of macros as strings. |
|
14 | """Simple class to store the value of macros as strings. | |
15 |
|
15 | |||
16 | Macro is just a callable that executes a string of IPython |
|
16 | Macro is just a callable that executes a string of IPython | |
17 | input when called. |
|
17 | input when called. | |
18 |
|
18 | |||
19 | Args to macro are available in _margv list if you need them. |
|
19 | Args to macro are available in _margv list if you need them. | |
20 | """ |
|
20 | """ | |
21 |
|
21 | |||
22 | def __init__(self,data): |
|
22 | def __init__(self,data): | |
23 |
|
23 | # store the macro value, as a single string which can be executed | ||
24 | # store the macro value, as a single string which can be evaluated by |
|
|||
25 | # runlines() |
|
|||
26 | self.value = ''.join(data).rstrip()+'\n' |
|
24 | self.value = ''.join(data).rstrip()+'\n' | |
27 |
|
25 | |||
28 | def __str__(self): |
|
26 | def __str__(self): | |
29 | return self.value |
|
27 | return self.value | |
30 |
|
28 | |||
31 | def __repr__(self): |
|
29 | def __repr__(self): | |
32 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
30 | return 'IPython.macro.Macro(%s)' % repr(self.value) | |
33 |
|
31 | |||
34 | def __call__(self,*args): |
|
32 | def __call__(self,*args): | |
35 | IPython.utils.io.Term.cout.flush() |
|
33 | IPython.utils.io.Term.cout.flush() | |
36 | self._ip.user_ns['_margv'] = args |
|
34 | self._ip.user_ns['_margv'] = args | |
37 |
self._ip.run |
|
35 | self._ip.run_cell(self.value) | |
38 |
|
36 | |||
39 | def __getstate__(self): |
|
37 | def __getstate__(self): | |
40 | """ needed for safe pickling via %store """ |
|
38 | """ needed for safe pickling via %store """ | |
41 | return {'value': self.value} |
|
39 | return {'value': self.value} |
@@ -1,3372 +1,3367 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-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | # print_function was added to __future__ in Python2.6, remove this when we drop |
|
|||
45 | # 2.5 compatibility |
|
|||
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): |
|
|||
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 |
|
|||
48 |
|
||||
49 | import IPython |
|
44 | import IPython | |
50 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
51 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
52 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
53 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
54 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
55 | from IPython.core import page |
|
50 | from IPython.core import page | |
56 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
57 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
58 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
59 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
60 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
61 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
62 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
63 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
64 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
66 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
67 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
68 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
69 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
70 |
|
65 | |||
71 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
72 | # Utility functions |
|
67 | # Utility functions | |
73 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
74 |
|
69 | |||
75 | def on_off(tag): |
|
70 | def on_off(tag): | |
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
77 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
78 |
|
73 | |||
79 | class Bunch: pass |
|
74 | class Bunch: pass | |
80 |
|
75 | |||
81 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
82 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
83 |
|
78 | |||
84 | newhead = [] |
|
79 | newhead = [] | |
85 | done = set() |
|
80 | done = set() | |
86 | for h in head: |
|
81 | for h in head: | |
87 | if h in done: |
|
82 | if h in done: | |
88 | continue |
|
83 | continue | |
89 | newhead.append(h) |
|
84 | newhead.append(h) | |
90 | done.add(h) |
|
85 | done.add(h) | |
91 |
|
86 | |||
92 | return newhead + tail |
|
87 | return newhead + tail | |
93 |
|
88 | |||
94 |
|
89 | |||
95 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
96 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
97 |
|
92 | |||
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
99 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
101 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
102 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
104 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
105 |
|
100 | |||
106 | class Magic: |
|
101 | class Magic: | |
107 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
108 |
|
103 | |||
109 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
110 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
111 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
112 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
113 |
|
108 | |||
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
115 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
116 |
|
111 | |||
117 | # class globals |
|
112 | # class globals | |
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
120 |
|
115 | |||
121 | #...................................................................... |
|
116 | #...................................................................... | |
122 | # some utility functions |
|
117 | # some utility functions | |
123 |
|
118 | |||
124 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
125 |
|
120 | |||
126 | self.options_table = {} |
|
121 | self.options_table = {} | |
127 | if profile is None: |
|
122 | if profile is None: | |
128 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
129 | self.shell = shell |
|
124 | self.shell = shell | |
130 |
|
125 | |||
131 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
132 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
133 |
|
128 | |||
134 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
135 | error("""\ |
|
130 | error("""\ | |
136 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
137 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
138 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
139 |
|
134 | |||
140 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
141 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
142 |
|
137 | |||
143 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
144 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
145 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
146 |
|
141 | |||
147 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
148 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
149 |
|
144 | |||
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
151 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
152 |
|
147 | |||
153 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
154 |
|
149 | |||
155 | # magics in class definition |
|
150 | # magics in class definition | |
156 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
157 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
158 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
160 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
161 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
163 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
165 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
167 | out = [] |
|
162 | out = [] | |
168 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
169 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
170 | out.sort() |
|
165 | out.sort() | |
171 | return out |
|
166 | return out | |
172 |
|
167 | |||
173 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
174 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
175 |
|
170 | |||
176 | Inputs: |
|
171 | Inputs: | |
177 |
|
172 | |||
178 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
179 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
180 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
181 |
|
176 | |||
182 | Optional inputs: |
|
177 | Optional inputs: | |
183 |
|
178 | |||
184 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
185 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
186 |
|
181 | |||
187 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
188 |
|
183 | |||
189 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
190 |
|
185 | |||
191 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
192 |
|
187 | |||
193 | if raw: |
|
188 | if raw: | |
194 | hist = self.shell.input_hist_raw |
|
189 | hist = self.shell.input_hist_raw | |
195 | else: |
|
190 | else: | |
196 | hist = self.shell.input_hist |
|
191 | hist = self.shell.input_hist | |
197 |
|
192 | |||
198 | cmds = [] |
|
193 | cmds = [] | |
199 | for chunk in slices: |
|
194 | for chunk in slices: | |
200 | if ':' in chunk: |
|
195 | if ':' in chunk: | |
201 | ini,fin = map(int,chunk.split(':')) |
|
196 | ini,fin = map(int,chunk.split(':')) | |
202 | elif '-' in chunk: |
|
197 | elif '-' in chunk: | |
203 | ini,fin = map(int,chunk.split('-')) |
|
198 | ini,fin = map(int,chunk.split('-')) | |
204 | fin += 1 |
|
199 | fin += 1 | |
205 | else: |
|
200 | else: | |
206 | ini = int(chunk) |
|
201 | ini = int(chunk) | |
207 | fin = ini+1 |
|
202 | fin = ini+1 | |
208 | cmds.append(hist[ini:fin]) |
|
203 | cmds.append(hist[ini:fin]) | |
209 | return cmds |
|
204 | return cmds | |
210 |
|
205 | |||
211 | def arg_err(self,func): |
|
206 | def arg_err(self,func): | |
212 | """Print docstring if incorrect arguments were passed""" |
|
207 | """Print docstring if incorrect arguments were passed""" | |
213 | print 'Error in arguments:' |
|
208 | print 'Error in arguments:' | |
214 | print oinspect.getdoc(func) |
|
209 | print oinspect.getdoc(func) | |
215 |
|
210 | |||
216 | def format_latex(self,strng): |
|
211 | def format_latex(self,strng): | |
217 | """Format a string for latex inclusion.""" |
|
212 | """Format a string for latex inclusion.""" | |
218 |
|
213 | |||
219 | # Characters that need to be escaped for latex: |
|
214 | # Characters that need to be escaped for latex: | |
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
221 | # Magic command names as headers: |
|
216 | # Magic command names as headers: | |
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
223 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
224 | # Magic commands |
|
219 | # Magic commands | |
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
226 | re.MULTILINE) |
|
221 | re.MULTILINE) | |
227 | # Paragraph continue |
|
222 | # Paragraph continue | |
228 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
223 | par_re = re.compile(r'\\$',re.MULTILINE) | |
229 |
|
224 | |||
230 | # The "\n" symbol |
|
225 | # The "\n" symbol | |
231 | newline_re = re.compile(r'\\n') |
|
226 | newline_re = re.compile(r'\\n') | |
232 |
|
227 | |||
233 | # Now build the string for output: |
|
228 | # Now build the string for output: | |
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
236 | strng) |
|
231 | strng) | |
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
238 | strng = par_re.sub(r'\\\\',strng) |
|
233 | strng = par_re.sub(r'\\\\',strng) | |
239 | strng = escape_re.sub(r'\\\1',strng) |
|
234 | strng = escape_re.sub(r'\\\1',strng) | |
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
241 | return strng |
|
236 | return strng | |
242 |
|
237 | |||
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
244 | """Parse options passed to an argument string. |
|
239 | """Parse options passed to an argument string. | |
245 |
|
240 | |||
246 | The interface is similar to that of getopt(), but it returns back a |
|
241 | The interface is similar to that of getopt(), but it returns back a | |
247 | Struct with the options as keys and the stripped argument string still |
|
242 | Struct with the options as keys and the stripped argument string still | |
248 | as a string. |
|
243 | as a string. | |
249 |
|
244 | |||
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
251 | This allows us to easily expand variables, glob files, quote |
|
246 | This allows us to easily expand variables, glob files, quote | |
252 | arguments, etc. |
|
247 | arguments, etc. | |
253 |
|
248 | |||
254 | Options: |
|
249 | Options: | |
255 | -mode: default 'string'. If given as 'list', the argument string is |
|
250 | -mode: default 'string'. If given as 'list', the argument string is | |
256 | returned as a list (split on whitespace) instead of a string. |
|
251 | returned as a list (split on whitespace) instead of a string. | |
257 |
|
252 | |||
258 | -list_all: put all option values in lists. Normally only options |
|
253 | -list_all: put all option values in lists. Normally only options | |
259 | appearing more than once are put in a list. |
|
254 | appearing more than once are put in a list. | |
260 |
|
255 | |||
261 | -posix (True): whether to split the input line in POSIX mode or not, |
|
256 | -posix (True): whether to split the input line in POSIX mode or not, | |
262 | as per the conventions outlined in the shlex module from the |
|
257 | as per the conventions outlined in the shlex module from the | |
263 | standard library.""" |
|
258 | standard library.""" | |
264 |
|
259 | |||
265 | # inject default options at the beginning of the input line |
|
260 | # inject default options at the beginning of the input line | |
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
268 |
|
263 | |||
269 | mode = kw.get('mode','string') |
|
264 | mode = kw.get('mode','string') | |
270 | if mode not in ['string','list']: |
|
265 | if mode not in ['string','list']: | |
271 | raise ValueError,'incorrect mode given: %s' % mode |
|
266 | raise ValueError,'incorrect mode given: %s' % mode | |
272 | # Get options |
|
267 | # Get options | |
273 | list_all = kw.get('list_all',0) |
|
268 | list_all = kw.get('list_all',0) | |
274 | posix = kw.get('posix', os.name == 'posix') |
|
269 | posix = kw.get('posix', os.name == 'posix') | |
275 |
|
270 | |||
276 | # Check if we have more than one argument to warrant extra processing: |
|
271 | # Check if we have more than one argument to warrant extra processing: | |
277 | odict = {} # Dictionary with options |
|
272 | odict = {} # Dictionary with options | |
278 | args = arg_str.split() |
|
273 | args = arg_str.split() | |
279 | if len(args) >= 1: |
|
274 | if len(args) >= 1: | |
280 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
275 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
281 | # need to look for options |
|
276 | # need to look for options | |
282 | argv = arg_split(arg_str,posix) |
|
277 | argv = arg_split(arg_str,posix) | |
283 | # Do regular option processing |
|
278 | # Do regular option processing | |
284 | try: |
|
279 | try: | |
285 | opts,args = getopt(argv,opt_str,*long_opts) |
|
280 | opts,args = getopt(argv,opt_str,*long_opts) | |
286 | except GetoptError,e: |
|
281 | except GetoptError,e: | |
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
288 | " ".join(long_opts))) |
|
283 | " ".join(long_opts))) | |
289 | for o,a in opts: |
|
284 | for o,a in opts: | |
290 | if o.startswith('--'): |
|
285 | if o.startswith('--'): | |
291 | o = o[2:] |
|
286 | o = o[2:] | |
292 | else: |
|
287 | else: | |
293 | o = o[1:] |
|
288 | o = o[1:] | |
294 | try: |
|
289 | try: | |
295 | odict[o].append(a) |
|
290 | odict[o].append(a) | |
296 | except AttributeError: |
|
291 | except AttributeError: | |
297 | odict[o] = [odict[o],a] |
|
292 | odict[o] = [odict[o],a] | |
298 | except KeyError: |
|
293 | except KeyError: | |
299 | if list_all: |
|
294 | if list_all: | |
300 | odict[o] = [a] |
|
295 | odict[o] = [a] | |
301 | else: |
|
296 | else: | |
302 | odict[o] = a |
|
297 | odict[o] = a | |
303 |
|
298 | |||
304 | # Prepare opts,args for return |
|
299 | # Prepare opts,args for return | |
305 | opts = Struct(odict) |
|
300 | opts = Struct(odict) | |
306 | if mode == 'string': |
|
301 | if mode == 'string': | |
307 | args = ' '.join(args) |
|
302 | args = ' '.join(args) | |
308 |
|
303 | |||
309 | return opts,args |
|
304 | return opts,args | |
310 |
|
305 | |||
311 | #...................................................................... |
|
306 | #...................................................................... | |
312 | # And now the actual magic functions |
|
307 | # And now the actual magic functions | |
313 |
|
308 | |||
314 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
309 | # Functions for IPython shell work (vars,funcs, config, etc) | |
315 | def magic_lsmagic(self, parameter_s = ''): |
|
310 | def magic_lsmagic(self, parameter_s = ''): | |
316 | """List currently available magic functions.""" |
|
311 | """List currently available magic functions.""" | |
317 | mesc = ESC_MAGIC |
|
312 | mesc = ESC_MAGIC | |
318 | print 'Available magic functions:\n'+mesc+\ |
|
313 | print 'Available magic functions:\n'+mesc+\ | |
319 | (' '+mesc).join(self.lsmagic()) |
|
314 | (' '+mesc).join(self.lsmagic()) | |
320 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
315 | print '\n' + Magic.auto_status[self.shell.automagic] | |
321 | return None |
|
316 | return None | |
322 |
|
317 | |||
323 | def magic_magic(self, parameter_s = ''): |
|
318 | def magic_magic(self, parameter_s = ''): | |
324 | """Print information about the magic function system. |
|
319 | """Print information about the magic function system. | |
325 |
|
320 | |||
326 | Supported formats: -latex, -brief, -rest |
|
321 | Supported formats: -latex, -brief, -rest | |
327 | """ |
|
322 | """ | |
328 |
|
323 | |||
329 | mode = '' |
|
324 | mode = '' | |
330 | try: |
|
325 | try: | |
331 | if parameter_s.split()[0] == '-latex': |
|
326 | if parameter_s.split()[0] == '-latex': | |
332 | mode = 'latex' |
|
327 | mode = 'latex' | |
333 | if parameter_s.split()[0] == '-brief': |
|
328 | if parameter_s.split()[0] == '-brief': | |
334 | mode = 'brief' |
|
329 | mode = 'brief' | |
335 | if parameter_s.split()[0] == '-rest': |
|
330 | if parameter_s.split()[0] == '-rest': | |
336 | mode = 'rest' |
|
331 | mode = 'rest' | |
337 | rest_docs = [] |
|
332 | rest_docs = [] | |
338 | except: |
|
333 | except: | |
339 | pass |
|
334 | pass | |
340 |
|
335 | |||
341 | magic_docs = [] |
|
336 | magic_docs = [] | |
342 | for fname in self.lsmagic(): |
|
337 | for fname in self.lsmagic(): | |
343 | mname = 'magic_' + fname |
|
338 | mname = 'magic_' + fname | |
344 | for space in (Magic,self,self.__class__): |
|
339 | for space in (Magic,self,self.__class__): | |
345 | try: |
|
340 | try: | |
346 | fn = space.__dict__[mname] |
|
341 | fn = space.__dict__[mname] | |
347 | except KeyError: |
|
342 | except KeyError: | |
348 | pass |
|
343 | pass | |
349 | else: |
|
344 | else: | |
350 | break |
|
345 | break | |
351 | if mode == 'brief': |
|
346 | if mode == 'brief': | |
352 | # only first line |
|
347 | # only first line | |
353 | if fn.__doc__: |
|
348 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.split('\n',1)[0] |
|
349 | fndoc = fn.__doc__.split('\n',1)[0] | |
355 | else: |
|
350 | else: | |
356 | fndoc = 'No documentation' |
|
351 | fndoc = 'No documentation' | |
357 | else: |
|
352 | else: | |
358 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
359 | fndoc = fn.__doc__.rstrip() |
|
354 | fndoc = fn.__doc__.rstrip() | |
360 | else: |
|
355 | else: | |
361 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
362 |
|
357 | |||
363 |
|
358 | |||
364 | if mode == 'rest': |
|
359 | if mode == 'rest': | |
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
366 | fname,fndoc)) |
|
361 | fname,fndoc)) | |
367 |
|
362 | |||
368 | else: |
|
363 | else: | |
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
370 | fname,fndoc)) |
|
365 | fname,fndoc)) | |
371 |
|
366 | |||
372 | magic_docs = ''.join(magic_docs) |
|
367 | magic_docs = ''.join(magic_docs) | |
373 |
|
368 | |||
374 | if mode == 'rest': |
|
369 | if mode == 'rest': | |
375 | return "".join(rest_docs) |
|
370 | return "".join(rest_docs) | |
376 |
|
371 | |||
377 | if mode == 'latex': |
|
372 | if mode == 'latex': | |
378 | print self.format_latex(magic_docs) |
|
373 | print self.format_latex(magic_docs) | |
379 | return |
|
374 | return | |
380 | else: |
|
375 | else: | |
381 | magic_docs = format_screen(magic_docs) |
|
376 | magic_docs = format_screen(magic_docs) | |
382 | if mode == 'brief': |
|
377 | if mode == 'brief': | |
383 | return magic_docs |
|
378 | return magic_docs | |
384 |
|
379 | |||
385 | outmsg = """ |
|
380 | outmsg = """ | |
386 | IPython's 'magic' functions |
|
381 | IPython's 'magic' functions | |
387 | =========================== |
|
382 | =========================== | |
388 |
|
383 | |||
389 | The magic function system provides a series of functions which allow you to |
|
384 | The magic function system provides a series of functions which allow you to | |
390 | control the behavior of IPython itself, plus a lot of system-type |
|
385 | control the behavior of IPython itself, plus a lot of system-type | |
391 | features. All these functions are prefixed with a % character, but parameters |
|
386 | features. All these functions are prefixed with a % character, but parameters | |
392 | are given without parentheses or quotes. |
|
387 | are given without parentheses or quotes. | |
393 |
|
388 | |||
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
395 | %automagic function), you don't need to type in the % explicitly. By default, |
|
390 | %automagic function), you don't need to type in the % explicitly. By default, | |
396 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
391 | IPython ships with automagic on, so you should only rarely need the % escape. | |
397 |
|
392 | |||
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
399 | to 'mydir', if it exists. |
|
394 | to 'mydir', if it exists. | |
400 |
|
395 | |||
401 | You can define your own magic functions to extend the system. See the supplied |
|
396 | You can define your own magic functions to extend the system. See the supplied | |
402 | ipythonrc and example-magic.py files for details (in your ipython |
|
397 | ipythonrc and example-magic.py files for details (in your ipython | |
403 | configuration directory, typically $HOME/.ipython/). |
|
398 | configuration directory, typically $HOME/.ipython/). | |
404 |
|
399 | |||
405 | You can also define your own aliased names for magic functions. In your |
|
400 | You can also define your own aliased names for magic functions. In your | |
406 | ipythonrc file, placing a line like: |
|
401 | ipythonrc file, placing a line like: | |
407 |
|
402 | |||
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
409 |
|
404 | |||
410 | will define %pf as a new name for %profile. |
|
405 | will define %pf as a new name for %profile. | |
411 |
|
406 | |||
412 | You can also call magics in code using the magic() function, which IPython |
|
407 | You can also call magics in code using the magic() function, which IPython | |
413 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
408 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
414 |
|
409 | |||
415 | For a list of the available magic functions, use %lsmagic. For a description |
|
410 | For a list of the available magic functions, use %lsmagic. For a description | |
416 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
411 | of any of them, type %magic_name?, e.g. '%cd?'. | |
417 |
|
412 | |||
418 | Currently the magic system has the following functions:\n""" |
|
413 | Currently the magic system has the following functions:\n""" | |
419 |
|
414 | |||
420 | mesc = ESC_MAGIC |
|
415 | mesc = ESC_MAGIC | |
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
422 | "\n\n%s%s\n\n%s" % (outmsg, |
|
417 | "\n\n%s%s\n\n%s" % (outmsg, | |
423 | magic_docs,mesc,mesc, |
|
418 | magic_docs,mesc,mesc, | |
424 | (' '+mesc).join(self.lsmagic()), |
|
419 | (' '+mesc).join(self.lsmagic()), | |
425 | Magic.auto_status[self.shell.automagic] ) ) |
|
420 | Magic.auto_status[self.shell.automagic] ) ) | |
426 | page.page(outmsg) |
|
421 | page.page(outmsg) | |
427 |
|
422 | |||
428 | def magic_automagic(self, parameter_s = ''): |
|
423 | def magic_automagic(self, parameter_s = ''): | |
429 | """Make magic functions callable without having to type the initial %. |
|
424 | """Make magic functions callable without having to type the initial %. | |
430 |
|
425 | |||
431 | Without argumentsl toggles on/off (when off, you must call it as |
|
426 | Without argumentsl toggles on/off (when off, you must call it as | |
432 | %automagic, of course). With arguments it sets the value, and you can |
|
427 | %automagic, of course). With arguments it sets the value, and you can | |
433 | use any of (case insensitive): |
|
428 | use any of (case insensitive): | |
434 |
|
429 | |||
435 | - on,1,True: to activate |
|
430 | - on,1,True: to activate | |
436 |
|
431 | |||
437 | - off,0,False: to deactivate. |
|
432 | - off,0,False: to deactivate. | |
438 |
|
433 | |||
439 | Note that magic functions have lowest priority, so if there's a |
|
434 | Note that magic functions have lowest priority, so if there's a | |
440 | variable whose name collides with that of a magic fn, automagic won't |
|
435 | variable whose name collides with that of a magic fn, automagic won't | |
441 | work for that function (you get the variable instead). However, if you |
|
436 | work for that function (you get the variable instead). However, if you | |
442 | delete the variable (del var), the previously shadowed magic function |
|
437 | delete the variable (del var), the previously shadowed magic function | |
443 | becomes visible to automagic again.""" |
|
438 | becomes visible to automagic again.""" | |
444 |
|
439 | |||
445 | arg = parameter_s.lower() |
|
440 | arg = parameter_s.lower() | |
446 | if parameter_s in ('on','1','true'): |
|
441 | if parameter_s in ('on','1','true'): | |
447 | self.shell.automagic = True |
|
442 | self.shell.automagic = True | |
448 | elif parameter_s in ('off','0','false'): |
|
443 | elif parameter_s in ('off','0','false'): | |
449 | self.shell.automagic = False |
|
444 | self.shell.automagic = False | |
450 | else: |
|
445 | else: | |
451 | self.shell.automagic = not self.shell.automagic |
|
446 | self.shell.automagic = not self.shell.automagic | |
452 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
447 | print '\n' + Magic.auto_status[self.shell.automagic] | |
453 |
|
448 | |||
454 | @testdec.skip_doctest |
|
449 | @testdec.skip_doctest | |
455 | def magic_autocall(self, parameter_s = ''): |
|
450 | def magic_autocall(self, parameter_s = ''): | |
456 | """Make functions callable without having to type parentheses. |
|
451 | """Make functions callable without having to type parentheses. | |
457 |
|
452 | |||
458 | Usage: |
|
453 | Usage: | |
459 |
|
454 | |||
460 | %autocall [mode] |
|
455 | %autocall [mode] | |
461 |
|
456 | |||
462 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
463 | value is toggled on and off (remembering the previous state). |
|
458 | value is toggled on and off (remembering the previous state). | |
464 |
|
459 | |||
465 | In more detail, these values mean: |
|
460 | In more detail, these values mean: | |
466 |
|
461 | |||
467 | 0 -> fully disabled |
|
462 | 0 -> fully disabled | |
468 |
|
463 | |||
469 | 1 -> active, but do not apply if there are no arguments on the line. |
|
464 | 1 -> active, but do not apply if there are no arguments on the line. | |
470 |
|
465 | |||
471 | In this mode, you get: |
|
466 | In this mode, you get: | |
472 |
|
467 | |||
473 | In [1]: callable |
|
468 | In [1]: callable | |
474 | Out[1]: <built-in function callable> |
|
469 | Out[1]: <built-in function callable> | |
475 |
|
470 | |||
476 | In [2]: callable 'hello' |
|
471 | In [2]: callable 'hello' | |
477 | ------> callable('hello') |
|
472 | ------> callable('hello') | |
478 | Out[2]: False |
|
473 | Out[2]: False | |
479 |
|
474 | |||
480 | 2 -> Active always. Even if no arguments are present, the callable |
|
475 | 2 -> Active always. Even if no arguments are present, the callable | |
481 | object is called: |
|
476 | object is called: | |
482 |
|
477 | |||
483 | In [2]: float |
|
478 | In [2]: float | |
484 | ------> float() |
|
479 | ------> float() | |
485 | Out[2]: 0.0 |
|
480 | Out[2]: 0.0 | |
486 |
|
481 | |||
487 | Note that even with autocall off, you can still use '/' at the start of |
|
482 | Note that even with autocall off, you can still use '/' at the start of | |
488 | a line to treat the first argument on the command line as a function |
|
483 | a line to treat the first argument on the command line as a function | |
489 | and add parentheses to it: |
|
484 | and add parentheses to it: | |
490 |
|
485 | |||
491 | In [8]: /str 43 |
|
486 | In [8]: /str 43 | |
492 | ------> str(43) |
|
487 | ------> str(43) | |
493 | Out[8]: '43' |
|
488 | Out[8]: '43' | |
494 |
|
489 | |||
495 | # all-random (note for auto-testing) |
|
490 | # all-random (note for auto-testing) | |
496 | """ |
|
491 | """ | |
497 |
|
492 | |||
498 | if parameter_s: |
|
493 | if parameter_s: | |
499 | arg = int(parameter_s) |
|
494 | arg = int(parameter_s) | |
500 | else: |
|
495 | else: | |
501 | arg = 'toggle' |
|
496 | arg = 'toggle' | |
502 |
|
497 | |||
503 | if not arg in (0,1,2,'toggle'): |
|
498 | if not arg in (0,1,2,'toggle'): | |
504 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
505 | return |
|
500 | return | |
506 |
|
501 | |||
507 | if arg in (0,1,2): |
|
502 | if arg in (0,1,2): | |
508 | self.shell.autocall = arg |
|
503 | self.shell.autocall = arg | |
509 | else: # toggle |
|
504 | else: # toggle | |
510 | if self.shell.autocall: |
|
505 | if self.shell.autocall: | |
511 | self._magic_state.autocall_save = self.shell.autocall |
|
506 | self._magic_state.autocall_save = self.shell.autocall | |
512 | self.shell.autocall = 0 |
|
507 | self.shell.autocall = 0 | |
513 | else: |
|
508 | else: | |
514 | try: |
|
509 | try: | |
515 | self.shell.autocall = self._magic_state.autocall_save |
|
510 | self.shell.autocall = self._magic_state.autocall_save | |
516 | except AttributeError: |
|
511 | except AttributeError: | |
517 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
512 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
518 |
|
513 | |||
519 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
520 |
|
515 | |||
521 |
|
516 | |||
522 | def magic_page(self, parameter_s=''): |
|
517 | def magic_page(self, parameter_s=''): | |
523 | """Pretty print the object and display it through a pager. |
|
518 | """Pretty print the object and display it through a pager. | |
524 |
|
519 | |||
525 | %page [options] OBJECT |
|
520 | %page [options] OBJECT | |
526 |
|
521 | |||
527 | If no object is given, use _ (last output). |
|
522 | If no object is given, use _ (last output). | |
528 |
|
523 | |||
529 | Options: |
|
524 | Options: | |
530 |
|
525 | |||
531 | -r: page str(object), don't pretty-print it.""" |
|
526 | -r: page str(object), don't pretty-print it.""" | |
532 |
|
527 | |||
533 | # After a function contributed by Olivier Aubert, slightly modified. |
|
528 | # After a function contributed by Olivier Aubert, slightly modified. | |
534 |
|
529 | |||
535 | # Process options/args |
|
530 | # Process options/args | |
536 | opts,args = self.parse_options(parameter_s,'r') |
|
531 | opts,args = self.parse_options(parameter_s,'r') | |
537 | raw = 'r' in opts |
|
532 | raw = 'r' in opts | |
538 |
|
533 | |||
539 | oname = args and args or '_' |
|
534 | oname = args and args or '_' | |
540 | info = self._ofind(oname) |
|
535 | info = self._ofind(oname) | |
541 | if info['found']: |
|
536 | if info['found']: | |
542 | txt = (raw and str or pformat)( info['obj'] ) |
|
537 | txt = (raw and str or pformat)( info['obj'] ) | |
543 | page.page(txt) |
|
538 | page.page(txt) | |
544 | else: |
|
539 | else: | |
545 | print 'Object `%s` not found' % oname |
|
540 | print 'Object `%s` not found' % oname | |
546 |
|
541 | |||
547 | def magic_profile(self, parameter_s=''): |
|
542 | def magic_profile(self, parameter_s=''): | |
548 | """Print your currently active IPython profile.""" |
|
543 | """Print your currently active IPython profile.""" | |
549 | if self.shell.profile: |
|
544 | if self.shell.profile: | |
550 | printpl('Current IPython profile: $self.shell.profile.') |
|
545 | printpl('Current IPython profile: $self.shell.profile.') | |
551 | else: |
|
546 | else: | |
552 | print 'No profile active.' |
|
547 | print 'No profile active.' | |
553 |
|
548 | |||
554 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
549 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
555 | """Provide detailed information about an object. |
|
550 | """Provide detailed information about an object. | |
556 |
|
551 | |||
557 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
552 | '%pinfo object' is just a synonym for object? or ?object.""" | |
558 |
|
553 | |||
559 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
554 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
560 |
|
555 | |||
561 |
|
556 | |||
562 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
557 | # detail_level: 0 -> obj? , 1 -> obj?? | |
563 | detail_level = 0 |
|
558 | detail_level = 0 | |
564 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
565 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
560 | # happen if the user types 'pinfo foo?' at the cmd line. | |
566 | pinfo,qmark1,oname,qmark2 = \ |
|
561 | pinfo,qmark1,oname,qmark2 = \ | |
567 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
568 | if pinfo or qmark1 or qmark2: |
|
563 | if pinfo or qmark1 or qmark2: | |
569 | detail_level = 1 |
|
564 | detail_level = 1 | |
570 | if "*" in oname: |
|
565 | if "*" in oname: | |
571 | self.magic_psearch(oname) |
|
566 | self.magic_psearch(oname) | |
572 | else: |
|
567 | else: | |
573 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
574 | namespaces=namespaces) |
|
569 | namespaces=namespaces) | |
575 |
|
570 | |||
576 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
577 | """Provide extra detailed information about an object. |
|
572 | """Provide extra detailed information about an object. | |
578 |
|
573 | |||
579 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
580 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
581 | namespaces=namespaces) |
|
576 | namespaces=namespaces) | |
582 |
|
577 | |||
583 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
578 | def magic_pdef(self, parameter_s='', namespaces=None): | |
584 | """Print the definition header for any callable object. |
|
579 | """Print the definition header for any callable object. | |
585 |
|
580 | |||
586 | If the object is a class, print the constructor information.""" |
|
581 | If the object is a class, print the constructor information.""" | |
587 | self._inspect('pdef',parameter_s, namespaces) |
|
582 | self._inspect('pdef',parameter_s, namespaces) | |
588 |
|
583 | |||
589 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
584 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
590 | """Print the docstring for an object. |
|
585 | """Print the docstring for an object. | |
591 |
|
586 | |||
592 | If the given object is a class, it will print both the class and the |
|
587 | If the given object is a class, it will print both the class and the | |
593 | constructor docstrings.""" |
|
588 | constructor docstrings.""" | |
594 | self._inspect('pdoc',parameter_s, namespaces) |
|
589 | self._inspect('pdoc',parameter_s, namespaces) | |
595 |
|
590 | |||
596 | def magic_psource(self, parameter_s='', namespaces=None): |
|
591 | def magic_psource(self, parameter_s='', namespaces=None): | |
597 | """Print (or run through pager) the source code for an object.""" |
|
592 | """Print (or run through pager) the source code for an object.""" | |
598 | self._inspect('psource',parameter_s, namespaces) |
|
593 | self._inspect('psource',parameter_s, namespaces) | |
599 |
|
594 | |||
600 | def magic_pfile(self, parameter_s=''): |
|
595 | def magic_pfile(self, parameter_s=''): | |
601 | """Print (or run through pager) the file where an object is defined. |
|
596 | """Print (or run through pager) the file where an object is defined. | |
602 |
|
597 | |||
603 | The file opens at the line where the object definition begins. IPython |
|
598 | The file opens at the line where the object definition begins. IPython | |
604 | will honor the environment variable PAGER if set, and otherwise will |
|
599 | will honor the environment variable PAGER if set, and otherwise will | |
605 | do its best to print the file in a convenient form. |
|
600 | do its best to print the file in a convenient form. | |
606 |
|
601 | |||
607 | If the given argument is not an object currently defined, IPython will |
|
602 | If the given argument is not an object currently defined, IPython will | |
608 | try to interpret it as a filename (automatically adding a .py extension |
|
603 | try to interpret it as a filename (automatically adding a .py extension | |
609 | if needed). You can thus use %pfile as a syntax highlighting code |
|
604 | if needed). You can thus use %pfile as a syntax highlighting code | |
610 | viewer.""" |
|
605 | viewer.""" | |
611 |
|
606 | |||
612 | # first interpret argument as an object name |
|
607 | # first interpret argument as an object name | |
613 | out = self._inspect('pfile',parameter_s) |
|
608 | out = self._inspect('pfile',parameter_s) | |
614 | # if not, try the input as a filename |
|
609 | # if not, try the input as a filename | |
615 | if out == 'not found': |
|
610 | if out == 'not found': | |
616 | try: |
|
611 | try: | |
617 | filename = get_py_filename(parameter_s) |
|
612 | filename = get_py_filename(parameter_s) | |
618 | except IOError,msg: |
|
613 | except IOError,msg: | |
619 | print msg |
|
614 | print msg | |
620 | return |
|
615 | return | |
621 | page.page(self.shell.inspector.format(file(filename).read())) |
|
616 | page.page(self.shell.inspector.format(file(filename).read())) | |
622 |
|
617 | |||
623 | def magic_psearch(self, parameter_s=''): |
|
618 | def magic_psearch(self, parameter_s=''): | |
624 | """Search for object in namespaces by wildcard. |
|
619 | """Search for object in namespaces by wildcard. | |
625 |
|
620 | |||
626 | %psearch [options] PATTERN [OBJECT TYPE] |
|
621 | %psearch [options] PATTERN [OBJECT TYPE] | |
627 |
|
622 | |||
628 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
623 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
629 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
624 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
630 | rest of the command line must be unchanged (options come first), so |
|
625 | rest of the command line must be unchanged (options come first), so | |
631 | for example the following forms are equivalent |
|
626 | for example the following forms are equivalent | |
632 |
|
627 | |||
633 | %psearch -i a* function |
|
628 | %psearch -i a* function | |
634 | -i a* function? |
|
629 | -i a* function? | |
635 | ?-i a* function |
|
630 | ?-i a* function | |
636 |
|
631 | |||
637 | Arguments: |
|
632 | Arguments: | |
638 |
|
633 | |||
639 | PATTERN |
|
634 | PATTERN | |
640 |
|
635 | |||
641 | where PATTERN is a string containing * as a wildcard similar to its |
|
636 | where PATTERN is a string containing * as a wildcard similar to its | |
642 | use in a shell. The pattern is matched in all namespaces on the |
|
637 | use in a shell. The pattern is matched in all namespaces on the | |
643 | search path. By default objects starting with a single _ are not |
|
638 | search path. By default objects starting with a single _ are not | |
644 | matched, many IPython generated objects have a single |
|
639 | matched, many IPython generated objects have a single | |
645 | underscore. The default is case insensitive matching. Matching is |
|
640 | underscore. The default is case insensitive matching. Matching is | |
646 | also done on the attributes of objects and not only on the objects |
|
641 | also done on the attributes of objects and not only on the objects | |
647 | in a module. |
|
642 | in a module. | |
648 |
|
643 | |||
649 | [OBJECT TYPE] |
|
644 | [OBJECT TYPE] | |
650 |
|
645 | |||
651 | Is the name of a python type from the types module. The name is |
|
646 | Is the name of a python type from the types module. The name is | |
652 | given in lowercase without the ending type, ex. StringType is |
|
647 | given in lowercase without the ending type, ex. StringType is | |
653 | written string. By adding a type here only objects matching the |
|
648 | written string. By adding a type here only objects matching the | |
654 | given type are matched. Using all here makes the pattern match all |
|
649 | given type are matched. Using all here makes the pattern match all | |
655 | types (this is the default). |
|
650 | types (this is the default). | |
656 |
|
651 | |||
657 | Options: |
|
652 | Options: | |
658 |
|
653 | |||
659 | -a: makes the pattern match even objects whose names start with a |
|
654 | -a: makes the pattern match even objects whose names start with a | |
660 | single underscore. These names are normally ommitted from the |
|
655 | single underscore. These names are normally ommitted from the | |
661 | search. |
|
656 | search. | |
662 |
|
657 | |||
663 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
658 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
664 | these options is given, the default is read from your ipythonrc |
|
659 | these options is given, the default is read from your ipythonrc | |
665 | file. The option name which sets this value is |
|
660 | file. The option name which sets this value is | |
666 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
661 | 'wildcards_case_sensitive'. If this option is not specified in your | |
667 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
662 | ipythonrc file, IPython's internal default is to do a case sensitive | |
668 | search. |
|
663 | search. | |
669 |
|
664 | |||
670 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
671 | specifiy can be searched in any of the following namespaces: |
|
666 | specifiy can be searched in any of the following namespaces: | |
672 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
673 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 'builtin' and 'user' are the search defaults. Note that you should | |
674 | not use quotes when specifying namespaces. |
|
669 | not use quotes when specifying namespaces. | |
675 |
|
670 | |||
676 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 'Builtin' contains the python module builtin, 'user' contains all | |
677 | user data, 'alias' only contain the shell aliases and no python |
|
672 | user data, 'alias' only contain the shell aliases and no python | |
678 | objects, 'internal' contains objects used by IPython. The |
|
673 | objects, 'internal' contains objects used by IPython. The | |
679 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 'user_global' namespace is only used by embedded IPython instances, | |
680 | and it contains module-level globals. You can add namespaces to the |
|
675 | and it contains module-level globals. You can add namespaces to the | |
681 | search with -s or exclude them with -e (these options can be given |
|
676 | search with -s or exclude them with -e (these options can be given | |
682 | more than once). |
|
677 | more than once). | |
683 |
|
678 | |||
684 | Examples: |
|
679 | Examples: | |
685 |
|
680 | |||
686 | %psearch a* -> objects beginning with an a |
|
681 | %psearch a* -> objects beginning with an a | |
687 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
682 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
688 | %psearch a* function -> all functions beginning with an a |
|
683 | %psearch a* function -> all functions beginning with an a | |
689 | %psearch re.e* -> objects beginning with an e in module re |
|
684 | %psearch re.e* -> objects beginning with an e in module re | |
690 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
685 | %psearch r*.e* -> objects that start with e in modules starting in r | |
691 | %psearch r*.* string -> all strings in modules beginning with r |
|
686 | %psearch r*.* string -> all strings in modules beginning with r | |
692 |
|
687 | |||
693 | Case sensitve search: |
|
688 | Case sensitve search: | |
694 |
|
689 | |||
695 | %psearch -c a* list all object beginning with lower case a |
|
690 | %psearch -c a* list all object beginning with lower case a | |
696 |
|
691 | |||
697 | Show objects beginning with a single _: |
|
692 | Show objects beginning with a single _: | |
698 |
|
693 | |||
699 | %psearch -a _* list objects beginning with a single underscore""" |
|
694 | %psearch -a _* list objects beginning with a single underscore""" | |
700 | try: |
|
695 | try: | |
701 | parameter_s = parameter_s.encode('ascii') |
|
696 | parameter_s = parameter_s.encode('ascii') | |
702 | except UnicodeEncodeError: |
|
697 | except UnicodeEncodeError: | |
703 | print 'Python identifiers can only contain ascii characters.' |
|
698 | print 'Python identifiers can only contain ascii characters.' | |
704 | return |
|
699 | return | |
705 |
|
700 | |||
706 | # default namespaces to be searched |
|
701 | # default namespaces to be searched | |
707 | def_search = ['user','builtin'] |
|
702 | def_search = ['user','builtin'] | |
708 |
|
703 | |||
709 | # Process options/args |
|
704 | # Process options/args | |
710 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
705 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
711 | opt = opts.get |
|
706 | opt = opts.get | |
712 | shell = self.shell |
|
707 | shell = self.shell | |
713 | psearch = shell.inspector.psearch |
|
708 | psearch = shell.inspector.psearch | |
714 |
|
709 | |||
715 | # select case options |
|
710 | # select case options | |
716 | if opts.has_key('i'): |
|
711 | if opts.has_key('i'): | |
717 | ignore_case = True |
|
712 | ignore_case = True | |
718 | elif opts.has_key('c'): |
|
713 | elif opts.has_key('c'): | |
719 | ignore_case = False |
|
714 | ignore_case = False | |
720 | else: |
|
715 | else: | |
721 | ignore_case = not shell.wildcards_case_sensitive |
|
716 | ignore_case = not shell.wildcards_case_sensitive | |
722 |
|
717 | |||
723 | # Build list of namespaces to search from user options |
|
718 | # Build list of namespaces to search from user options | |
724 | def_search.extend(opt('s',[])) |
|
719 | def_search.extend(opt('s',[])) | |
725 | ns_exclude = ns_exclude=opt('e',[]) |
|
720 | ns_exclude = ns_exclude=opt('e',[]) | |
726 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
721 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
727 |
|
722 | |||
728 | # Call the actual search |
|
723 | # Call the actual search | |
729 | try: |
|
724 | try: | |
730 | psearch(args,shell.ns_table,ns_search, |
|
725 | psearch(args,shell.ns_table,ns_search, | |
731 | show_all=opt('a'),ignore_case=ignore_case) |
|
726 | show_all=opt('a'),ignore_case=ignore_case) | |
732 | except: |
|
727 | except: | |
733 | shell.showtraceback() |
|
728 | shell.showtraceback() | |
734 |
|
729 | |||
735 | def magic_who_ls(self, parameter_s=''): |
|
730 | def magic_who_ls(self, parameter_s=''): | |
736 | """Return a sorted list of all interactive variables. |
|
731 | """Return a sorted list of all interactive variables. | |
737 |
|
732 | |||
738 | If arguments are given, only variables of types matching these |
|
733 | If arguments are given, only variables of types matching these | |
739 | arguments are returned.""" |
|
734 | arguments are returned.""" | |
740 |
|
735 | |||
741 | user_ns = self.shell.user_ns |
|
736 | user_ns = self.shell.user_ns | |
742 | internal_ns = self.shell.internal_ns |
|
737 | internal_ns = self.shell.internal_ns | |
743 | user_ns_hidden = self.shell.user_ns_hidden |
|
738 | user_ns_hidden = self.shell.user_ns_hidden | |
744 | out = [ i for i in user_ns |
|
739 | out = [ i for i in user_ns | |
745 | if not i.startswith('_') \ |
|
740 | if not i.startswith('_') \ | |
746 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
741 | and not (i in internal_ns or i in user_ns_hidden) ] | |
747 |
|
742 | |||
748 | typelist = parameter_s.split() |
|
743 | typelist = parameter_s.split() | |
749 | if typelist: |
|
744 | if typelist: | |
750 | typeset = set(typelist) |
|
745 | typeset = set(typelist) | |
751 | out = [i for i in out if type(i).__name__ in typeset] |
|
746 | out = [i for i in out if type(i).__name__ in typeset] | |
752 |
|
747 | |||
753 | out.sort() |
|
748 | out.sort() | |
754 | return out |
|
749 | return out | |
755 |
|
750 | |||
756 | def magic_who(self, parameter_s=''): |
|
751 | def magic_who(self, parameter_s=''): | |
757 | """Print all interactive variables, with some minimal formatting. |
|
752 | """Print all interactive variables, with some minimal formatting. | |
758 |
|
753 | |||
759 | If any arguments are given, only variables whose type matches one of |
|
754 | If any arguments are given, only variables whose type matches one of | |
760 | these are printed. For example: |
|
755 | these are printed. For example: | |
761 |
|
756 | |||
762 | %who function str |
|
757 | %who function str | |
763 |
|
758 | |||
764 | will only list functions and strings, excluding all other types of |
|
759 | will only list functions and strings, excluding all other types of | |
765 | variables. To find the proper type names, simply use type(var) at a |
|
760 | variables. To find the proper type names, simply use type(var) at a | |
766 | command line to see how python prints type names. For example: |
|
761 | command line to see how python prints type names. For example: | |
767 |
|
762 | |||
768 | In [1]: type('hello')\\ |
|
763 | In [1]: type('hello')\\ | |
769 | Out[1]: <type 'str'> |
|
764 | Out[1]: <type 'str'> | |
770 |
|
765 | |||
771 | indicates that the type name for strings is 'str'. |
|
766 | indicates that the type name for strings is 'str'. | |
772 |
|
767 | |||
773 | %who always excludes executed names loaded through your configuration |
|
768 | %who always excludes executed names loaded through your configuration | |
774 | file and things which are internal to IPython. |
|
769 | file and things which are internal to IPython. | |
775 |
|
770 | |||
776 | This is deliberate, as typically you may load many modules and the |
|
771 | This is deliberate, as typically you may load many modules and the | |
777 | purpose of %who is to show you only what you've manually defined.""" |
|
772 | purpose of %who is to show you only what you've manually defined.""" | |
778 |
|
773 | |||
779 | varlist = self.magic_who_ls(parameter_s) |
|
774 | varlist = self.magic_who_ls(parameter_s) | |
780 | if not varlist: |
|
775 | if not varlist: | |
781 | if parameter_s: |
|
776 | if parameter_s: | |
782 | print 'No variables match your requested type.' |
|
777 | print 'No variables match your requested type.' | |
783 | else: |
|
778 | else: | |
784 | print 'Interactive namespace is empty.' |
|
779 | print 'Interactive namespace is empty.' | |
785 | return |
|
780 | return | |
786 |
|
781 | |||
787 | # if we have variables, move on... |
|
782 | # if we have variables, move on... | |
788 | count = 0 |
|
783 | count = 0 | |
789 | for i in varlist: |
|
784 | for i in varlist: | |
790 | print i+'\t', |
|
785 | print i+'\t', | |
791 | count += 1 |
|
786 | count += 1 | |
792 | if count > 8: |
|
787 | if count > 8: | |
793 | count = 0 |
|
788 | count = 0 | |
794 |
|
789 | |||
795 |
|
790 | |||
796 |
|
791 | |||
797 | def magic_whos(self, parameter_s=''): |
|
792 | def magic_whos(self, parameter_s=''): | |
798 | """Like %who, but gives some extra information about each variable. |
|
793 | """Like %who, but gives some extra information about each variable. | |
799 |
|
794 | |||
800 | The same type filtering of %who can be applied here. |
|
795 | The same type filtering of %who can be applied here. | |
801 |
|
796 | |||
802 | For all variables, the type is printed. Additionally it prints: |
|
797 | For all variables, the type is printed. Additionally it prints: | |
803 |
|
798 | |||
804 | - For {},[],(): their length. |
|
799 | - For {},[],(): their length. | |
805 |
|
800 | |||
806 | - For numpy and Numeric arrays, a summary with shape, number of |
|
801 | - For numpy and Numeric arrays, a summary with shape, number of | |
807 | elements, typecode and size in memory. |
|
802 | elements, typecode and size in memory. | |
808 |
|
803 | |||
809 | - Everything else: a string representation, snipping their middle if |
|
804 | - Everything else: a string representation, snipping their middle if | |
810 | too long.""" |
|
805 | too long.""" | |
811 |
|
806 | |||
812 | varnames = self.magic_who_ls(parameter_s) |
|
807 | varnames = self.magic_who_ls(parameter_s) | |
813 | if not varnames: |
|
808 | if not varnames: | |
814 | if parameter_s: |
|
809 | if parameter_s: | |
815 | print 'No variables match your requested type.' |
|
810 | print 'No variables match your requested type.' | |
816 | else: |
|
811 | else: | |
817 | print 'Interactive namespace is empty.' |
|
812 | print 'Interactive namespace is empty.' | |
818 | return |
|
813 | return | |
819 |
|
814 | |||
820 | # if we have variables, move on... |
|
815 | # if we have variables, move on... | |
821 |
|
816 | |||
822 | # for these types, show len() instead of data: |
|
817 | # for these types, show len() instead of data: | |
823 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
818 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
824 |
|
819 | |||
825 | # for numpy/Numeric arrays, display summary info |
|
820 | # for numpy/Numeric arrays, display summary info | |
826 | try: |
|
821 | try: | |
827 | import numpy |
|
822 | import numpy | |
828 | except ImportError: |
|
823 | except ImportError: | |
829 | ndarray_type = None |
|
824 | ndarray_type = None | |
830 | else: |
|
825 | else: | |
831 | ndarray_type = numpy.ndarray.__name__ |
|
826 | ndarray_type = numpy.ndarray.__name__ | |
832 | try: |
|
827 | try: | |
833 | import Numeric |
|
828 | import Numeric | |
834 | except ImportError: |
|
829 | except ImportError: | |
835 | array_type = None |
|
830 | array_type = None | |
836 | else: |
|
831 | else: | |
837 | array_type = Numeric.ArrayType.__name__ |
|
832 | array_type = Numeric.ArrayType.__name__ | |
838 |
|
833 | |||
839 | # Find all variable names and types so we can figure out column sizes |
|
834 | # Find all variable names and types so we can figure out column sizes | |
840 | def get_vars(i): |
|
835 | def get_vars(i): | |
841 | return self.shell.user_ns[i] |
|
836 | return self.shell.user_ns[i] | |
842 |
|
837 | |||
843 | # some types are well known and can be shorter |
|
838 | # some types are well known and can be shorter | |
844 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
839 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
845 | def type_name(v): |
|
840 | def type_name(v): | |
846 | tn = type(v).__name__ |
|
841 | tn = type(v).__name__ | |
847 | return abbrevs.get(tn,tn) |
|
842 | return abbrevs.get(tn,tn) | |
848 |
|
843 | |||
849 | varlist = map(get_vars,varnames) |
|
844 | varlist = map(get_vars,varnames) | |
850 |
|
845 | |||
851 | typelist = [] |
|
846 | typelist = [] | |
852 | for vv in varlist: |
|
847 | for vv in varlist: | |
853 | tt = type_name(vv) |
|
848 | tt = type_name(vv) | |
854 |
|
849 | |||
855 | if tt=='instance': |
|
850 | if tt=='instance': | |
856 | typelist.append( abbrevs.get(str(vv.__class__), |
|
851 | typelist.append( abbrevs.get(str(vv.__class__), | |
857 | str(vv.__class__))) |
|
852 | str(vv.__class__))) | |
858 | else: |
|
853 | else: | |
859 | typelist.append(tt) |
|
854 | typelist.append(tt) | |
860 |
|
855 | |||
861 | # column labels and # of spaces as separator |
|
856 | # column labels and # of spaces as separator | |
862 | varlabel = 'Variable' |
|
857 | varlabel = 'Variable' | |
863 | typelabel = 'Type' |
|
858 | typelabel = 'Type' | |
864 | datalabel = 'Data/Info' |
|
859 | datalabel = 'Data/Info' | |
865 | colsep = 3 |
|
860 | colsep = 3 | |
866 | # variable format strings |
|
861 | # variable format strings | |
867 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
862 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
868 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
863 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
869 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
864 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
870 | # find the size of the columns to format the output nicely |
|
865 | # find the size of the columns to format the output nicely | |
871 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
866 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
872 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
867 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
873 | # table header |
|
868 | # table header | |
874 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
869 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
875 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
870 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
876 | # and the table itself |
|
871 | # and the table itself | |
877 | kb = 1024 |
|
872 | kb = 1024 | |
878 | Mb = 1048576 # kb**2 |
|
873 | Mb = 1048576 # kb**2 | |
879 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
874 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
880 | print itpl(vformat), |
|
875 | print itpl(vformat), | |
881 | if vtype in seq_types: |
|
876 | if vtype in seq_types: | |
882 | print len(var) |
|
877 | print len(var) | |
883 | elif vtype in [array_type,ndarray_type]: |
|
878 | elif vtype in [array_type,ndarray_type]: | |
884 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
879 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
885 | if vtype==ndarray_type: |
|
880 | if vtype==ndarray_type: | |
886 | # numpy |
|
881 | # numpy | |
887 | vsize = var.size |
|
882 | vsize = var.size | |
888 | vbytes = vsize*var.itemsize |
|
883 | vbytes = vsize*var.itemsize | |
889 | vdtype = var.dtype |
|
884 | vdtype = var.dtype | |
890 | else: |
|
885 | else: | |
891 | # Numeric |
|
886 | # Numeric | |
892 | vsize = Numeric.size(var) |
|
887 | vsize = Numeric.size(var) | |
893 | vbytes = vsize*var.itemsize() |
|
888 | vbytes = vsize*var.itemsize() | |
894 | vdtype = var.typecode() |
|
889 | vdtype = var.typecode() | |
895 |
|
890 | |||
896 | if vbytes < 100000: |
|
891 | if vbytes < 100000: | |
897 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
892 | print aformat % (vshape,vsize,vdtype,vbytes) | |
898 | else: |
|
893 | else: | |
899 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
894 | print aformat % (vshape,vsize,vdtype,vbytes), | |
900 | if vbytes < Mb: |
|
895 | if vbytes < Mb: | |
901 | print '(%s kb)' % (vbytes/kb,) |
|
896 | print '(%s kb)' % (vbytes/kb,) | |
902 | else: |
|
897 | else: | |
903 | print '(%s Mb)' % (vbytes/Mb,) |
|
898 | print '(%s Mb)' % (vbytes/Mb,) | |
904 | else: |
|
899 | else: | |
905 | try: |
|
900 | try: | |
906 | vstr = str(var) |
|
901 | vstr = str(var) | |
907 | except UnicodeEncodeError: |
|
902 | except UnicodeEncodeError: | |
908 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
903 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
909 | 'backslashreplace') |
|
904 | 'backslashreplace') | |
910 | vstr = vstr.replace('\n','\\n') |
|
905 | vstr = vstr.replace('\n','\\n') | |
911 | if len(vstr) < 50: |
|
906 | if len(vstr) < 50: | |
912 | print vstr |
|
907 | print vstr | |
913 | else: |
|
908 | else: | |
914 | printpl(vfmt_short) |
|
909 | printpl(vfmt_short) | |
915 |
|
910 | |||
916 | def magic_reset(self, parameter_s=''): |
|
911 | def magic_reset(self, parameter_s=''): | |
917 | """Resets the namespace by removing all names defined by the user. |
|
912 | """Resets the namespace by removing all names defined by the user. | |
918 |
|
913 | |||
919 | Input/Output history are left around in case you need them. |
|
914 | Input/Output history are left around in case you need them. | |
920 |
|
915 | |||
921 | Parameters |
|
916 | Parameters | |
922 | ---------- |
|
917 | ---------- | |
923 | -y : force reset without asking for confirmation. |
|
918 | -y : force reset without asking for confirmation. | |
924 |
|
919 | |||
925 | Examples |
|
920 | Examples | |
926 | -------- |
|
921 | -------- | |
927 | In [6]: a = 1 |
|
922 | In [6]: a = 1 | |
928 |
|
923 | |||
929 | In [7]: a |
|
924 | In [7]: a | |
930 | Out[7]: 1 |
|
925 | Out[7]: 1 | |
931 |
|
926 | |||
932 | In [8]: 'a' in _ip.user_ns |
|
927 | In [8]: 'a' in _ip.user_ns | |
933 | Out[8]: True |
|
928 | Out[8]: True | |
934 |
|
929 | |||
935 | In [9]: %reset -f |
|
930 | In [9]: %reset -f | |
936 |
|
931 | |||
937 | In [10]: 'a' in _ip.user_ns |
|
932 | In [10]: 'a' in _ip.user_ns | |
938 | Out[10]: False |
|
933 | Out[10]: False | |
939 | """ |
|
934 | """ | |
940 |
|
935 | |||
941 | if parameter_s == '-f': |
|
936 | if parameter_s == '-f': | |
942 | ans = True |
|
937 | ans = True | |
943 | else: |
|
938 | else: | |
944 | ans = self.shell.ask_yes_no( |
|
939 | ans = self.shell.ask_yes_no( | |
945 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
940 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
946 | if not ans: |
|
941 | if not ans: | |
947 | print 'Nothing done.' |
|
942 | print 'Nothing done.' | |
948 | return |
|
943 | return | |
949 | user_ns = self.shell.user_ns |
|
944 | user_ns = self.shell.user_ns | |
950 | for i in self.magic_who_ls(): |
|
945 | for i in self.magic_who_ls(): | |
951 | del(user_ns[i]) |
|
946 | del(user_ns[i]) | |
952 |
|
947 | |||
953 | # Also flush the private list of module references kept for script |
|
948 | # Also flush the private list of module references kept for script | |
954 | # execution protection |
|
949 | # execution protection | |
955 | self.shell.clear_main_mod_cache() |
|
950 | self.shell.clear_main_mod_cache() | |
956 |
|
951 | |||
957 | def magic_reset_selective(self, parameter_s=''): |
|
952 | def magic_reset_selective(self, parameter_s=''): | |
958 | """Resets the namespace by removing names defined by the user. |
|
953 | """Resets the namespace by removing names defined by the user. | |
959 |
|
954 | |||
960 | Input/Output history are left around in case you need them. |
|
955 | Input/Output history are left around in case you need them. | |
961 |
|
956 | |||
962 | %reset_selective [-f] regex |
|
957 | %reset_selective [-f] regex | |
963 |
|
958 | |||
964 | No action is taken if regex is not included |
|
959 | No action is taken if regex is not included | |
965 |
|
960 | |||
966 | Options |
|
961 | Options | |
967 | -f : force reset without asking for confirmation. |
|
962 | -f : force reset without asking for confirmation. | |
968 |
|
963 | |||
969 | Examples |
|
964 | Examples | |
970 | -------- |
|
965 | -------- | |
971 |
|
966 | |||
972 | We first fully reset the namespace so your output looks identical to |
|
967 | We first fully reset the namespace so your output looks identical to | |
973 | this example for pedagogical reasons; in practice you do not need a |
|
968 | this example for pedagogical reasons; in practice you do not need a | |
974 | full reset. |
|
969 | full reset. | |
975 |
|
970 | |||
976 | In [1]: %reset -f |
|
971 | In [1]: %reset -f | |
977 |
|
972 | |||
978 | Now, with a clean namespace we can make a few variables and use |
|
973 | Now, with a clean namespace we can make a few variables and use | |
979 | %reset_selective to only delete names that match our regexp: |
|
974 | %reset_selective to only delete names that match our regexp: | |
980 |
|
975 | |||
981 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
976 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
982 |
|
977 | |||
983 | In [3]: who_ls |
|
978 | In [3]: who_ls | |
984 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
979 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
985 |
|
980 | |||
986 | In [4]: %reset_selective -f b[2-3]m |
|
981 | In [4]: %reset_selective -f b[2-3]m | |
987 |
|
982 | |||
988 | In [5]: who_ls |
|
983 | In [5]: who_ls | |
989 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
984 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
990 |
|
985 | |||
991 | In [6]: %reset_selective -f d |
|
986 | In [6]: %reset_selective -f d | |
992 |
|
987 | |||
993 | In [7]: who_ls |
|
988 | In [7]: who_ls | |
994 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
989 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
995 |
|
990 | |||
996 | In [8]: %reset_selective -f c |
|
991 | In [8]: %reset_selective -f c | |
997 |
|
992 | |||
998 | In [9]: who_ls |
|
993 | In [9]: who_ls | |
999 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
994 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1000 |
|
995 | |||
1001 | In [10]: %reset_selective -f b |
|
996 | In [10]: %reset_selective -f b | |
1002 |
|
997 | |||
1003 | In [11]: who_ls |
|
998 | In [11]: who_ls | |
1004 | Out[11]: ['a'] |
|
999 | Out[11]: ['a'] | |
1005 | """ |
|
1000 | """ | |
1006 |
|
1001 | |||
1007 | opts, regex = self.parse_options(parameter_s,'f') |
|
1002 | opts, regex = self.parse_options(parameter_s,'f') | |
1008 |
|
1003 | |||
1009 | if opts.has_key('f'): |
|
1004 | if opts.has_key('f'): | |
1010 | ans = True |
|
1005 | ans = True | |
1011 | else: |
|
1006 | else: | |
1012 | ans = self.shell.ask_yes_no( |
|
1007 | ans = self.shell.ask_yes_no( | |
1013 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1008 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1014 | if not ans: |
|
1009 | if not ans: | |
1015 | print 'Nothing done.' |
|
1010 | print 'Nothing done.' | |
1016 | return |
|
1011 | return | |
1017 | user_ns = self.shell.user_ns |
|
1012 | user_ns = self.shell.user_ns | |
1018 | if not regex: |
|
1013 | if not regex: | |
1019 | print 'No regex pattern specified. Nothing done.' |
|
1014 | print 'No regex pattern specified. Nothing done.' | |
1020 | return |
|
1015 | return | |
1021 | else: |
|
1016 | else: | |
1022 | try: |
|
1017 | try: | |
1023 | m = re.compile(regex) |
|
1018 | m = re.compile(regex) | |
1024 | except TypeError: |
|
1019 | except TypeError: | |
1025 | raise TypeError('regex must be a string or compiled pattern') |
|
1020 | raise TypeError('regex must be a string or compiled pattern') | |
1026 | for i in self.magic_who_ls(): |
|
1021 | for i in self.magic_who_ls(): | |
1027 | if m.search(i): |
|
1022 | if m.search(i): | |
1028 | del(user_ns[i]) |
|
1023 | del(user_ns[i]) | |
1029 |
|
1024 | |||
1030 | def magic_logstart(self,parameter_s=''): |
|
1025 | def magic_logstart(self,parameter_s=''): | |
1031 | """Start logging anywhere in a session. |
|
1026 | """Start logging anywhere in a session. | |
1032 |
|
1027 | |||
1033 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1034 |
|
1029 | |||
1035 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1036 | current directory, in 'rotate' mode (see below). |
|
1031 | current directory, in 'rotate' mode (see below). | |
1037 |
|
1032 | |||
1038 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1039 | history up to that point and then continues logging. |
|
1034 | history up to that point and then continues logging. | |
1040 |
|
1035 | |||
1041 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1036 | %logstart takes a second optional parameter: logging mode. This can be one | |
1042 | of (note that the modes are given unquoted):\\ |
|
1037 | of (note that the modes are given unquoted):\\ | |
1043 | append: well, that says it.\\ |
|
1038 | append: well, that says it.\\ | |
1044 | backup: rename (if exists) to name~ and start name.\\ |
|
1039 | backup: rename (if exists) to name~ and start name.\\ | |
1045 | global: single logfile in your home dir, appended to.\\ |
|
1040 | global: single logfile in your home dir, appended to.\\ | |
1046 | over : overwrite existing log.\\ |
|
1041 | over : overwrite existing log.\\ | |
1047 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1042 | rotate: create rotating logs name.1~, name.2~, etc. | |
1048 |
|
1043 | |||
1049 | Options: |
|
1044 | Options: | |
1050 |
|
1045 | |||
1051 | -o: log also IPython's output. In this mode, all commands which |
|
1046 | -o: log also IPython's output. In this mode, all commands which | |
1052 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1047 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1053 | their corresponding input line. The output lines are always |
|
1048 | their corresponding input line. The output lines are always | |
1054 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1055 | Python code. |
|
1050 | Python code. | |
1056 |
|
1051 | |||
1057 | Since this marker is always the same, filtering only the output from |
|
1052 | Since this marker is always the same, filtering only the output from | |
1058 | a log is very easy, using for example a simple awk call: |
|
1053 | a log is very easy, using for example a simple awk call: | |
1059 |
|
1054 | |||
1060 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1061 |
|
1056 | |||
1062 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1063 | input, so that user lines are logged in their final form, converted |
|
1058 | input, so that user lines are logged in their final form, converted | |
1064 | into valid Python. For example, %Exit is logged as |
|
1059 | into valid Python. For example, %Exit is logged as | |
1065 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1066 | exactly as typed, with no transformations applied. |
|
1061 | exactly as typed, with no transformations applied. | |
1067 |
|
1062 | |||
1068 | -t: put timestamps before each input line logged (these are put in |
|
1063 | -t: put timestamps before each input line logged (these are put in | |
1069 | comments).""" |
|
1064 | comments).""" | |
1070 |
|
1065 | |||
1071 | opts,par = self.parse_options(parameter_s,'ort') |
|
1066 | opts,par = self.parse_options(parameter_s,'ort') | |
1072 | log_output = 'o' in opts |
|
1067 | log_output = 'o' in opts | |
1073 | log_raw_input = 'r' in opts |
|
1068 | log_raw_input = 'r' in opts | |
1074 | timestamp = 't' in opts |
|
1069 | timestamp = 't' in opts | |
1075 |
|
1070 | |||
1076 | logger = self.shell.logger |
|
1071 | logger = self.shell.logger | |
1077 |
|
1072 | |||
1078 | # if no args are given, the defaults set in the logger constructor by |
|
1073 | # if no args are given, the defaults set in the logger constructor by | |
1079 | # ipytohn remain valid |
|
1074 | # ipytohn remain valid | |
1080 | if par: |
|
1075 | if par: | |
1081 | try: |
|
1076 | try: | |
1082 | logfname,logmode = par.split() |
|
1077 | logfname,logmode = par.split() | |
1083 | except: |
|
1078 | except: | |
1084 | logfname = par |
|
1079 | logfname = par | |
1085 | logmode = 'backup' |
|
1080 | logmode = 'backup' | |
1086 | else: |
|
1081 | else: | |
1087 | logfname = logger.logfname |
|
1082 | logfname = logger.logfname | |
1088 | logmode = logger.logmode |
|
1083 | logmode = logger.logmode | |
1089 | # put logfname into rc struct as if it had been called on the command |
|
1084 | # put logfname into rc struct as if it had been called on the command | |
1090 | # line, so it ends up saved in the log header Save it in case we need |
|
1085 | # line, so it ends up saved in the log header Save it in case we need | |
1091 | # to restore it... |
|
1086 | # to restore it... | |
1092 | old_logfile = self.shell.logfile |
|
1087 | old_logfile = self.shell.logfile | |
1093 | if logfname: |
|
1088 | if logfname: | |
1094 | logfname = os.path.expanduser(logfname) |
|
1089 | logfname = os.path.expanduser(logfname) | |
1095 | self.shell.logfile = logfname |
|
1090 | self.shell.logfile = logfname | |
1096 |
|
1091 | |||
1097 | loghead = '# IPython log file\n\n' |
|
1092 | loghead = '# IPython log file\n\n' | |
1098 | try: |
|
1093 | try: | |
1099 | started = logger.logstart(logfname,loghead,logmode, |
|
1094 | started = logger.logstart(logfname,loghead,logmode, | |
1100 | log_output,timestamp,log_raw_input) |
|
1095 | log_output,timestamp,log_raw_input) | |
1101 | except: |
|
1096 | except: | |
1102 | self.shell.logfile = old_logfile |
|
1097 | self.shell.logfile = old_logfile | |
1103 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1104 | else: |
|
1099 | else: | |
1105 | # log input history up to this point, optionally interleaving |
|
1100 | # log input history up to this point, optionally interleaving | |
1106 | # output if requested |
|
1101 | # output if requested | |
1107 |
|
1102 | |||
1108 | if timestamp: |
|
1103 | if timestamp: | |
1109 | # disable timestamping for the previous history, since we've |
|
1104 | # disable timestamping for the previous history, since we've | |
1110 | # lost those already (no time machine here). |
|
1105 | # lost those already (no time machine here). | |
1111 | logger.timestamp = False |
|
1106 | logger.timestamp = False | |
1112 |
|
1107 | |||
1113 | if log_raw_input: |
|
1108 | if log_raw_input: | |
1114 | input_hist = self.shell.input_hist_raw |
|
1109 | input_hist = self.shell.input_hist_raw | |
1115 | else: |
|
1110 | else: | |
1116 | input_hist = self.shell.input_hist |
|
1111 | input_hist = self.shell.input_hist | |
1117 |
|
1112 | |||
1118 | if log_output: |
|
1113 | if log_output: | |
1119 | log_write = logger.log_write |
|
1114 | log_write = logger.log_write | |
1120 | output_hist = self.shell.output_hist |
|
1115 | output_hist = self.shell.output_hist | |
1121 | for n in range(1,len(input_hist)-1): |
|
1116 | for n in range(1,len(input_hist)-1): | |
1122 | log_write(input_hist[n].rstrip()) |
|
1117 | log_write(input_hist[n].rstrip()) | |
1123 | if n in output_hist: |
|
1118 | if n in output_hist: | |
1124 | log_write(repr(output_hist[n]),'output') |
|
1119 | log_write(repr(output_hist[n]),'output') | |
1125 | else: |
|
1120 | else: | |
1126 | logger.log_write(input_hist[1:]) |
|
1121 | logger.log_write(input_hist[1:]) | |
1127 | if timestamp: |
|
1122 | if timestamp: | |
1128 | # re-enable timestamping |
|
1123 | # re-enable timestamping | |
1129 | logger.timestamp = True |
|
1124 | logger.timestamp = True | |
1130 |
|
1125 | |||
1131 | print ('Activating auto-logging. ' |
|
1126 | print ('Activating auto-logging. ' | |
1132 | 'Current session state plus future input saved.') |
|
1127 | 'Current session state plus future input saved.') | |
1133 | logger.logstate() |
|
1128 | logger.logstate() | |
1134 |
|
1129 | |||
1135 | def magic_logstop(self,parameter_s=''): |
|
1130 | def magic_logstop(self,parameter_s=''): | |
1136 | """Fully stop logging and close log file. |
|
1131 | """Fully stop logging and close log file. | |
1137 |
|
1132 | |||
1138 | In order to start logging again, a new %logstart call needs to be made, |
|
1133 | In order to start logging again, a new %logstart call needs to be made, | |
1139 | possibly (though not necessarily) with a new filename, mode and other |
|
1134 | possibly (though not necessarily) with a new filename, mode and other | |
1140 | options.""" |
|
1135 | options.""" | |
1141 | self.logger.logstop() |
|
1136 | self.logger.logstop() | |
1142 |
|
1137 | |||
1143 | def magic_logoff(self,parameter_s=''): |
|
1138 | def magic_logoff(self,parameter_s=''): | |
1144 | """Temporarily stop logging. |
|
1139 | """Temporarily stop logging. | |
1145 |
|
1140 | |||
1146 | You must have previously started logging.""" |
|
1141 | You must have previously started logging.""" | |
1147 | self.shell.logger.switch_log(0) |
|
1142 | self.shell.logger.switch_log(0) | |
1148 |
|
1143 | |||
1149 | def magic_logon(self,parameter_s=''): |
|
1144 | def magic_logon(self,parameter_s=''): | |
1150 | """Restart logging. |
|
1145 | """Restart logging. | |
1151 |
|
1146 | |||
1152 | This function is for restarting logging which you've temporarily |
|
1147 | This function is for restarting logging which you've temporarily | |
1153 | stopped with %logoff. For starting logging for the first time, you |
|
1148 | stopped with %logoff. For starting logging for the first time, you | |
1154 | must use the %logstart function, which allows you to specify an |
|
1149 | must use the %logstart function, which allows you to specify an | |
1155 | optional log filename.""" |
|
1150 | optional log filename.""" | |
1156 |
|
1151 | |||
1157 | self.shell.logger.switch_log(1) |
|
1152 | self.shell.logger.switch_log(1) | |
1158 |
|
1153 | |||
1159 | def magic_logstate(self,parameter_s=''): |
|
1154 | def magic_logstate(self,parameter_s=''): | |
1160 | """Print the status of the logging system.""" |
|
1155 | """Print the status of the logging system.""" | |
1161 |
|
1156 | |||
1162 | self.shell.logger.logstate() |
|
1157 | self.shell.logger.logstate() | |
1163 |
|
1158 | |||
1164 | def magic_pdb(self, parameter_s=''): |
|
1159 | def magic_pdb(self, parameter_s=''): | |
1165 | """Control the automatic calling of the pdb interactive debugger. |
|
1160 | """Control the automatic calling of the pdb interactive debugger. | |
1166 |
|
1161 | |||
1167 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1162 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1168 | argument it works as a toggle. |
|
1163 | argument it works as a toggle. | |
1169 |
|
1164 | |||
1170 | When an exception is triggered, IPython can optionally call the |
|
1165 | When an exception is triggered, IPython can optionally call the | |
1171 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1166 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1172 | this feature on and off. |
|
1167 | this feature on and off. | |
1173 |
|
1168 | |||
1174 | The initial state of this feature is set in your ipythonrc |
|
1169 | The initial state of this feature is set in your ipythonrc | |
1175 | configuration file (the variable is called 'pdb'). |
|
1170 | configuration file (the variable is called 'pdb'). | |
1176 |
|
1171 | |||
1177 | If you want to just activate the debugger AFTER an exception has fired, |
|
1172 | If you want to just activate the debugger AFTER an exception has fired, | |
1178 | without having to type '%pdb on' and rerunning your code, you can use |
|
1173 | without having to type '%pdb on' and rerunning your code, you can use | |
1179 | the %debug magic.""" |
|
1174 | the %debug magic.""" | |
1180 |
|
1175 | |||
1181 | par = parameter_s.strip().lower() |
|
1176 | par = parameter_s.strip().lower() | |
1182 |
|
1177 | |||
1183 | if par: |
|
1178 | if par: | |
1184 | try: |
|
1179 | try: | |
1185 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1180 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1186 | except KeyError: |
|
1181 | except KeyError: | |
1187 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1182 | print ('Incorrect argument. Use on/1, off/0, ' | |
1188 | 'or nothing for a toggle.') |
|
1183 | 'or nothing for a toggle.') | |
1189 | return |
|
1184 | return | |
1190 | else: |
|
1185 | else: | |
1191 | # toggle |
|
1186 | # toggle | |
1192 | new_pdb = not self.shell.call_pdb |
|
1187 | new_pdb = not self.shell.call_pdb | |
1193 |
|
1188 | |||
1194 | # set on the shell |
|
1189 | # set on the shell | |
1195 | self.shell.call_pdb = new_pdb |
|
1190 | self.shell.call_pdb = new_pdb | |
1196 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1191 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1197 |
|
1192 | |||
1198 | def magic_debug(self, parameter_s=''): |
|
1193 | def magic_debug(self, parameter_s=''): | |
1199 | """Activate the interactive debugger in post-mortem mode. |
|
1194 | """Activate the interactive debugger in post-mortem mode. | |
1200 |
|
1195 | |||
1201 | If an exception has just occurred, this lets you inspect its stack |
|
1196 | If an exception has just occurred, this lets you inspect its stack | |
1202 | frames interactively. Note that this will always work only on the last |
|
1197 | frames interactively. Note that this will always work only on the last | |
1203 | traceback that occurred, so you must call this quickly after an |
|
1198 | traceback that occurred, so you must call this quickly after an | |
1204 | exception that you wish to inspect has fired, because if another one |
|
1199 | exception that you wish to inspect has fired, because if another one | |
1205 | occurs, it clobbers the previous one. |
|
1200 | occurs, it clobbers the previous one. | |
1206 |
|
1201 | |||
1207 | If you want IPython to automatically do this on every exception, see |
|
1202 | If you want IPython to automatically do this on every exception, see | |
1208 | the %pdb magic for more details. |
|
1203 | the %pdb magic for more details. | |
1209 | """ |
|
1204 | """ | |
1210 | self.shell.debugger(force=True) |
|
1205 | self.shell.debugger(force=True) | |
1211 |
|
1206 | |||
1212 | @testdec.skip_doctest |
|
1207 | @testdec.skip_doctest | |
1213 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1208 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1214 | opts=None,arg_lst=None,prog_ns=None): |
|
1209 | opts=None,arg_lst=None,prog_ns=None): | |
1215 |
|
1210 | |||
1216 | """Run a statement through the python code profiler. |
|
1211 | """Run a statement through the python code profiler. | |
1217 |
|
1212 | |||
1218 | Usage: |
|
1213 | Usage: | |
1219 | %prun [options] statement |
|
1214 | %prun [options] statement | |
1220 |
|
1215 | |||
1221 | The given statement (which doesn't require quote marks) is run via the |
|
1216 | The given statement (which doesn't require quote marks) is run via the | |
1222 | python profiler in a manner similar to the profile.run() function. |
|
1217 | python profiler in a manner similar to the profile.run() function. | |
1223 | Namespaces are internally managed to work correctly; profile.run |
|
1218 | Namespaces are internally managed to work correctly; profile.run | |
1224 | cannot be used in IPython because it makes certain assumptions about |
|
1219 | cannot be used in IPython because it makes certain assumptions about | |
1225 | namespaces which do not hold under IPython. |
|
1220 | namespaces which do not hold under IPython. | |
1226 |
|
1221 | |||
1227 | Options: |
|
1222 | Options: | |
1228 |
|
1223 | |||
1229 | -l <limit>: you can place restrictions on what or how much of the |
|
1224 | -l <limit>: you can place restrictions on what or how much of the | |
1230 | profile gets printed. The limit value can be: |
|
1225 | profile gets printed. The limit value can be: | |
1231 |
|
1226 | |||
1232 | * A string: only information for function names containing this string |
|
1227 | * A string: only information for function names containing this string | |
1233 | is printed. |
|
1228 | is printed. | |
1234 |
|
1229 | |||
1235 | * An integer: only these many lines are printed. |
|
1230 | * An integer: only these many lines are printed. | |
1236 |
|
1231 | |||
1237 | * A float (between 0 and 1): this fraction of the report is printed |
|
1232 | * A float (between 0 and 1): this fraction of the report is printed | |
1238 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1233 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1239 |
|
1234 | |||
1240 | You can combine several limits with repeated use of the option. For |
|
1235 | You can combine several limits with repeated use of the option. For | |
1241 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1236 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1242 | information about class constructors. |
|
1237 | information about class constructors. | |
1243 |
|
1238 | |||
1244 | -r: return the pstats.Stats object generated by the profiling. This |
|
1239 | -r: return the pstats.Stats object generated by the profiling. This | |
1245 | object has all the information about the profile in it, and you can |
|
1240 | object has all the information about the profile in it, and you can | |
1246 | later use it for further analysis or in other functions. |
|
1241 | later use it for further analysis or in other functions. | |
1247 |
|
1242 | |||
1248 | -s <key>: sort profile by given key. You can provide more than one key |
|
1243 | -s <key>: sort profile by given key. You can provide more than one key | |
1249 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1244 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1250 | default sorting key is 'time'. |
|
1245 | default sorting key is 'time'. | |
1251 |
|
1246 | |||
1252 | The following is copied verbatim from the profile documentation |
|
1247 | The following is copied verbatim from the profile documentation | |
1253 | referenced below: |
|
1248 | referenced below: | |
1254 |
|
1249 | |||
1255 | When more than one key is provided, additional keys are used as |
|
1250 | When more than one key is provided, additional keys are used as | |
1256 | secondary criteria when the there is equality in all keys selected |
|
1251 | secondary criteria when the there is equality in all keys selected | |
1257 | before them. |
|
1252 | before them. | |
1258 |
|
1253 | |||
1259 | Abbreviations can be used for any key names, as long as the |
|
1254 | Abbreviations can be used for any key names, as long as the | |
1260 | abbreviation is unambiguous. The following are the keys currently |
|
1255 | abbreviation is unambiguous. The following are the keys currently | |
1261 | defined: |
|
1256 | defined: | |
1262 |
|
1257 | |||
1263 | Valid Arg Meaning |
|
1258 | Valid Arg Meaning | |
1264 | "calls" call count |
|
1259 | "calls" call count | |
1265 | "cumulative" cumulative time |
|
1260 | "cumulative" cumulative time | |
1266 | "file" file name |
|
1261 | "file" file name | |
1267 | "module" file name |
|
1262 | "module" file name | |
1268 | "pcalls" primitive call count |
|
1263 | "pcalls" primitive call count | |
1269 | "line" line number |
|
1264 | "line" line number | |
1270 | "name" function name |
|
1265 | "name" function name | |
1271 | "nfl" name/file/line |
|
1266 | "nfl" name/file/line | |
1272 | "stdname" standard name |
|
1267 | "stdname" standard name | |
1273 | "time" internal time |
|
1268 | "time" internal time | |
1274 |
|
1269 | |||
1275 | Note that all sorts on statistics are in descending order (placing |
|
1270 | Note that all sorts on statistics are in descending order (placing | |
1276 | most time consuming items first), where as name, file, and line number |
|
1271 | most time consuming items first), where as name, file, and line number | |
1277 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1272 | searches are in ascending order (i.e., alphabetical). The subtle | |
1278 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1273 | distinction between "nfl" and "stdname" is that the standard name is a | |
1279 | sort of the name as printed, which means that the embedded line |
|
1274 | sort of the name as printed, which means that the embedded line | |
1280 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1275 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1281 | would (if the file names were the same) appear in the string order |
|
1276 | would (if the file names were the same) appear in the string order | |
1282 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1277 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1283 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1278 | line numbers. In fact, sort_stats("nfl") is the same as | |
1284 | sort_stats("name", "file", "line"). |
|
1279 | sort_stats("name", "file", "line"). | |
1285 |
|
1280 | |||
1286 | -T <filename>: save profile results as shown on screen to a text |
|
1281 | -T <filename>: save profile results as shown on screen to a text | |
1287 | file. The profile is still shown on screen. |
|
1282 | file. The profile is still shown on screen. | |
1288 |
|
1283 | |||
1289 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1284 | -D <filename>: save (via dump_stats) profile statistics to given | |
1290 | filename. This data is in a format understod by the pstats module, and |
|
1285 | filename. This data is in a format understod by the pstats module, and | |
1291 | is generated by a call to the dump_stats() method of profile |
|
1286 | is generated by a call to the dump_stats() method of profile | |
1292 | objects. The profile is still shown on screen. |
|
1287 | objects. The profile is still shown on screen. | |
1293 |
|
1288 | |||
1294 | If you want to run complete programs under the profiler's control, use |
|
1289 | If you want to run complete programs under the profiler's control, use | |
1295 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1290 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1296 | contains profiler specific options as described here. |
|
1291 | contains profiler specific options as described here. | |
1297 |
|
1292 | |||
1298 | You can read the complete documentation for the profile module with:: |
|
1293 | You can read the complete documentation for the profile module with:: | |
1299 |
|
1294 | |||
1300 | In [1]: import profile; profile.help() |
|
1295 | In [1]: import profile; profile.help() | |
1301 | """ |
|
1296 | """ | |
1302 |
|
1297 | |||
1303 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1298 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1304 | # protect user quote marks |
|
1299 | # protect user quote marks | |
1305 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1300 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1306 |
|
1301 | |||
1307 | if user_mode: # regular user call |
|
1302 | if user_mode: # regular user call | |
1308 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1303 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1309 | list_all=1) |
|
1304 | list_all=1) | |
1310 | namespace = self.shell.user_ns |
|
1305 | namespace = self.shell.user_ns | |
1311 | else: # called to run a program by %run -p |
|
1306 | else: # called to run a program by %run -p | |
1312 | try: |
|
1307 | try: | |
1313 | filename = get_py_filename(arg_lst[0]) |
|
1308 | filename = get_py_filename(arg_lst[0]) | |
1314 | except IOError,msg: |
|
1309 | except IOError,msg: | |
1315 | error(msg) |
|
1310 | error(msg) | |
1316 | return |
|
1311 | return | |
1317 |
|
1312 | |||
1318 | arg_str = 'execfile(filename,prog_ns)' |
|
1313 | arg_str = 'execfile(filename,prog_ns)' | |
1319 | namespace = locals() |
|
1314 | namespace = locals() | |
1320 |
|
1315 | |||
1321 | opts.merge(opts_def) |
|
1316 | opts.merge(opts_def) | |
1322 |
|
1317 | |||
1323 | prof = profile.Profile() |
|
1318 | prof = profile.Profile() | |
1324 | try: |
|
1319 | try: | |
1325 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1320 | prof = prof.runctx(arg_str,namespace,namespace) | |
1326 | sys_exit = '' |
|
1321 | sys_exit = '' | |
1327 | except SystemExit: |
|
1322 | except SystemExit: | |
1328 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1323 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1329 |
|
1324 | |||
1330 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1325 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1331 |
|
1326 | |||
1332 | lims = opts.l |
|
1327 | lims = opts.l | |
1333 | if lims: |
|
1328 | if lims: | |
1334 | lims = [] # rebuild lims with ints/floats/strings |
|
1329 | lims = [] # rebuild lims with ints/floats/strings | |
1335 | for lim in opts.l: |
|
1330 | for lim in opts.l: | |
1336 | try: |
|
1331 | try: | |
1337 | lims.append(int(lim)) |
|
1332 | lims.append(int(lim)) | |
1338 | except ValueError: |
|
1333 | except ValueError: | |
1339 | try: |
|
1334 | try: | |
1340 | lims.append(float(lim)) |
|
1335 | lims.append(float(lim)) | |
1341 | except ValueError: |
|
1336 | except ValueError: | |
1342 | lims.append(lim) |
|
1337 | lims.append(lim) | |
1343 |
|
1338 | |||
1344 | # Trap output. |
|
1339 | # Trap output. | |
1345 | stdout_trap = StringIO() |
|
1340 | stdout_trap = StringIO() | |
1346 |
|
1341 | |||
1347 | if hasattr(stats,'stream'): |
|
1342 | if hasattr(stats,'stream'): | |
1348 | # In newer versions of python, the stats object has a 'stream' |
|
1343 | # In newer versions of python, the stats object has a 'stream' | |
1349 | # attribute to write into. |
|
1344 | # attribute to write into. | |
1350 | stats.stream = stdout_trap |
|
1345 | stats.stream = stdout_trap | |
1351 | stats.print_stats(*lims) |
|
1346 | stats.print_stats(*lims) | |
1352 | else: |
|
1347 | else: | |
1353 | # For older versions, we manually redirect stdout during printing |
|
1348 | # For older versions, we manually redirect stdout during printing | |
1354 | sys_stdout = sys.stdout |
|
1349 | sys_stdout = sys.stdout | |
1355 | try: |
|
1350 | try: | |
1356 | sys.stdout = stdout_trap |
|
1351 | sys.stdout = stdout_trap | |
1357 | stats.print_stats(*lims) |
|
1352 | stats.print_stats(*lims) | |
1358 | finally: |
|
1353 | finally: | |
1359 | sys.stdout = sys_stdout |
|
1354 | sys.stdout = sys_stdout | |
1360 |
|
1355 | |||
1361 | output = stdout_trap.getvalue() |
|
1356 | output = stdout_trap.getvalue() | |
1362 | output = output.rstrip() |
|
1357 | output = output.rstrip() | |
1363 |
|
1358 | |||
1364 | page.page(output) |
|
1359 | page.page(output) | |
1365 | print sys_exit, |
|
1360 | print sys_exit, | |
1366 |
|
1361 | |||
1367 | dump_file = opts.D[0] |
|
1362 | dump_file = opts.D[0] | |
1368 | text_file = opts.T[0] |
|
1363 | text_file = opts.T[0] | |
1369 | if dump_file: |
|
1364 | if dump_file: | |
1370 | prof.dump_stats(dump_file) |
|
1365 | prof.dump_stats(dump_file) | |
1371 | print '\n*** Profile stats marshalled to file',\ |
|
1366 | print '\n*** Profile stats marshalled to file',\ | |
1372 | `dump_file`+'.',sys_exit |
|
1367 | `dump_file`+'.',sys_exit | |
1373 | if text_file: |
|
1368 | if text_file: | |
1374 | pfile = file(text_file,'w') |
|
1369 | pfile = file(text_file,'w') | |
1375 | pfile.write(output) |
|
1370 | pfile.write(output) | |
1376 | pfile.close() |
|
1371 | pfile.close() | |
1377 | print '\n*** Profile printout saved to text file',\ |
|
1372 | print '\n*** Profile printout saved to text file',\ | |
1378 | `text_file`+'.',sys_exit |
|
1373 | `text_file`+'.',sys_exit | |
1379 |
|
1374 | |||
1380 | if opts.has_key('r'): |
|
1375 | if opts.has_key('r'): | |
1381 | return stats |
|
1376 | return stats | |
1382 | else: |
|
1377 | else: | |
1383 | return None |
|
1378 | return None | |
1384 |
|
1379 | |||
1385 | @testdec.skip_doctest |
|
1380 | @testdec.skip_doctest | |
1386 | def magic_run(self, parameter_s ='',runner=None, |
|
1381 | def magic_run(self, parameter_s ='',runner=None, | |
1387 | file_finder=get_py_filename): |
|
1382 | file_finder=get_py_filename): | |
1388 | """Run the named file inside IPython as a program. |
|
1383 | """Run the named file inside IPython as a program. | |
1389 |
|
1384 | |||
1390 | Usage:\\ |
|
1385 | Usage:\\ | |
1391 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1386 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1392 |
|
1387 | |||
1393 | Parameters after the filename are passed as command-line arguments to |
|
1388 | Parameters after the filename are passed as command-line arguments to | |
1394 | the program (put in sys.argv). Then, control returns to IPython's |
|
1389 | the program (put in sys.argv). Then, control returns to IPython's | |
1395 | prompt. |
|
1390 | prompt. | |
1396 |
|
1391 | |||
1397 | This is similar to running at a system prompt:\\ |
|
1392 | This is similar to running at a system prompt:\\ | |
1398 | $ python file args\\ |
|
1393 | $ python file args\\ | |
1399 | but with the advantage of giving you IPython's tracebacks, and of |
|
1394 | but with the advantage of giving you IPython's tracebacks, and of | |
1400 | loading all variables into your interactive namespace for further use |
|
1395 | loading all variables into your interactive namespace for further use | |
1401 | (unless -p is used, see below). |
|
1396 | (unless -p is used, see below). | |
1402 |
|
1397 | |||
1403 | The file is executed in a namespace initially consisting only of |
|
1398 | The file is executed in a namespace initially consisting only of | |
1404 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1399 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1405 | sees its environment as if it were being run as a stand-alone program |
|
1400 | sees its environment as if it were being run as a stand-alone program | |
1406 | (except for sharing global objects such as previously imported |
|
1401 | (except for sharing global objects such as previously imported | |
1407 | modules). But after execution, the IPython interactive namespace gets |
|
1402 | modules). But after execution, the IPython interactive namespace gets | |
1408 | updated with all variables defined in the program (except for __name__ |
|
1403 | updated with all variables defined in the program (except for __name__ | |
1409 | and sys.argv). This allows for very convenient loading of code for |
|
1404 | and sys.argv). This allows for very convenient loading of code for | |
1410 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1405 | interactive work, while giving each program a 'clean sheet' to run in. | |
1411 |
|
1406 | |||
1412 | Options: |
|
1407 | Options: | |
1413 |
|
1408 | |||
1414 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1409 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1415 | without extension (as python does under import). This allows running |
|
1410 | without extension (as python does under import). This allows running | |
1416 | scripts and reloading the definitions in them without calling code |
|
1411 | scripts and reloading the definitions in them without calling code | |
1417 | protected by an ' if __name__ == "__main__" ' clause. |
|
1412 | protected by an ' if __name__ == "__main__" ' clause. | |
1418 |
|
1413 | |||
1419 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1414 | -i: run the file in IPython's namespace instead of an empty one. This | |
1420 | is useful if you are experimenting with code written in a text editor |
|
1415 | is useful if you are experimenting with code written in a text editor | |
1421 | which depends on variables defined interactively. |
|
1416 | which depends on variables defined interactively. | |
1422 |
|
1417 | |||
1423 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1418 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1424 | being run. This is particularly useful if IPython is being used to |
|
1419 | being run. This is particularly useful if IPython is being used to | |
1425 | run unittests, which always exit with a sys.exit() call. In such |
|
1420 | run unittests, which always exit with a sys.exit() call. In such | |
1426 | cases you are interested in the output of the test results, not in |
|
1421 | cases you are interested in the output of the test results, not in | |
1427 | seeing a traceback of the unittest module. |
|
1422 | seeing a traceback of the unittest module. | |
1428 |
|
1423 | |||
1429 | -t: print timing information at the end of the run. IPython will give |
|
1424 | -t: print timing information at the end of the run. IPython will give | |
1430 | you an estimated CPU time consumption for your script, which under |
|
1425 | you an estimated CPU time consumption for your script, which under | |
1431 | Unix uses the resource module to avoid the wraparound problems of |
|
1426 | Unix uses the resource module to avoid the wraparound problems of | |
1432 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1427 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1433 | is also given (for Windows platforms this is reported as 0.0). |
|
1428 | is also given (for Windows platforms this is reported as 0.0). | |
1434 |
|
1429 | |||
1435 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1430 | If -t is given, an additional -N<N> option can be given, where <N> | |
1436 | must be an integer indicating how many times you want the script to |
|
1431 | must be an integer indicating how many times you want the script to | |
1437 | run. The final timing report will include total and per run results. |
|
1432 | run. The final timing report will include total and per run results. | |
1438 |
|
1433 | |||
1439 | For example (testing the script uniq_stable.py): |
|
1434 | For example (testing the script uniq_stable.py): | |
1440 |
|
1435 | |||
1441 | In [1]: run -t uniq_stable |
|
1436 | In [1]: run -t uniq_stable | |
1442 |
|
1437 | |||
1443 | IPython CPU timings (estimated):\\ |
|
1438 | IPython CPU timings (estimated):\\ | |
1444 | User : 0.19597 s.\\ |
|
1439 | User : 0.19597 s.\\ | |
1445 | System: 0.0 s.\\ |
|
1440 | System: 0.0 s.\\ | |
1446 |
|
1441 | |||
1447 | In [2]: run -t -N5 uniq_stable |
|
1442 | In [2]: run -t -N5 uniq_stable | |
1448 |
|
1443 | |||
1449 | IPython CPU timings (estimated):\\ |
|
1444 | IPython CPU timings (estimated):\\ | |
1450 | Total runs performed: 5\\ |
|
1445 | Total runs performed: 5\\ | |
1451 | Times : Total Per run\\ |
|
1446 | Times : Total Per run\\ | |
1452 | User : 0.910862 s, 0.1821724 s.\\ |
|
1447 | User : 0.910862 s, 0.1821724 s.\\ | |
1453 | System: 0.0 s, 0.0 s. |
|
1448 | System: 0.0 s, 0.0 s. | |
1454 |
|
1449 | |||
1455 | -d: run your program under the control of pdb, the Python debugger. |
|
1450 | -d: run your program under the control of pdb, the Python debugger. | |
1456 | This allows you to execute your program step by step, watch variables, |
|
1451 | This allows you to execute your program step by step, watch variables, | |
1457 | etc. Internally, what IPython does is similar to calling: |
|
1452 | etc. Internally, what IPython does is similar to calling: | |
1458 |
|
1453 | |||
1459 | pdb.run('execfile("YOURFILENAME")') |
|
1454 | pdb.run('execfile("YOURFILENAME")') | |
1460 |
|
1455 | |||
1461 | with a breakpoint set on line 1 of your file. You can change the line |
|
1456 | with a breakpoint set on line 1 of your file. You can change the line | |
1462 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1457 | number for this automatic breakpoint to be <N> by using the -bN option | |
1463 | (where N must be an integer). For example: |
|
1458 | (where N must be an integer). For example: | |
1464 |
|
1459 | |||
1465 | %run -d -b40 myscript |
|
1460 | %run -d -b40 myscript | |
1466 |
|
1461 | |||
1467 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1462 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1468 | the first breakpoint must be set on a line which actually does |
|
1463 | the first breakpoint must be set on a line which actually does | |
1469 | something (not a comment or docstring) for it to stop execution. |
|
1464 | something (not a comment or docstring) for it to stop execution. | |
1470 |
|
1465 | |||
1471 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1466 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1472 | first enter 'c' (without qoutes) to start execution up to the first |
|
1467 | first enter 'c' (without qoutes) to start execution up to the first | |
1473 | breakpoint. |
|
1468 | breakpoint. | |
1474 |
|
1469 | |||
1475 | Entering 'help' gives information about the use of the debugger. You |
|
1470 | Entering 'help' gives information about the use of the debugger. You | |
1476 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1471 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1477 | at a prompt. |
|
1472 | at a prompt. | |
1478 |
|
1473 | |||
1479 | -p: run program under the control of the Python profiler module (which |
|
1474 | -p: run program under the control of the Python profiler module (which | |
1480 | prints a detailed report of execution times, function calls, etc). |
|
1475 | prints a detailed report of execution times, function calls, etc). | |
1481 |
|
1476 | |||
1482 | You can pass other options after -p which affect the behavior of the |
|
1477 | You can pass other options after -p which affect the behavior of the | |
1483 | profiler itself. See the docs for %prun for details. |
|
1478 | profiler itself. See the docs for %prun for details. | |
1484 |
|
1479 | |||
1485 | In this mode, the program's variables do NOT propagate back to the |
|
1480 | In this mode, the program's variables do NOT propagate back to the | |
1486 | IPython interactive namespace (because they remain in the namespace |
|
1481 | IPython interactive namespace (because they remain in the namespace | |
1487 | where the profiler executes them). |
|
1482 | where the profiler executes them). | |
1488 |
|
1483 | |||
1489 | Internally this triggers a call to %prun, see its documentation for |
|
1484 | Internally this triggers a call to %prun, see its documentation for | |
1490 | details on the options available specifically for profiling. |
|
1485 | details on the options available specifically for profiling. | |
1491 |
|
1486 | |||
1492 | There is one special usage for which the text above doesn't apply: |
|
1487 | There is one special usage for which the text above doesn't apply: | |
1493 | if the filename ends with .ipy, the file is run as ipython script, |
|
1488 | if the filename ends with .ipy, the file is run as ipython script, | |
1494 | just as if the commands were written on IPython prompt. |
|
1489 | just as if the commands were written on IPython prompt. | |
1495 | """ |
|
1490 | """ | |
1496 |
|
1491 | |||
1497 | # get arguments and set sys.argv for program to be run. |
|
1492 | # get arguments and set sys.argv for program to be run. | |
1498 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1493 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1499 | mode='list',list_all=1) |
|
1494 | mode='list',list_all=1) | |
1500 |
|
1495 | |||
1501 | try: |
|
1496 | try: | |
1502 | filename = file_finder(arg_lst[0]) |
|
1497 | filename = file_finder(arg_lst[0]) | |
1503 | except IndexError: |
|
1498 | except IndexError: | |
1504 | warn('you must provide at least a filename.') |
|
1499 | warn('you must provide at least a filename.') | |
1505 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1500 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1506 | return |
|
1501 | return | |
1507 | except IOError,msg: |
|
1502 | except IOError,msg: | |
1508 | error(msg) |
|
1503 | error(msg) | |
1509 | return |
|
1504 | return | |
1510 |
|
1505 | |||
1511 | if filename.lower().endswith('.ipy'): |
|
1506 | if filename.lower().endswith('.ipy'): | |
1512 | self.shell.safe_execfile_ipy(filename) |
|
1507 | self.shell.safe_execfile_ipy(filename) | |
1513 | return |
|
1508 | return | |
1514 |
|
1509 | |||
1515 | # Control the response to exit() calls made by the script being run |
|
1510 | # Control the response to exit() calls made by the script being run | |
1516 | exit_ignore = opts.has_key('e') |
|
1511 | exit_ignore = opts.has_key('e') | |
1517 |
|
1512 | |||
1518 | # Make sure that the running script gets a proper sys.argv as if it |
|
1513 | # Make sure that the running script gets a proper sys.argv as if it | |
1519 | # were run from a system shell. |
|
1514 | # were run from a system shell. | |
1520 | save_argv = sys.argv # save it for later restoring |
|
1515 | save_argv = sys.argv # save it for later restoring | |
1521 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1516 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1522 |
|
1517 | |||
1523 | if opts.has_key('i'): |
|
1518 | if opts.has_key('i'): | |
1524 | # Run in user's interactive namespace |
|
1519 | # Run in user's interactive namespace | |
1525 | prog_ns = self.shell.user_ns |
|
1520 | prog_ns = self.shell.user_ns | |
1526 | __name__save = self.shell.user_ns['__name__'] |
|
1521 | __name__save = self.shell.user_ns['__name__'] | |
1527 | prog_ns['__name__'] = '__main__' |
|
1522 | prog_ns['__name__'] = '__main__' | |
1528 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1523 | main_mod = self.shell.new_main_mod(prog_ns) | |
1529 | else: |
|
1524 | else: | |
1530 | # Run in a fresh, empty namespace |
|
1525 | # Run in a fresh, empty namespace | |
1531 | if opts.has_key('n'): |
|
1526 | if opts.has_key('n'): | |
1532 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1527 | name = os.path.splitext(os.path.basename(filename))[0] | |
1533 | else: |
|
1528 | else: | |
1534 | name = '__main__' |
|
1529 | name = '__main__' | |
1535 |
|
1530 | |||
1536 | main_mod = self.shell.new_main_mod() |
|
1531 | main_mod = self.shell.new_main_mod() | |
1537 | prog_ns = main_mod.__dict__ |
|
1532 | prog_ns = main_mod.__dict__ | |
1538 | prog_ns['__name__'] = name |
|
1533 | prog_ns['__name__'] = name | |
1539 |
|
1534 | |||
1540 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1535 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1541 | # set the __file__ global in the script's namespace |
|
1536 | # set the __file__ global in the script's namespace | |
1542 | prog_ns['__file__'] = filename |
|
1537 | prog_ns['__file__'] = filename | |
1543 |
|
1538 | |||
1544 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1539 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1545 | # that, if we overwrite __main__, we replace it at the end |
|
1540 | # that, if we overwrite __main__, we replace it at the end | |
1546 | main_mod_name = prog_ns['__name__'] |
|
1541 | main_mod_name = prog_ns['__name__'] | |
1547 |
|
1542 | |||
1548 | if main_mod_name == '__main__': |
|
1543 | if main_mod_name == '__main__': | |
1549 | restore_main = sys.modules['__main__'] |
|
1544 | restore_main = sys.modules['__main__'] | |
1550 | else: |
|
1545 | else: | |
1551 | restore_main = False |
|
1546 | restore_main = False | |
1552 |
|
1547 | |||
1553 | # This needs to be undone at the end to prevent holding references to |
|
1548 | # This needs to be undone at the end to prevent holding references to | |
1554 | # every single object ever created. |
|
1549 | # every single object ever created. | |
1555 | sys.modules[main_mod_name] = main_mod |
|
1550 | sys.modules[main_mod_name] = main_mod | |
1556 |
|
1551 | |||
1557 | stats = None |
|
1552 | stats = None | |
1558 | try: |
|
1553 | try: | |
1559 | self.shell.savehist() |
|
1554 | self.shell.save_hist() | |
1560 |
|
1555 | |||
1561 | if opts.has_key('p'): |
|
1556 | if opts.has_key('p'): | |
1562 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1557 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1563 | else: |
|
1558 | else: | |
1564 | if opts.has_key('d'): |
|
1559 | if opts.has_key('d'): | |
1565 | deb = debugger.Pdb(self.shell.colors) |
|
1560 | deb = debugger.Pdb(self.shell.colors) | |
1566 | # reset Breakpoint state, which is moronically kept |
|
1561 | # reset Breakpoint state, which is moronically kept | |
1567 | # in a class |
|
1562 | # in a class | |
1568 | bdb.Breakpoint.next = 1 |
|
1563 | bdb.Breakpoint.next = 1 | |
1569 | bdb.Breakpoint.bplist = {} |
|
1564 | bdb.Breakpoint.bplist = {} | |
1570 | bdb.Breakpoint.bpbynumber = [None] |
|
1565 | bdb.Breakpoint.bpbynumber = [None] | |
1571 | # Set an initial breakpoint to stop execution |
|
1566 | # Set an initial breakpoint to stop execution | |
1572 | maxtries = 10 |
|
1567 | maxtries = 10 | |
1573 | bp = int(opts.get('b',[1])[0]) |
|
1568 | bp = int(opts.get('b',[1])[0]) | |
1574 | checkline = deb.checkline(filename,bp) |
|
1569 | checkline = deb.checkline(filename,bp) | |
1575 | if not checkline: |
|
1570 | if not checkline: | |
1576 | for bp in range(bp+1,bp+maxtries+1): |
|
1571 | for bp in range(bp+1,bp+maxtries+1): | |
1577 | if deb.checkline(filename,bp): |
|
1572 | if deb.checkline(filename,bp): | |
1578 | break |
|
1573 | break | |
1579 | else: |
|
1574 | else: | |
1580 | msg = ("\nI failed to find a valid line to set " |
|
1575 | msg = ("\nI failed to find a valid line to set " | |
1581 | "a breakpoint\n" |
|
1576 | "a breakpoint\n" | |
1582 | "after trying up to line: %s.\n" |
|
1577 | "after trying up to line: %s.\n" | |
1583 | "Please set a valid breakpoint manually " |
|
1578 | "Please set a valid breakpoint manually " | |
1584 | "with the -b option." % bp) |
|
1579 | "with the -b option." % bp) | |
1585 | error(msg) |
|
1580 | error(msg) | |
1586 | return |
|
1581 | return | |
1587 | # if we find a good linenumber, set the breakpoint |
|
1582 | # if we find a good linenumber, set the breakpoint | |
1588 | deb.do_break('%s:%s' % (filename,bp)) |
|
1583 | deb.do_break('%s:%s' % (filename,bp)) | |
1589 | # Start file run |
|
1584 | # Start file run | |
1590 | print "NOTE: Enter 'c' at the", |
|
1585 | print "NOTE: Enter 'c' at the", | |
1591 | print "%s prompt to start your script." % deb.prompt |
|
1586 | print "%s prompt to start your script." % deb.prompt | |
1592 | try: |
|
1587 | try: | |
1593 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1588 | deb.run('execfile("%s")' % filename,prog_ns) | |
1594 |
|
1589 | |||
1595 | except: |
|
1590 | except: | |
1596 | etype, value, tb = sys.exc_info() |
|
1591 | etype, value, tb = sys.exc_info() | |
1597 | # Skip three frames in the traceback: the %run one, |
|
1592 | # Skip three frames in the traceback: the %run one, | |
1598 | # one inside bdb.py, and the command-line typed by the |
|
1593 | # one inside bdb.py, and the command-line typed by the | |
1599 | # user (run by exec in pdb itself). |
|
1594 | # user (run by exec in pdb itself). | |
1600 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1595 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1601 | else: |
|
1596 | else: | |
1602 | if runner is None: |
|
1597 | if runner is None: | |
1603 | runner = self.shell.safe_execfile |
|
1598 | runner = self.shell.safe_execfile | |
1604 | if opts.has_key('t'): |
|
1599 | if opts.has_key('t'): | |
1605 | # timed execution |
|
1600 | # timed execution | |
1606 | try: |
|
1601 | try: | |
1607 | nruns = int(opts['N'][0]) |
|
1602 | nruns = int(opts['N'][0]) | |
1608 | if nruns < 1: |
|
1603 | if nruns < 1: | |
1609 | error('Number of runs must be >=1') |
|
1604 | error('Number of runs must be >=1') | |
1610 | return |
|
1605 | return | |
1611 | except (KeyError): |
|
1606 | except (KeyError): | |
1612 | nruns = 1 |
|
1607 | nruns = 1 | |
1613 | if nruns == 1: |
|
1608 | if nruns == 1: | |
1614 | t0 = clock2() |
|
1609 | t0 = clock2() | |
1615 | runner(filename,prog_ns,prog_ns, |
|
1610 | runner(filename,prog_ns,prog_ns, | |
1616 | exit_ignore=exit_ignore) |
|
1611 | exit_ignore=exit_ignore) | |
1617 | t1 = clock2() |
|
1612 | t1 = clock2() | |
1618 | t_usr = t1[0]-t0[0] |
|
1613 | t_usr = t1[0]-t0[0] | |
1619 | t_sys = t1[1]-t0[1] |
|
1614 | t_sys = t1[1]-t0[1] | |
1620 | print "\nIPython CPU timings (estimated):" |
|
1615 | print "\nIPython CPU timings (estimated):" | |
1621 | print " User : %10s s." % t_usr |
|
1616 | print " User : %10s s." % t_usr | |
1622 | print " System: %10s s." % t_sys |
|
1617 | print " System: %10s s." % t_sys | |
1623 | else: |
|
1618 | else: | |
1624 | runs = range(nruns) |
|
1619 | runs = range(nruns) | |
1625 | t0 = clock2() |
|
1620 | t0 = clock2() | |
1626 | for nr in runs: |
|
1621 | for nr in runs: | |
1627 | runner(filename,prog_ns,prog_ns, |
|
1622 | runner(filename,prog_ns,prog_ns, | |
1628 | exit_ignore=exit_ignore) |
|
1623 | exit_ignore=exit_ignore) | |
1629 | t1 = clock2() |
|
1624 | t1 = clock2() | |
1630 | t_usr = t1[0]-t0[0] |
|
1625 | t_usr = t1[0]-t0[0] | |
1631 | t_sys = t1[1]-t0[1] |
|
1626 | t_sys = t1[1]-t0[1] | |
1632 | print "\nIPython CPU timings (estimated):" |
|
1627 | print "\nIPython CPU timings (estimated):" | |
1633 | print "Total runs performed:",nruns |
|
1628 | print "Total runs performed:",nruns | |
1634 | print " Times : %10s %10s" % ('Total','Per run') |
|
1629 | print " Times : %10s %10s" % ('Total','Per run') | |
1635 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1630 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1636 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1631 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1637 |
|
1632 | |||
1638 | else: |
|
1633 | else: | |
1639 | # regular execution |
|
1634 | # regular execution | |
1640 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1635 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1641 |
|
1636 | |||
1642 | if opts.has_key('i'): |
|
1637 | if opts.has_key('i'): | |
1643 | self.shell.user_ns['__name__'] = __name__save |
|
1638 | self.shell.user_ns['__name__'] = __name__save | |
1644 | else: |
|
1639 | else: | |
1645 | # The shell MUST hold a reference to prog_ns so after %run |
|
1640 | # The shell MUST hold a reference to prog_ns so after %run | |
1646 | # exits, the python deletion mechanism doesn't zero it out |
|
1641 | # exits, the python deletion mechanism doesn't zero it out | |
1647 | # (leaving dangling references). |
|
1642 | # (leaving dangling references). | |
1648 | self.shell.cache_main_mod(prog_ns,filename) |
|
1643 | self.shell.cache_main_mod(prog_ns,filename) | |
1649 | # update IPython interactive namespace |
|
1644 | # update IPython interactive namespace | |
1650 |
|
1645 | |||
1651 | # Some forms of read errors on the file may mean the |
|
1646 | # Some forms of read errors on the file may mean the | |
1652 | # __name__ key was never set; using pop we don't have to |
|
1647 | # __name__ key was never set; using pop we don't have to | |
1653 | # worry about a possible KeyError. |
|
1648 | # worry about a possible KeyError. | |
1654 | prog_ns.pop('__name__', None) |
|
1649 | prog_ns.pop('__name__', None) | |
1655 |
|
1650 | |||
1656 | self.shell.user_ns.update(prog_ns) |
|
1651 | self.shell.user_ns.update(prog_ns) | |
1657 | finally: |
|
1652 | finally: | |
1658 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1653 | # It's a bit of a mystery why, but __builtins__ can change from | |
1659 | # being a module to becoming a dict missing some key data after |
|
1654 | # being a module to becoming a dict missing some key data after | |
1660 | # %run. As best I can see, this is NOT something IPython is doing |
|
1655 | # %run. As best I can see, this is NOT something IPython is doing | |
1661 | # at all, and similar problems have been reported before: |
|
1656 | # at all, and similar problems have been reported before: | |
1662 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1657 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1663 | # Since this seems to be done by the interpreter itself, the best |
|
1658 | # Since this seems to be done by the interpreter itself, the best | |
1664 | # we can do is to at least restore __builtins__ for the user on |
|
1659 | # we can do is to at least restore __builtins__ for the user on | |
1665 | # exit. |
|
1660 | # exit. | |
1666 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1661 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1667 |
|
1662 | |||
1668 | # Ensure key global structures are restored |
|
1663 | # Ensure key global structures are restored | |
1669 | sys.argv = save_argv |
|
1664 | sys.argv = save_argv | |
1670 | if restore_main: |
|
1665 | if restore_main: | |
1671 | sys.modules['__main__'] = restore_main |
|
1666 | sys.modules['__main__'] = restore_main | |
1672 | else: |
|
1667 | else: | |
1673 | # Remove from sys.modules the reference to main_mod we'd |
|
1668 | # Remove from sys.modules the reference to main_mod we'd | |
1674 | # added. Otherwise it will trap references to objects |
|
1669 | # added. Otherwise it will trap references to objects | |
1675 | # contained therein. |
|
1670 | # contained therein. | |
1676 | del sys.modules[main_mod_name] |
|
1671 | del sys.modules[main_mod_name] | |
1677 |
|
1672 | |||
1678 | self.shell.reloadhist() |
|
1673 | self.shell.reload_hist() | |
1679 |
|
1674 | |||
1680 | return stats |
|
1675 | return stats | |
1681 |
|
1676 | |||
1682 | @testdec.skip_doctest |
|
1677 | @testdec.skip_doctest | |
1683 | def magic_timeit(self, parameter_s =''): |
|
1678 | def magic_timeit(self, parameter_s =''): | |
1684 | """Time execution of a Python statement or expression |
|
1679 | """Time execution of a Python statement or expression | |
1685 |
|
1680 | |||
1686 | Usage:\\ |
|
1681 | Usage:\\ | |
1687 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1682 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1688 |
|
1683 | |||
1689 | Time execution of a Python statement or expression using the timeit |
|
1684 | Time execution of a Python statement or expression using the timeit | |
1690 | module. |
|
1685 | module. | |
1691 |
|
1686 | |||
1692 | Options: |
|
1687 | Options: | |
1693 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1688 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1694 | is not given, a fitting value is chosen. |
|
1689 | is not given, a fitting value is chosen. | |
1695 |
|
1690 | |||
1696 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1691 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1697 | Default: 3 |
|
1692 | Default: 3 | |
1698 |
|
1693 | |||
1699 | -t: use time.time to measure the time, which is the default on Unix. |
|
1694 | -t: use time.time to measure the time, which is the default on Unix. | |
1700 | This function measures wall time. |
|
1695 | This function measures wall time. | |
1701 |
|
1696 | |||
1702 | -c: use time.clock to measure the time, which is the default on |
|
1697 | -c: use time.clock to measure the time, which is the default on | |
1703 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1698 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1704 | instead and returns the CPU user time. |
|
1699 | instead and returns the CPU user time. | |
1705 |
|
1700 | |||
1706 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1701 | -p<P>: use a precision of <P> digits to display the timing result. | |
1707 | Default: 3 |
|
1702 | Default: 3 | |
1708 |
|
1703 | |||
1709 |
|
1704 | |||
1710 | Examples: |
|
1705 | Examples: | |
1711 |
|
1706 | |||
1712 | In [1]: %timeit pass |
|
1707 | In [1]: %timeit pass | |
1713 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1708 | 10000000 loops, best of 3: 53.3 ns per loop | |
1714 |
|
1709 | |||
1715 | In [2]: u = None |
|
1710 | In [2]: u = None | |
1716 |
|
1711 | |||
1717 | In [3]: %timeit u is None |
|
1712 | In [3]: %timeit u is None | |
1718 | 10000000 loops, best of 3: 184 ns per loop |
|
1713 | 10000000 loops, best of 3: 184 ns per loop | |
1719 |
|
1714 | |||
1720 | In [4]: %timeit -r 4 u == None |
|
1715 | In [4]: %timeit -r 4 u == None | |
1721 | 1000000 loops, best of 4: 242 ns per loop |
|
1716 | 1000000 loops, best of 4: 242 ns per loop | |
1722 |
|
1717 | |||
1723 | In [5]: import time |
|
1718 | In [5]: import time | |
1724 |
|
1719 | |||
1725 | In [6]: %timeit -n1 time.sleep(2) |
|
1720 | In [6]: %timeit -n1 time.sleep(2) | |
1726 | 1 loops, best of 3: 2 s per loop |
|
1721 | 1 loops, best of 3: 2 s per loop | |
1727 |
|
1722 | |||
1728 |
|
1723 | |||
1729 | The times reported by %timeit will be slightly higher than those |
|
1724 | The times reported by %timeit will be slightly higher than those | |
1730 | reported by the timeit.py script when variables are accessed. This is |
|
1725 | reported by the timeit.py script when variables are accessed. This is | |
1731 | due to the fact that %timeit executes the statement in the namespace |
|
1726 | due to the fact that %timeit executes the statement in the namespace | |
1732 | of the shell, compared with timeit.py, which uses a single setup |
|
1727 | of the shell, compared with timeit.py, which uses a single setup | |
1733 | statement to import function or create variables. Generally, the bias |
|
1728 | statement to import function or create variables. Generally, the bias | |
1734 | does not matter as long as results from timeit.py are not mixed with |
|
1729 | does not matter as long as results from timeit.py are not mixed with | |
1735 | those from %timeit.""" |
|
1730 | those from %timeit.""" | |
1736 |
|
1731 | |||
1737 | import timeit |
|
1732 | import timeit | |
1738 | import math |
|
1733 | import math | |
1739 |
|
1734 | |||
1740 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1735 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1741 | # certain terminals. Until we figure out a robust way of |
|
1736 | # certain terminals. Until we figure out a robust way of | |
1742 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1737 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1743 | # microseconds. I am really NOT happy about disabling the proper |
|
1738 | # microseconds. I am really NOT happy about disabling the proper | |
1744 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1739 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1745 | # right solution for this is, I'm all ears... |
|
1740 | # right solution for this is, I'm all ears... | |
1746 | # |
|
1741 | # | |
1747 | # Note: using |
|
1742 | # Note: using | |
1748 | # |
|
1743 | # | |
1749 | # s = u'\xb5' |
|
1744 | # s = u'\xb5' | |
1750 | # s.encode(sys.getdefaultencoding()) |
|
1745 | # s.encode(sys.getdefaultencoding()) | |
1751 | # |
|
1746 | # | |
1752 | # is not sufficient, as I've seen terminals where that fails but |
|
1747 | # is not sufficient, as I've seen terminals where that fails but | |
1753 | # print s |
|
1748 | # print s | |
1754 | # |
|
1749 | # | |
1755 | # succeeds |
|
1750 | # succeeds | |
1756 | # |
|
1751 | # | |
1757 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1752 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1758 |
|
1753 | |||
1759 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1754 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1760 | units = [u"s", u"ms",u'us',"ns"] |
|
1755 | units = [u"s", u"ms",u'us',"ns"] | |
1761 |
|
1756 | |||
1762 | scaling = [1, 1e3, 1e6, 1e9] |
|
1757 | scaling = [1, 1e3, 1e6, 1e9] | |
1763 |
|
1758 | |||
1764 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1765 | posix=False) |
|
1760 | posix=False) | |
1766 | if stmt == "": |
|
1761 | if stmt == "": | |
1767 | return |
|
1762 | return | |
1768 | timefunc = timeit.default_timer |
|
1763 | timefunc = timeit.default_timer | |
1769 | number = int(getattr(opts, "n", 0)) |
|
1764 | number = int(getattr(opts, "n", 0)) | |
1770 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1771 | precision = int(getattr(opts, "p", 3)) |
|
1766 | precision = int(getattr(opts, "p", 3)) | |
1772 | if hasattr(opts, "t"): |
|
1767 | if hasattr(opts, "t"): | |
1773 | timefunc = time.time |
|
1768 | timefunc = time.time | |
1774 | if hasattr(opts, "c"): |
|
1769 | if hasattr(opts, "c"): | |
1775 | timefunc = clock |
|
1770 | timefunc = clock | |
1776 |
|
1771 | |||
1777 | timer = timeit.Timer(timer=timefunc) |
|
1772 | timer = timeit.Timer(timer=timefunc) | |
1778 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1773 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1779 | # but is there a better way to achieve that the code stmt has access |
|
1774 | # but is there a better way to achieve that the code stmt has access | |
1780 | # to the shell namespace? |
|
1775 | # to the shell namespace? | |
1781 |
|
1776 | |||
1782 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1783 | 'setup': "pass"} |
|
1778 | 'setup': "pass"} | |
1784 | # Track compilation time so it can be reported if too long |
|
1779 | # Track compilation time so it can be reported if too long | |
1785 | # Minimum time above which compilation time will be reported |
|
1780 | # Minimum time above which compilation time will be reported | |
1786 | tc_min = 0.1 |
|
1781 | tc_min = 0.1 | |
1787 |
|
1782 | |||
1788 | t0 = clock() |
|
1783 | t0 = clock() | |
1789 | code = compile(src, "<magic-timeit>", "exec") |
|
1784 | code = compile(src, "<magic-timeit>", "exec") | |
1790 | tc = clock()-t0 |
|
1785 | tc = clock()-t0 | |
1791 |
|
1786 | |||
1792 | ns = {} |
|
1787 | ns = {} | |
1793 | exec code in self.shell.user_ns, ns |
|
1788 | exec code in self.shell.user_ns, ns | |
1794 | timer.inner = ns["inner"] |
|
1789 | timer.inner = ns["inner"] | |
1795 |
|
1790 | |||
1796 | if number == 0: |
|
1791 | if number == 0: | |
1797 | # determine number so that 0.2 <= total time < 2.0 |
|
1792 | # determine number so that 0.2 <= total time < 2.0 | |
1798 | number = 1 |
|
1793 | number = 1 | |
1799 | for i in range(1, 10): |
|
1794 | for i in range(1, 10): | |
1800 | if timer.timeit(number) >= 0.2: |
|
1795 | if timer.timeit(number) >= 0.2: | |
1801 | break |
|
1796 | break | |
1802 | number *= 10 |
|
1797 | number *= 10 | |
1803 |
|
1798 | |||
1804 | best = min(timer.repeat(repeat, number)) / number |
|
1799 | best = min(timer.repeat(repeat, number)) / number | |
1805 |
|
1800 | |||
1806 | if best > 0.0 and best < 1000.0: |
|
1801 | if best > 0.0 and best < 1000.0: | |
1807 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1802 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1808 | elif best >= 1000.0: |
|
1803 | elif best >= 1000.0: | |
1809 | order = 0 |
|
1804 | order = 0 | |
1810 | else: |
|
1805 | else: | |
1811 | order = 3 |
|
1806 | order = 3 | |
1812 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1807 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1813 | precision, |
|
1808 | precision, | |
1814 | best * scaling[order], |
|
1809 | best * scaling[order], | |
1815 | units[order]) |
|
1810 | units[order]) | |
1816 | if tc > tc_min: |
|
1811 | if tc > tc_min: | |
1817 | print "Compiler time: %.2f s" % tc |
|
1812 | print "Compiler time: %.2f s" % tc | |
1818 |
|
1813 | |||
1819 | @testdec.skip_doctest |
|
1814 | @testdec.skip_doctest | |
1820 | def magic_time(self,parameter_s = ''): |
|
1815 | def magic_time(self,parameter_s = ''): | |
1821 | """Time execution of a Python statement or expression. |
|
1816 | """Time execution of a Python statement or expression. | |
1822 |
|
1817 | |||
1823 | The CPU and wall clock times are printed, and the value of the |
|
1818 | The CPU and wall clock times are printed, and the value of the | |
1824 | expression (if any) is returned. Note that under Win32, system time |
|
1819 | expression (if any) is returned. Note that under Win32, system time | |
1825 | is always reported as 0, since it can not be measured. |
|
1820 | is always reported as 0, since it can not be measured. | |
1826 |
|
1821 | |||
1827 | This function provides very basic timing functionality. In Python |
|
1822 | This function provides very basic timing functionality. In Python | |
1828 | 2.3, the timeit module offers more control and sophistication, so this |
|
1823 | 2.3, the timeit module offers more control and sophistication, so this | |
1829 | could be rewritten to use it (patches welcome). |
|
1824 | could be rewritten to use it (patches welcome). | |
1830 |
|
1825 | |||
1831 | Some examples: |
|
1826 | Some examples: | |
1832 |
|
1827 | |||
1833 | In [1]: time 2**128 |
|
1828 | In [1]: time 2**128 | |
1834 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1829 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1835 | Wall time: 0.00 |
|
1830 | Wall time: 0.00 | |
1836 | Out[1]: 340282366920938463463374607431768211456L |
|
1831 | Out[1]: 340282366920938463463374607431768211456L | |
1837 |
|
1832 | |||
1838 | In [2]: n = 1000000 |
|
1833 | In [2]: n = 1000000 | |
1839 |
|
1834 | |||
1840 | In [3]: time sum(range(n)) |
|
1835 | In [3]: time sum(range(n)) | |
1841 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1836 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1842 | Wall time: 1.37 |
|
1837 | Wall time: 1.37 | |
1843 | Out[3]: 499999500000L |
|
1838 | Out[3]: 499999500000L | |
1844 |
|
1839 | |||
1845 | In [4]: time print 'hello world' |
|
1840 | In [4]: time print 'hello world' | |
1846 | hello world |
|
1841 | hello world | |
1847 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1848 | Wall time: 0.00 |
|
1843 | Wall time: 0.00 | |
1849 |
|
1844 | |||
1850 | Note that the time needed by Python to compile the given expression |
|
1845 | Note that the time needed by Python to compile the given expression | |
1851 | will be reported if it is more than 0.1s. In this example, the |
|
1846 | will be reported if it is more than 0.1s. In this example, the | |
1852 | actual exponentiation is done by Python at compilation time, so while |
|
1847 | actual exponentiation is done by Python at compilation time, so while | |
1853 | the expression can take a noticeable amount of time to compute, that |
|
1848 | the expression can take a noticeable amount of time to compute, that | |
1854 | time is purely due to the compilation: |
|
1849 | time is purely due to the compilation: | |
1855 |
|
1850 | |||
1856 | In [5]: time 3**9999; |
|
1851 | In [5]: time 3**9999; | |
1857 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1852 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1858 | Wall time: 0.00 s |
|
1853 | Wall time: 0.00 s | |
1859 |
|
1854 | |||
1860 | In [6]: time 3**999999; |
|
1855 | In [6]: time 3**999999; | |
1861 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1862 | Wall time: 0.00 s |
|
1857 | Wall time: 0.00 s | |
1863 | Compiler : 0.78 s |
|
1858 | Compiler : 0.78 s | |
1864 | """ |
|
1859 | """ | |
1865 |
|
1860 | |||
1866 | # fail immediately if the given expression can't be compiled |
|
1861 | # fail immediately if the given expression can't be compiled | |
1867 |
|
1862 | |||
1868 | expr = self.shell.prefilter(parameter_s,False) |
|
1863 | expr = self.shell.prefilter(parameter_s,False) | |
1869 |
|
1864 | |||
1870 | # Minimum time above which compilation time will be reported |
|
1865 | # Minimum time above which compilation time will be reported | |
1871 | tc_min = 0.1 |
|
1866 | tc_min = 0.1 | |
1872 |
|
1867 | |||
1873 | try: |
|
1868 | try: | |
1874 | mode = 'eval' |
|
1869 | mode = 'eval' | |
1875 | t0 = clock() |
|
1870 | t0 = clock() | |
1876 | code = compile(expr,'<timed eval>',mode) |
|
1871 | code = compile(expr,'<timed eval>',mode) | |
1877 | tc = clock()-t0 |
|
1872 | tc = clock()-t0 | |
1878 | except SyntaxError: |
|
1873 | except SyntaxError: | |
1879 | mode = 'exec' |
|
1874 | mode = 'exec' | |
1880 | t0 = clock() |
|
1875 | t0 = clock() | |
1881 | code = compile(expr,'<timed exec>',mode) |
|
1876 | code = compile(expr,'<timed exec>',mode) | |
1882 | tc = clock()-t0 |
|
1877 | tc = clock()-t0 | |
1883 | # skew measurement as little as possible |
|
1878 | # skew measurement as little as possible | |
1884 | glob = self.shell.user_ns |
|
1879 | glob = self.shell.user_ns | |
1885 | clk = clock2 |
|
1880 | clk = clock2 | |
1886 | wtime = time.time |
|
1881 | wtime = time.time | |
1887 | # time execution |
|
1882 | # time execution | |
1888 | wall_st = wtime() |
|
1883 | wall_st = wtime() | |
1889 | if mode=='eval': |
|
1884 | if mode=='eval': | |
1890 | st = clk() |
|
1885 | st = clk() | |
1891 | out = eval(code,glob) |
|
1886 | out = eval(code,glob) | |
1892 | end = clk() |
|
1887 | end = clk() | |
1893 | else: |
|
1888 | else: | |
1894 | st = clk() |
|
1889 | st = clk() | |
1895 | exec code in glob |
|
1890 | exec code in glob | |
1896 | end = clk() |
|
1891 | end = clk() | |
1897 | out = None |
|
1892 | out = None | |
1898 | wall_end = wtime() |
|
1893 | wall_end = wtime() | |
1899 | # Compute actual times and report |
|
1894 | # Compute actual times and report | |
1900 | wall_time = wall_end-wall_st |
|
1895 | wall_time = wall_end-wall_st | |
1901 | cpu_user = end[0]-st[0] |
|
1896 | cpu_user = end[0]-st[0] | |
1902 | cpu_sys = end[1]-st[1] |
|
1897 | cpu_sys = end[1]-st[1] | |
1903 | cpu_tot = cpu_user+cpu_sys |
|
1898 | cpu_tot = cpu_user+cpu_sys | |
1904 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1899 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1905 | (cpu_user,cpu_sys,cpu_tot) |
|
1900 | (cpu_user,cpu_sys,cpu_tot) | |
1906 | print "Wall time: %.2f s" % wall_time |
|
1901 | print "Wall time: %.2f s" % wall_time | |
1907 | if tc > tc_min: |
|
1902 | if tc > tc_min: | |
1908 | print "Compiler : %.2f s" % tc |
|
1903 | print "Compiler : %.2f s" % tc | |
1909 | return out |
|
1904 | return out | |
1910 |
|
1905 | |||
1911 | @testdec.skip_doctest |
|
1906 | @testdec.skip_doctest | |
1912 | def magic_macro(self,parameter_s = ''): |
|
1907 | def magic_macro(self,parameter_s = ''): | |
1913 | """Define a set of input lines as a macro for future re-execution. |
|
1908 | """Define a set of input lines as a macro for future re-execution. | |
1914 |
|
1909 | |||
1915 | Usage:\\ |
|
1910 | Usage:\\ | |
1916 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1911 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1917 |
|
1912 | |||
1918 | Options: |
|
1913 | Options: | |
1919 |
|
1914 | |||
1920 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1915 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1921 | so that magics are loaded in their transformed version to valid |
|
1916 | so that magics are loaded in their transformed version to valid | |
1922 | Python. If this option is given, the raw input as typed as the |
|
1917 | Python. If this option is given, the raw input as typed as the | |
1923 | command line is used instead. |
|
1918 | command line is used instead. | |
1924 |
|
1919 | |||
1925 | This will define a global variable called `name` which is a string |
|
1920 | This will define a global variable called `name` which is a string | |
1926 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1921 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1927 | above) from your input history into a single string. This variable |
|
1922 | above) from your input history into a single string. This variable | |
1928 | acts like an automatic function which re-executes those lines as if |
|
1923 | acts like an automatic function which re-executes those lines as if | |
1929 | you had typed them. You just type 'name' at the prompt and the code |
|
1924 | you had typed them. You just type 'name' at the prompt and the code | |
1930 | executes. |
|
1925 | executes. | |
1931 |
|
1926 | |||
1932 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1927 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1933 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1928 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1934 | using the lines numbered 5,6 and 7. |
|
1929 | using the lines numbered 5,6 and 7. | |
1935 |
|
1930 | |||
1936 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1931 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1937 | notation, where N:M means numbers N through M-1. |
|
1932 | notation, where N:M means numbers N through M-1. | |
1938 |
|
1933 | |||
1939 | For example, if your history contains (%hist prints it): |
|
1934 | For example, if your history contains (%hist prints it): | |
1940 |
|
1935 | |||
1941 | 44: x=1 |
|
1936 | 44: x=1 | |
1942 | 45: y=3 |
|
1937 | 45: y=3 | |
1943 | 46: z=x+y |
|
1938 | 46: z=x+y | |
1944 | 47: print x |
|
1939 | 47: print x | |
1945 | 48: a=5 |
|
1940 | 48: a=5 | |
1946 | 49: print 'x',x,'y',y |
|
1941 | 49: print 'x',x,'y',y | |
1947 |
|
1942 | |||
1948 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1943 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1949 | called my_macro with: |
|
1944 | called my_macro with: | |
1950 |
|
1945 | |||
1951 | In [55]: %macro my_macro 44-47 49 |
|
1946 | In [55]: %macro my_macro 44-47 49 | |
1952 |
|
1947 | |||
1953 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1948 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1954 | in one pass. |
|
1949 | in one pass. | |
1955 |
|
1950 | |||
1956 | You don't need to give the line-numbers in order, and any given line |
|
1951 | You don't need to give the line-numbers in order, and any given line | |
1957 | number can appear multiple times. You can assemble macros with any |
|
1952 | number can appear multiple times. You can assemble macros with any | |
1958 | lines from your input history in any order. |
|
1953 | lines from your input history in any order. | |
1959 |
|
1954 | |||
1960 | The macro is a simple object which holds its value in an attribute, |
|
1955 | The macro is a simple object which holds its value in an attribute, | |
1961 | but IPython's display system checks for macros and executes them as |
|
1956 | but IPython's display system checks for macros and executes them as | |
1962 | code instead of printing them when you type their name. |
|
1957 | code instead of printing them when you type their name. | |
1963 |
|
1958 | |||
1964 | You can view a macro's contents by explicitly printing it with: |
|
1959 | You can view a macro's contents by explicitly printing it with: | |
1965 |
|
1960 | |||
1966 | 'print macro_name'. |
|
1961 | 'print macro_name'. | |
1967 |
|
1962 | |||
1968 | For one-off cases which DON'T contain magic function calls in them you |
|
1963 | For one-off cases which DON'T contain magic function calls in them you | |
1969 | can obtain similar results by explicitly executing slices from your |
|
1964 | can obtain similar results by explicitly executing slices from your | |
1970 | input history with: |
|
1965 | input history with: | |
1971 |
|
1966 | |||
1972 | In [60]: exec In[44:48]+In[49]""" |
|
1967 | In [60]: exec In[44:48]+In[49]""" | |
1973 |
|
1968 | |||
1974 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1969 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1975 | if not args: |
|
1970 | if not args: | |
1976 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1971 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1977 | macs.sort() |
|
1972 | macs.sort() | |
1978 | return macs |
|
1973 | return macs | |
1979 | if len(args) == 1: |
|
1974 | if len(args) == 1: | |
1980 | raise UsageError( |
|
1975 | raise UsageError( | |
1981 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1976 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1982 | name,ranges = args[0], args[1:] |
|
1977 | name,ranges = args[0], args[1:] | |
1983 |
|
1978 | |||
1984 | #print 'rng',ranges # dbg |
|
1979 | #print 'rng',ranges # dbg | |
1985 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1980 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1986 | macro = Macro(lines) |
|
1981 | macro = Macro(lines) | |
1987 | self.shell.define_macro(name, macro) |
|
1982 | self.shell.define_macro(name, macro) | |
1988 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1983 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1989 | print 'Macro contents:' |
|
1984 | print 'Macro contents:' | |
1990 | print macro, |
|
1985 | print macro, | |
1991 |
|
1986 | |||
1992 | def magic_save(self,parameter_s = ''): |
|
1987 | def magic_save(self,parameter_s = ''): | |
1993 | """Save a set of lines to a given filename. |
|
1988 | """Save a set of lines to a given filename. | |
1994 |
|
1989 | |||
1995 | Usage:\\ |
|
1990 | Usage:\\ | |
1996 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1991 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1997 |
|
1992 | |||
1998 | Options: |
|
1993 | Options: | |
1999 |
|
1994 | |||
2000 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1995 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2001 | so that magics are loaded in their transformed version to valid |
|
1996 | so that magics are loaded in their transformed version to valid | |
2002 | Python. If this option is given, the raw input as typed as the |
|
1997 | Python. If this option is given, the raw input as typed as the | |
2003 | command line is used instead. |
|
1998 | command line is used instead. | |
2004 |
|
1999 | |||
2005 | This function uses the same syntax as %macro for line extraction, but |
|
2000 | This function uses the same syntax as %macro for line extraction, but | |
2006 | instead of creating a macro it saves the resulting string to the |
|
2001 | instead of creating a macro it saves the resulting string to the | |
2007 | filename you specify. |
|
2002 | filename you specify. | |
2008 |
|
2003 | |||
2009 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2004 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2010 | it asks for confirmation before overwriting existing files.""" |
|
2005 | it asks for confirmation before overwriting existing files.""" | |
2011 |
|
2006 | |||
2012 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2007 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2013 | fname,ranges = args[0], args[1:] |
|
2008 | fname,ranges = args[0], args[1:] | |
2014 | if not fname.endswith('.py'): |
|
2009 | if not fname.endswith('.py'): | |
2015 | fname += '.py' |
|
2010 | fname += '.py' | |
2016 | if os.path.isfile(fname): |
|
2011 | if os.path.isfile(fname): | |
2017 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2012 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2018 | if ans.lower() not in ['y','yes']: |
|
2013 | if ans.lower() not in ['y','yes']: | |
2019 | print 'Operation cancelled.' |
|
2014 | print 'Operation cancelled.' | |
2020 | return |
|
2015 | return | |
2021 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2016 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2022 | f = file(fname,'w') |
|
2017 | f = file(fname,'w') | |
2023 | f.write(cmds) |
|
2018 | f.write(cmds) | |
2024 | f.close() |
|
2019 | f.close() | |
2025 | print 'The following commands were written to file `%s`:' % fname |
|
2020 | print 'The following commands were written to file `%s`:' % fname | |
2026 | print cmds |
|
2021 | print cmds | |
2027 |
|
2022 | |||
2028 | def _edit_macro(self,mname,macro): |
|
2023 | def _edit_macro(self,mname,macro): | |
2029 | """open an editor with the macro data in a file""" |
|
2024 | """open an editor with the macro data in a file""" | |
2030 | filename = self.shell.mktempfile(macro.value) |
|
2025 | filename = self.shell.mktempfile(macro.value) | |
2031 | self.shell.hooks.editor(filename) |
|
2026 | self.shell.hooks.editor(filename) | |
2032 |
|
2027 | |||
2033 | # and make a new macro object, to replace the old one |
|
2028 | # and make a new macro object, to replace the old one | |
2034 | mfile = open(filename) |
|
2029 | mfile = open(filename) | |
2035 | mvalue = mfile.read() |
|
2030 | mvalue = mfile.read() | |
2036 | mfile.close() |
|
2031 | mfile.close() | |
2037 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2032 | self.shell.user_ns[mname] = Macro(mvalue) | |
2038 |
|
2033 | |||
2039 | def magic_ed(self,parameter_s=''): |
|
2034 | def magic_ed(self,parameter_s=''): | |
2040 | """Alias to %edit.""" |
|
2035 | """Alias to %edit.""" | |
2041 | return self.magic_edit(parameter_s) |
|
2036 | return self.magic_edit(parameter_s) | |
2042 |
|
2037 | |||
2043 | @testdec.skip_doctest |
|
2038 | @testdec.skip_doctest | |
2044 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2039 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2045 | """Bring up an editor and execute the resulting code. |
|
2040 | """Bring up an editor and execute the resulting code. | |
2046 |
|
2041 | |||
2047 | Usage: |
|
2042 | Usage: | |
2048 | %edit [options] [args] |
|
2043 | %edit [options] [args] | |
2049 |
|
2044 | |||
2050 | %edit runs IPython's editor hook. The default version of this hook is |
|
2045 | %edit runs IPython's editor hook. The default version of this hook is | |
2051 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2046 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2052 | environment variable $EDITOR. If this isn't found, it will default to |
|
2047 | environment variable $EDITOR. If this isn't found, it will default to | |
2053 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2048 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2054 | docstring for how to change the editor hook. |
|
2049 | docstring for how to change the editor hook. | |
2055 |
|
2050 | |||
2056 | You can also set the value of this editor via the command line option |
|
2051 | You can also set the value of this editor via the command line option | |
2057 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2052 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2058 | specifically for IPython an editor different from your typical default |
|
2053 | specifically for IPython an editor different from your typical default | |
2059 | (and for Windows users who typically don't set environment variables). |
|
2054 | (and for Windows users who typically don't set environment variables). | |
2060 |
|
2055 | |||
2061 | This command allows you to conveniently edit multi-line code right in |
|
2056 | This command allows you to conveniently edit multi-line code right in | |
2062 | your IPython session. |
|
2057 | your IPython session. | |
2063 |
|
2058 | |||
2064 | If called without arguments, %edit opens up an empty editor with a |
|
2059 | If called without arguments, %edit opens up an empty editor with a | |
2065 | temporary file and will execute the contents of this file when you |
|
2060 | temporary file and will execute the contents of this file when you | |
2066 | close it (don't forget to save it!). |
|
2061 | close it (don't forget to save it!). | |
2067 |
|
2062 | |||
2068 |
|
2063 | |||
2069 | Options: |
|
2064 | Options: | |
2070 |
|
2065 | |||
2071 | -n <number>: open the editor at a specified line number. By default, |
|
2066 | -n <number>: open the editor at a specified line number. By default, | |
2072 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2067 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2073 | you can configure this by providing your own modified hook if your |
|
2068 | you can configure this by providing your own modified hook if your | |
2074 | favorite editor supports line-number specifications with a different |
|
2069 | favorite editor supports line-number specifications with a different | |
2075 | syntax. |
|
2070 | syntax. | |
2076 |
|
2071 | |||
2077 | -p: this will call the editor with the same data as the previous time |
|
2072 | -p: this will call the editor with the same data as the previous time | |
2078 | it was used, regardless of how long ago (in your current session) it |
|
2073 | it was used, regardless of how long ago (in your current session) it | |
2079 | was. |
|
2074 | was. | |
2080 |
|
2075 | |||
2081 | -r: use 'raw' input. This option only applies to input taken from the |
|
2076 | -r: use 'raw' input. This option only applies to input taken from the | |
2082 | user's history. By default, the 'processed' history is used, so that |
|
2077 | user's history. By default, the 'processed' history is used, so that | |
2083 | magics are loaded in their transformed version to valid Python. If |
|
2078 | magics are loaded in their transformed version to valid Python. If | |
2084 | this option is given, the raw input as typed as the command line is |
|
2079 | this option is given, the raw input as typed as the command line is | |
2085 | used instead. When you exit the editor, it will be executed by |
|
2080 | used instead. When you exit the editor, it will be executed by | |
2086 | IPython's own processor. |
|
2081 | IPython's own processor. | |
2087 |
|
2082 | |||
2088 | -x: do not execute the edited code immediately upon exit. This is |
|
2083 | -x: do not execute the edited code immediately upon exit. This is | |
2089 | mainly useful if you are editing programs which need to be called with |
|
2084 | mainly useful if you are editing programs which need to be called with | |
2090 | command line arguments, which you can then do using %run. |
|
2085 | command line arguments, which you can then do using %run. | |
2091 |
|
2086 | |||
2092 |
|
2087 | |||
2093 | Arguments: |
|
2088 | Arguments: | |
2094 |
|
2089 | |||
2095 | If arguments are given, the following possibilites exist: |
|
2090 | If arguments are given, the following possibilites exist: | |
2096 |
|
2091 | |||
2097 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2092 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2098 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2093 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2099 | loaded into the editor. The syntax is the same of the %macro command. |
|
2094 | loaded into the editor. The syntax is the same of the %macro command. | |
2100 |
|
2095 | |||
2101 | - If the argument doesn't start with a number, it is evaluated as a |
|
2096 | - If the argument doesn't start with a number, it is evaluated as a | |
2102 | variable and its contents loaded into the editor. You can thus edit |
|
2097 | variable and its contents loaded into the editor. You can thus edit | |
2103 | any string which contains python code (including the result of |
|
2098 | any string which contains python code (including the result of | |
2104 | previous edits). |
|
2099 | previous edits). | |
2105 |
|
2100 | |||
2106 | - If the argument is the name of an object (other than a string), |
|
2101 | - If the argument is the name of an object (other than a string), | |
2107 | IPython will try to locate the file where it was defined and open the |
|
2102 | IPython will try to locate the file where it was defined and open the | |
2108 | editor at the point where it is defined. You can use `%edit function` |
|
2103 | editor at the point where it is defined. You can use `%edit function` | |
2109 | to load an editor exactly at the point where 'function' is defined, |
|
2104 | to load an editor exactly at the point where 'function' is defined, | |
2110 | edit it and have the file be executed automatically. |
|
2105 | edit it and have the file be executed automatically. | |
2111 |
|
2106 | |||
2112 | If the object is a macro (see %macro for details), this opens up your |
|
2107 | If the object is a macro (see %macro for details), this opens up your | |
2113 | specified editor with a temporary file containing the macro's data. |
|
2108 | specified editor with a temporary file containing the macro's data. | |
2114 | Upon exit, the macro is reloaded with the contents of the file. |
|
2109 | Upon exit, the macro is reloaded with the contents of the file. | |
2115 |
|
2110 | |||
2116 | Note: opening at an exact line is only supported under Unix, and some |
|
2111 | Note: opening at an exact line is only supported under Unix, and some | |
2117 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2112 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2118 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2113 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2119 | (X)Emacs, vi, jed, pico and joe all do. |
|
2114 | (X)Emacs, vi, jed, pico and joe all do. | |
2120 |
|
2115 | |||
2121 | - If the argument is not found as a variable, IPython will look for a |
|
2116 | - If the argument is not found as a variable, IPython will look for a | |
2122 | file with that name (adding .py if necessary) and load it into the |
|
2117 | file with that name (adding .py if necessary) and load it into the | |
2123 | editor. It will execute its contents with execfile() when you exit, |
|
2118 | editor. It will execute its contents with execfile() when you exit, | |
2124 | loading any code in the file into your interactive namespace. |
|
2119 | loading any code in the file into your interactive namespace. | |
2125 |
|
2120 | |||
2126 | After executing your code, %edit will return as output the code you |
|
2121 | After executing your code, %edit will return as output the code you | |
2127 | typed in the editor (except when it was an existing file). This way |
|
2122 | typed in the editor (except when it was an existing file). This way | |
2128 | you can reload the code in further invocations of %edit as a variable, |
|
2123 | you can reload the code in further invocations of %edit as a variable, | |
2129 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2124 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2130 | the output. |
|
2125 | the output. | |
2131 |
|
2126 | |||
2132 | Note that %edit is also available through the alias %ed. |
|
2127 | Note that %edit is also available through the alias %ed. | |
2133 |
|
2128 | |||
2134 | This is an example of creating a simple function inside the editor and |
|
2129 | This is an example of creating a simple function inside the editor and | |
2135 | then modifying it. First, start up the editor: |
|
2130 | then modifying it. First, start up the editor: | |
2136 |
|
2131 | |||
2137 | In [1]: ed |
|
2132 | In [1]: ed | |
2138 | Editing... done. Executing edited code... |
|
2133 | Editing... done. Executing edited code... | |
2139 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2134 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2140 |
|
2135 | |||
2141 | We can then call the function foo(): |
|
2136 | We can then call the function foo(): | |
2142 |
|
2137 | |||
2143 | In [2]: foo() |
|
2138 | In [2]: foo() | |
2144 | foo() was defined in an editing session |
|
2139 | foo() was defined in an editing session | |
2145 |
|
2140 | |||
2146 | Now we edit foo. IPython automatically loads the editor with the |
|
2141 | Now we edit foo. IPython automatically loads the editor with the | |
2147 | (temporary) file where foo() was previously defined: |
|
2142 | (temporary) file where foo() was previously defined: | |
2148 |
|
2143 | |||
2149 | In [3]: ed foo |
|
2144 | In [3]: ed foo | |
2150 | Editing... done. Executing edited code... |
|
2145 | Editing... done. Executing edited code... | |
2151 |
|
2146 | |||
2152 | And if we call foo() again we get the modified version: |
|
2147 | And if we call foo() again we get the modified version: | |
2153 |
|
2148 | |||
2154 | In [4]: foo() |
|
2149 | In [4]: foo() | |
2155 | foo() has now been changed! |
|
2150 | foo() has now been changed! | |
2156 |
|
2151 | |||
2157 | Here is an example of how to edit a code snippet successive |
|
2152 | Here is an example of how to edit a code snippet successive | |
2158 | times. First we call the editor: |
|
2153 | times. First we call the editor: | |
2159 |
|
2154 | |||
2160 | In [5]: ed |
|
2155 | In [5]: ed | |
2161 | Editing... done. Executing edited code... |
|
2156 | Editing... done. Executing edited code... | |
2162 | hello |
|
2157 | hello | |
2163 | Out[5]: "print 'hello'n" |
|
2158 | Out[5]: "print 'hello'n" | |
2164 |
|
2159 | |||
2165 | Now we call it again with the previous output (stored in _): |
|
2160 | Now we call it again with the previous output (stored in _): | |
2166 |
|
2161 | |||
2167 | In [6]: ed _ |
|
2162 | In [6]: ed _ | |
2168 | Editing... done. Executing edited code... |
|
2163 | Editing... done. Executing edited code... | |
2169 | hello world |
|
2164 | hello world | |
2170 | Out[6]: "print 'hello world'n" |
|
2165 | Out[6]: "print 'hello world'n" | |
2171 |
|
2166 | |||
2172 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2167 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2173 |
|
2168 | |||
2174 | In [7]: ed _8 |
|
2169 | In [7]: ed _8 | |
2175 | Editing... done. Executing edited code... |
|
2170 | Editing... done. Executing edited code... | |
2176 | hello again |
|
2171 | hello again | |
2177 | Out[7]: "print 'hello again'n" |
|
2172 | Out[7]: "print 'hello again'n" | |
2178 |
|
2173 | |||
2179 |
|
2174 | |||
2180 | Changing the default editor hook: |
|
2175 | Changing the default editor hook: | |
2181 |
|
2176 | |||
2182 | If you wish to write your own editor hook, you can put it in a |
|
2177 | If you wish to write your own editor hook, you can put it in a | |
2183 | configuration file which you load at startup time. The default hook |
|
2178 | configuration file which you load at startup time. The default hook | |
2184 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2179 | is defined in the IPython.core.hooks module, and you can use that as a | |
2185 | starting example for further modifications. That file also has |
|
2180 | starting example for further modifications. That file also has | |
2186 | general instructions on how to set a new hook for use once you've |
|
2181 | general instructions on how to set a new hook for use once you've | |
2187 | defined it.""" |
|
2182 | defined it.""" | |
2188 |
|
2183 | |||
2189 | # FIXME: This function has become a convoluted mess. It needs a |
|
2184 | # FIXME: This function has become a convoluted mess. It needs a | |
2190 | # ground-up rewrite with clean, simple logic. |
|
2185 | # ground-up rewrite with clean, simple logic. | |
2191 |
|
2186 | |||
2192 | def make_filename(arg): |
|
2187 | def make_filename(arg): | |
2193 | "Make a filename from the given args" |
|
2188 | "Make a filename from the given args" | |
2194 | try: |
|
2189 | try: | |
2195 | filename = get_py_filename(arg) |
|
2190 | filename = get_py_filename(arg) | |
2196 | except IOError: |
|
2191 | except IOError: | |
2197 | if args.endswith('.py'): |
|
2192 | if args.endswith('.py'): | |
2198 | filename = arg |
|
2193 | filename = arg | |
2199 | else: |
|
2194 | else: | |
2200 | filename = None |
|
2195 | filename = None | |
2201 | return filename |
|
2196 | return filename | |
2202 |
|
2197 | |||
2203 | # custom exceptions |
|
2198 | # custom exceptions | |
2204 | class DataIsObject(Exception): pass |
|
2199 | class DataIsObject(Exception): pass | |
2205 |
|
2200 | |||
2206 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2201 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2207 | # Set a few locals from the options for convenience: |
|
2202 | # Set a few locals from the options for convenience: | |
2208 | opts_p = opts.has_key('p') |
|
2203 | opts_p = opts.has_key('p') | |
2209 | opts_r = opts.has_key('r') |
|
2204 | opts_r = opts.has_key('r') | |
2210 |
|
2205 | |||
2211 | # Default line number value |
|
2206 | # Default line number value | |
2212 | lineno = opts.get('n',None) |
|
2207 | lineno = opts.get('n',None) | |
2213 |
|
2208 | |||
2214 | if opts_p: |
|
2209 | if opts_p: | |
2215 | args = '_%s' % last_call[0] |
|
2210 | args = '_%s' % last_call[0] | |
2216 | if not self.shell.user_ns.has_key(args): |
|
2211 | if not self.shell.user_ns.has_key(args): | |
2217 | args = last_call[1] |
|
2212 | args = last_call[1] | |
2218 |
|
2213 | |||
2219 | # use last_call to remember the state of the previous call, but don't |
|
2214 | # use last_call to remember the state of the previous call, but don't | |
2220 | # let it be clobbered by successive '-p' calls. |
|
2215 | # let it be clobbered by successive '-p' calls. | |
2221 | try: |
|
2216 | try: | |
2222 | last_call[0] = self.shell.displayhook.prompt_count |
|
2217 | last_call[0] = self.shell.displayhook.prompt_count | |
2223 | if not opts_p: |
|
2218 | if not opts_p: | |
2224 | last_call[1] = parameter_s |
|
2219 | last_call[1] = parameter_s | |
2225 | except: |
|
2220 | except: | |
2226 | pass |
|
2221 | pass | |
2227 |
|
2222 | |||
2228 | # by default this is done with temp files, except when the given |
|
2223 | # by default this is done with temp files, except when the given | |
2229 | # arg is a filename |
|
2224 | # arg is a filename | |
2230 | use_temp = 1 |
|
2225 | use_temp = 1 | |
2231 |
|
2226 | |||
2232 | if re.match(r'\d',args): |
|
2227 | if re.match(r'\d',args): | |
2233 | # Mode where user specifies ranges of lines, like in %macro. |
|
2228 | # Mode where user specifies ranges of lines, like in %macro. | |
2234 | # This means that you can't edit files whose names begin with |
|
2229 | # This means that you can't edit files whose names begin with | |
2235 | # numbers this way. Tough. |
|
2230 | # numbers this way. Tough. | |
2236 | ranges = args.split() |
|
2231 | ranges = args.split() | |
2237 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2232 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2238 | elif args.endswith('.py'): |
|
2233 | elif args.endswith('.py'): | |
2239 | filename = make_filename(args) |
|
2234 | filename = make_filename(args) | |
2240 | data = '' |
|
2235 | data = '' | |
2241 | use_temp = 0 |
|
2236 | use_temp = 0 | |
2242 | elif args: |
|
2237 | elif args: | |
2243 | try: |
|
2238 | try: | |
2244 | # Load the parameter given as a variable. If not a string, |
|
2239 | # Load the parameter given as a variable. If not a string, | |
2245 | # process it as an object instead (below) |
|
2240 | # process it as an object instead (below) | |
2246 |
|
2241 | |||
2247 | #print '*** args',args,'type',type(args) # dbg |
|
2242 | #print '*** args',args,'type',type(args) # dbg | |
2248 | data = eval(args,self.shell.user_ns) |
|
2243 | data = eval(args,self.shell.user_ns) | |
2249 | if not type(data) in StringTypes: |
|
2244 | if not type(data) in StringTypes: | |
2250 | raise DataIsObject |
|
2245 | raise DataIsObject | |
2251 |
|
2246 | |||
2252 | except (NameError,SyntaxError): |
|
2247 | except (NameError,SyntaxError): | |
2253 | # given argument is not a variable, try as a filename |
|
2248 | # given argument is not a variable, try as a filename | |
2254 | filename = make_filename(args) |
|
2249 | filename = make_filename(args) | |
2255 | if filename is None: |
|
2250 | if filename is None: | |
2256 | warn("Argument given (%s) can't be found as a variable " |
|
2251 | warn("Argument given (%s) can't be found as a variable " | |
2257 | "or as a filename." % args) |
|
2252 | "or as a filename." % args) | |
2258 | return |
|
2253 | return | |
2259 |
|
2254 | |||
2260 | data = '' |
|
2255 | data = '' | |
2261 | use_temp = 0 |
|
2256 | use_temp = 0 | |
2262 | except DataIsObject: |
|
2257 | except DataIsObject: | |
2263 |
|
2258 | |||
2264 | # macros have a special edit function |
|
2259 | # macros have a special edit function | |
2265 | if isinstance(data,Macro): |
|
2260 | if isinstance(data,Macro): | |
2266 | self._edit_macro(args,data) |
|
2261 | self._edit_macro(args,data) | |
2267 | return |
|
2262 | return | |
2268 |
|
2263 | |||
2269 | # For objects, try to edit the file where they are defined |
|
2264 | # For objects, try to edit the file where they are defined | |
2270 | try: |
|
2265 | try: | |
2271 | filename = inspect.getabsfile(data) |
|
2266 | filename = inspect.getabsfile(data) | |
2272 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2267 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2273 | # class created by %edit? Try to find source |
|
2268 | # class created by %edit? Try to find source | |
2274 | # by looking for method definitions instead, the |
|
2269 | # by looking for method definitions instead, the | |
2275 | # __module__ in those classes is FakeModule. |
|
2270 | # __module__ in those classes is FakeModule. | |
2276 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2271 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2277 | for attr in attrs: |
|
2272 | for attr in attrs: | |
2278 | if not inspect.ismethod(attr): |
|
2273 | if not inspect.ismethod(attr): | |
2279 | continue |
|
2274 | continue | |
2280 | filename = inspect.getabsfile(attr) |
|
2275 | filename = inspect.getabsfile(attr) | |
2281 | if filename and 'fakemodule' not in filename.lower(): |
|
2276 | if filename and 'fakemodule' not in filename.lower(): | |
2282 | # change the attribute to be the edit target instead |
|
2277 | # change the attribute to be the edit target instead | |
2283 | data = attr |
|
2278 | data = attr | |
2284 | break |
|
2279 | break | |
2285 |
|
2280 | |||
2286 | datafile = 1 |
|
2281 | datafile = 1 | |
2287 | except TypeError: |
|
2282 | except TypeError: | |
2288 | filename = make_filename(args) |
|
2283 | filename = make_filename(args) | |
2289 | datafile = 1 |
|
2284 | datafile = 1 | |
2290 | warn('Could not find file where `%s` is defined.\n' |
|
2285 | warn('Could not find file where `%s` is defined.\n' | |
2291 | 'Opening a file named `%s`' % (args,filename)) |
|
2286 | 'Opening a file named `%s`' % (args,filename)) | |
2292 | # Now, make sure we can actually read the source (if it was in |
|
2287 | # Now, make sure we can actually read the source (if it was in | |
2293 | # a temp file it's gone by now). |
|
2288 | # a temp file it's gone by now). | |
2294 | if datafile: |
|
2289 | if datafile: | |
2295 | try: |
|
2290 | try: | |
2296 | if lineno is None: |
|
2291 | if lineno is None: | |
2297 | lineno = inspect.getsourcelines(data)[1] |
|
2292 | lineno = inspect.getsourcelines(data)[1] | |
2298 | except IOError: |
|
2293 | except IOError: | |
2299 | filename = make_filename(args) |
|
2294 | filename = make_filename(args) | |
2300 | if filename is None: |
|
2295 | if filename is None: | |
2301 | warn('The file `%s` where `%s` was defined cannot ' |
|
2296 | warn('The file `%s` where `%s` was defined cannot ' | |
2302 | 'be read.' % (filename,data)) |
|
2297 | 'be read.' % (filename,data)) | |
2303 | return |
|
2298 | return | |
2304 | use_temp = 0 |
|
2299 | use_temp = 0 | |
2305 | else: |
|
2300 | else: | |
2306 | data = '' |
|
2301 | data = '' | |
2307 |
|
2302 | |||
2308 | if use_temp: |
|
2303 | if use_temp: | |
2309 | filename = self.shell.mktempfile(data) |
|
2304 | filename = self.shell.mktempfile(data) | |
2310 | print 'IPython will make a temporary file named:',filename |
|
2305 | print 'IPython will make a temporary file named:',filename | |
2311 |
|
2306 | |||
2312 | # do actual editing here |
|
2307 | # do actual editing here | |
2313 | print 'Editing...', |
|
2308 | print 'Editing...', | |
2314 | sys.stdout.flush() |
|
2309 | sys.stdout.flush() | |
2315 | try: |
|
2310 | try: | |
2316 | # Quote filenames that may have spaces in them |
|
2311 | # Quote filenames that may have spaces in them | |
2317 | if ' ' in filename: |
|
2312 | if ' ' in filename: | |
2318 | filename = "%s" % filename |
|
2313 | filename = "%s" % filename | |
2319 | self.shell.hooks.editor(filename,lineno) |
|
2314 | self.shell.hooks.editor(filename,lineno) | |
2320 | except TryNext: |
|
2315 | except TryNext: | |
2321 | warn('Could not open editor') |
|
2316 | warn('Could not open editor') | |
2322 | return |
|
2317 | return | |
2323 |
|
2318 | |||
2324 | # XXX TODO: should this be generalized for all string vars? |
|
2319 | # XXX TODO: should this be generalized for all string vars? | |
2325 | # For now, this is special-cased to blocks created by cpaste |
|
2320 | # For now, this is special-cased to blocks created by cpaste | |
2326 | if args.strip() == 'pasted_block': |
|
2321 | if args.strip() == 'pasted_block': | |
2327 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2322 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2328 |
|
2323 | |||
2329 | if opts.has_key('x'): # -x prevents actual execution |
|
2324 | if opts.has_key('x'): # -x prevents actual execution | |
2330 |
|
2325 | |||
2331 | else: |
|
2326 | else: | |
2332 | print 'done. Executing edited code...' |
|
2327 | print 'done. Executing edited code...' | |
2333 | if opts_r: |
|
2328 | if opts_r: | |
2334 |
self.shell.run |
|
2329 | self.shell.run_cell(file_read(filename)) | |
2335 | else: |
|
2330 | else: | |
2336 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2331 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2337 | self.shell.user_ns) |
|
2332 | self.shell.user_ns) | |
2338 |
|
2333 | |||
2339 |
|
2334 | |||
2340 | if use_temp: |
|
2335 | if use_temp: | |
2341 | try: |
|
2336 | try: | |
2342 | return open(filename).read() |
|
2337 | return open(filename).read() | |
2343 | except IOError,msg: |
|
2338 | except IOError,msg: | |
2344 | if msg.filename == filename: |
|
2339 | if msg.filename == filename: | |
2345 | warn('File not found. Did you forget to save?') |
|
2340 | warn('File not found. Did you forget to save?') | |
2346 | return |
|
2341 | return | |
2347 | else: |
|
2342 | else: | |
2348 | self.shell.showtraceback() |
|
2343 | self.shell.showtraceback() | |
2349 |
|
2344 | |||
2350 | def magic_xmode(self,parameter_s = ''): |
|
2345 | def magic_xmode(self,parameter_s = ''): | |
2351 | """Switch modes for the exception handlers. |
|
2346 | """Switch modes for the exception handlers. | |
2352 |
|
2347 | |||
2353 | Valid modes: Plain, Context and Verbose. |
|
2348 | Valid modes: Plain, Context and Verbose. | |
2354 |
|
2349 | |||
2355 | If called without arguments, acts as a toggle.""" |
|
2350 | If called without arguments, acts as a toggle.""" | |
2356 |
|
2351 | |||
2357 | def xmode_switch_err(name): |
|
2352 | def xmode_switch_err(name): | |
2358 | warn('Error changing %s exception modes.\n%s' % |
|
2353 | warn('Error changing %s exception modes.\n%s' % | |
2359 | (name,sys.exc_info()[1])) |
|
2354 | (name,sys.exc_info()[1])) | |
2360 |
|
2355 | |||
2361 | shell = self.shell |
|
2356 | shell = self.shell | |
2362 | new_mode = parameter_s.strip().capitalize() |
|
2357 | new_mode = parameter_s.strip().capitalize() | |
2363 | try: |
|
2358 | try: | |
2364 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2359 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2365 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2360 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2366 | except: |
|
2361 | except: | |
2367 | xmode_switch_err('user') |
|
2362 | xmode_switch_err('user') | |
2368 |
|
2363 | |||
2369 | def magic_colors(self,parameter_s = ''): |
|
2364 | def magic_colors(self,parameter_s = ''): | |
2370 | """Switch color scheme for prompts, info system and exception handlers. |
|
2365 | """Switch color scheme for prompts, info system and exception handlers. | |
2371 |
|
2366 | |||
2372 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2367 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2373 |
|
2368 | |||
2374 | Color scheme names are not case-sensitive.""" |
|
2369 | Color scheme names are not case-sensitive.""" | |
2375 |
|
2370 | |||
2376 | def color_switch_err(name): |
|
2371 | def color_switch_err(name): | |
2377 | warn('Error changing %s color schemes.\n%s' % |
|
2372 | warn('Error changing %s color schemes.\n%s' % | |
2378 | (name,sys.exc_info()[1])) |
|
2373 | (name,sys.exc_info()[1])) | |
2379 |
|
2374 | |||
2380 |
|
2375 | |||
2381 | new_scheme = parameter_s.strip() |
|
2376 | new_scheme = parameter_s.strip() | |
2382 | if not new_scheme: |
|
2377 | if not new_scheme: | |
2383 | raise UsageError( |
|
2378 | raise UsageError( | |
2384 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2379 | "%colors: you must specify a color scheme. See '%colors?'") | |
2385 | return |
|
2380 | return | |
2386 | # local shortcut |
|
2381 | # local shortcut | |
2387 | shell = self.shell |
|
2382 | shell = self.shell | |
2388 |
|
2383 | |||
2389 | import IPython.utils.rlineimpl as readline |
|
2384 | import IPython.utils.rlineimpl as readline | |
2390 |
|
2385 | |||
2391 | if not readline.have_readline and sys.platform == "win32": |
|
2386 | if not readline.have_readline and sys.platform == "win32": | |
2392 | msg = """\ |
|
2387 | msg = """\ | |
2393 | Proper color support under MS Windows requires the pyreadline library. |
|
2388 | Proper color support under MS Windows requires the pyreadline library. | |
2394 | You can find it at: |
|
2389 | You can find it at: | |
2395 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2390 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2396 | Gary's readline needs the ctypes module, from: |
|
2391 | Gary's readline needs the ctypes module, from: | |
2397 | http://starship.python.net/crew/theller/ctypes |
|
2392 | http://starship.python.net/crew/theller/ctypes | |
2398 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2393 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2399 |
|
2394 | |||
2400 | Defaulting color scheme to 'NoColor'""" |
|
2395 | Defaulting color scheme to 'NoColor'""" | |
2401 | new_scheme = 'NoColor' |
|
2396 | new_scheme = 'NoColor' | |
2402 | warn(msg) |
|
2397 | warn(msg) | |
2403 |
|
2398 | |||
2404 | # readline option is 0 |
|
2399 | # readline option is 0 | |
2405 | if not shell.has_readline: |
|
2400 | if not shell.has_readline: | |
2406 | new_scheme = 'NoColor' |
|
2401 | new_scheme = 'NoColor' | |
2407 |
|
2402 | |||
2408 | # Set prompt colors |
|
2403 | # Set prompt colors | |
2409 | try: |
|
2404 | try: | |
2410 | shell.displayhook.set_colors(new_scheme) |
|
2405 | shell.displayhook.set_colors(new_scheme) | |
2411 | except: |
|
2406 | except: | |
2412 | color_switch_err('prompt') |
|
2407 | color_switch_err('prompt') | |
2413 | else: |
|
2408 | else: | |
2414 | shell.colors = \ |
|
2409 | shell.colors = \ | |
2415 | shell.displayhook.color_table.active_scheme_name |
|
2410 | shell.displayhook.color_table.active_scheme_name | |
2416 | # Set exception colors |
|
2411 | # Set exception colors | |
2417 | try: |
|
2412 | try: | |
2418 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2413 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2419 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2414 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2420 | except: |
|
2415 | except: | |
2421 | color_switch_err('exception') |
|
2416 | color_switch_err('exception') | |
2422 |
|
2417 | |||
2423 | # Set info (for 'object?') colors |
|
2418 | # Set info (for 'object?') colors | |
2424 | if shell.color_info: |
|
2419 | if shell.color_info: | |
2425 | try: |
|
2420 | try: | |
2426 | shell.inspector.set_active_scheme(new_scheme) |
|
2421 | shell.inspector.set_active_scheme(new_scheme) | |
2427 | except: |
|
2422 | except: | |
2428 | color_switch_err('object inspector') |
|
2423 | color_switch_err('object inspector') | |
2429 | else: |
|
2424 | else: | |
2430 | shell.inspector.set_active_scheme('NoColor') |
|
2425 | shell.inspector.set_active_scheme('NoColor') | |
2431 |
|
2426 | |||
2432 | def magic_Pprint(self, parameter_s=''): |
|
2427 | def magic_Pprint(self, parameter_s=''): | |
2433 | """Toggle pretty printing on/off.""" |
|
2428 | """Toggle pretty printing on/off.""" | |
2434 |
|
2429 | |||
2435 | self.shell.pprint = 1 - self.shell.pprint |
|
2430 | self.shell.pprint = 1 - self.shell.pprint | |
2436 | print 'Pretty printing has been turned', \ |
|
2431 | print 'Pretty printing has been turned', \ | |
2437 | ['OFF','ON'][self.shell.pprint] |
|
2432 | ['OFF','ON'][self.shell.pprint] | |
2438 |
|
2433 | |||
2439 | def magic_Exit(self, parameter_s=''): |
|
2434 | def magic_Exit(self, parameter_s=''): | |
2440 | """Exit IPython.""" |
|
2435 | """Exit IPython.""" | |
2441 |
|
2436 | |||
2442 | self.shell.ask_exit() |
|
2437 | self.shell.ask_exit() | |
2443 |
|
2438 | |||
2444 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2439 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2445 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2440 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2446 |
|
2441 | |||
2447 | #...................................................................... |
|
2442 | #...................................................................... | |
2448 | # Functions to implement unix shell-type things |
|
2443 | # Functions to implement unix shell-type things | |
2449 |
|
2444 | |||
2450 | @testdec.skip_doctest |
|
2445 | @testdec.skip_doctest | |
2451 | def magic_alias(self, parameter_s = ''): |
|
2446 | def magic_alias(self, parameter_s = ''): | |
2452 | """Define an alias for a system command. |
|
2447 | """Define an alias for a system command. | |
2453 |
|
2448 | |||
2454 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2449 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2455 |
|
2450 | |||
2456 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2451 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2457 | params' (from your underlying operating system). |
|
2452 | params' (from your underlying operating system). | |
2458 |
|
2453 | |||
2459 | Aliases have lower precedence than magic functions and Python normal |
|
2454 | Aliases have lower precedence than magic functions and Python normal | |
2460 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2455 | variables, so if 'foo' is both a Python variable and an alias, the | |
2461 | alias can not be executed until 'del foo' removes the Python variable. |
|
2456 | alias can not be executed until 'del foo' removes the Python variable. | |
2462 |
|
2457 | |||
2463 | You can use the %l specifier in an alias definition to represent the |
|
2458 | You can use the %l specifier in an alias definition to represent the | |
2464 | whole line when the alias is called. For example: |
|
2459 | whole line when the alias is called. For example: | |
2465 |
|
2460 | |||
2466 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2461 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2467 | In [3]: bracket hello world |
|
2462 | In [3]: bracket hello world | |
2468 | Input in brackets: <hello world> |
|
2463 | Input in brackets: <hello world> | |
2469 |
|
2464 | |||
2470 | You can also define aliases with parameters using %s specifiers (one |
|
2465 | You can also define aliases with parameters using %s specifiers (one | |
2471 | per parameter): |
|
2466 | per parameter): | |
2472 |
|
2467 | |||
2473 | In [1]: alias parts echo first %s second %s |
|
2468 | In [1]: alias parts echo first %s second %s | |
2474 | In [2]: %parts A B |
|
2469 | In [2]: %parts A B | |
2475 | first A second B |
|
2470 | first A second B | |
2476 | In [3]: %parts A |
|
2471 | In [3]: %parts A | |
2477 | Incorrect number of arguments: 2 expected. |
|
2472 | Incorrect number of arguments: 2 expected. | |
2478 | parts is an alias to: 'echo first %s second %s' |
|
2473 | parts is an alias to: 'echo first %s second %s' | |
2479 |
|
2474 | |||
2480 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2475 | Note that %l and %s are mutually exclusive. You can only use one or | |
2481 | the other in your aliases. |
|
2476 | the other in your aliases. | |
2482 |
|
2477 | |||
2483 | Aliases expand Python variables just like system calls using ! or !! |
|
2478 | Aliases expand Python variables just like system calls using ! or !! | |
2484 | do: all expressions prefixed with '$' get expanded. For details of |
|
2479 | do: all expressions prefixed with '$' get expanded. For details of | |
2485 | the semantic rules, see PEP-215: |
|
2480 | the semantic rules, see PEP-215: | |
2486 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2481 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2487 | IPython for variable expansion. If you want to access a true shell |
|
2482 | IPython for variable expansion. If you want to access a true shell | |
2488 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2483 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2489 |
|
2484 | |||
2490 | In [6]: alias show echo |
|
2485 | In [6]: alias show echo | |
2491 | In [7]: PATH='A Python string' |
|
2486 | In [7]: PATH='A Python string' | |
2492 | In [8]: show $PATH |
|
2487 | In [8]: show $PATH | |
2493 | A Python string |
|
2488 | A Python string | |
2494 | In [9]: show $$PATH |
|
2489 | In [9]: show $$PATH | |
2495 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2490 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2496 |
|
2491 | |||
2497 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2492 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2498 | and %rehashx functions, which automatically create aliases for the |
|
2493 | and %rehashx functions, which automatically create aliases for the | |
2499 | contents of your $PATH. |
|
2494 | contents of your $PATH. | |
2500 |
|
2495 | |||
2501 | If called with no parameters, %alias prints the current alias table.""" |
|
2496 | If called with no parameters, %alias prints the current alias table.""" | |
2502 |
|
2497 | |||
2503 | par = parameter_s.strip() |
|
2498 | par = parameter_s.strip() | |
2504 | if not par: |
|
2499 | if not par: | |
2505 | stored = self.db.get('stored_aliases', {} ) |
|
2500 | stored = self.db.get('stored_aliases', {} ) | |
2506 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2501 | aliases = sorted(self.shell.alias_manager.aliases) | |
2507 | # for k, v in stored: |
|
2502 | # for k, v in stored: | |
2508 | # atab.append(k, v[0]) |
|
2503 | # atab.append(k, v[0]) | |
2509 |
|
2504 | |||
2510 | print "Total number of aliases:", len(aliases) |
|
2505 | print "Total number of aliases:", len(aliases) | |
2511 | sys.stdout.flush() |
|
2506 | sys.stdout.flush() | |
2512 | return aliases |
|
2507 | return aliases | |
2513 |
|
2508 | |||
2514 | # Now try to define a new one |
|
2509 | # Now try to define a new one | |
2515 | try: |
|
2510 | try: | |
2516 | alias,cmd = par.split(None, 1) |
|
2511 | alias,cmd = par.split(None, 1) | |
2517 | except: |
|
2512 | except: | |
2518 | print oinspect.getdoc(self.magic_alias) |
|
2513 | print oinspect.getdoc(self.magic_alias) | |
2519 | else: |
|
2514 | else: | |
2520 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2515 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2521 | # end magic_alias |
|
2516 | # end magic_alias | |
2522 |
|
2517 | |||
2523 | def magic_unalias(self, parameter_s = ''): |
|
2518 | def magic_unalias(self, parameter_s = ''): | |
2524 | """Remove an alias""" |
|
2519 | """Remove an alias""" | |
2525 |
|
2520 | |||
2526 | aname = parameter_s.strip() |
|
2521 | aname = parameter_s.strip() | |
2527 | self.shell.alias_manager.undefine_alias(aname) |
|
2522 | self.shell.alias_manager.undefine_alias(aname) | |
2528 | stored = self.db.get('stored_aliases', {} ) |
|
2523 | stored = self.db.get('stored_aliases', {} ) | |
2529 | if aname in stored: |
|
2524 | if aname in stored: | |
2530 | print "Removing %stored alias",aname |
|
2525 | print "Removing %stored alias",aname | |
2531 | del stored[aname] |
|
2526 | del stored[aname] | |
2532 | self.db['stored_aliases'] = stored |
|
2527 | self.db['stored_aliases'] = stored | |
2533 |
|
2528 | |||
2534 | def magic_rehashx(self, parameter_s = ''): |
|
2529 | def magic_rehashx(self, parameter_s = ''): | |
2535 | """Update the alias table with all executable files in $PATH. |
|
2530 | """Update the alias table with all executable files in $PATH. | |
2536 |
|
2531 | |||
2537 | This version explicitly checks that every entry in $PATH is a file |
|
2532 | This version explicitly checks that every entry in $PATH is a file | |
2538 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2533 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2539 |
|
2534 | |||
2540 | Under Windows, it checks executability as a match agains a |
|
2535 | Under Windows, it checks executability as a match agains a | |
2541 | '|'-separated string of extensions, stored in the IPython config |
|
2536 | '|'-separated string of extensions, stored in the IPython config | |
2542 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2543 |
|
2538 | |||
2544 | This function also resets the root module cache of module completer, |
|
2539 | This function also resets the root module cache of module completer, | |
2545 | used on slow filesystems. |
|
2540 | used on slow filesystems. | |
2546 | """ |
|
2541 | """ | |
2547 | from IPython.core.alias import InvalidAliasError |
|
2542 | from IPython.core.alias import InvalidAliasError | |
2548 |
|
2543 | |||
2549 | # for the benefit of module completer in ipy_completers.py |
|
2544 | # for the benefit of module completer in ipy_completers.py | |
2550 | del self.db['rootmodules'] |
|
2545 | del self.db['rootmodules'] | |
2551 |
|
2546 | |||
2552 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2547 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2553 | os.environ.get('PATH','').split(os.pathsep)] |
|
2548 | os.environ.get('PATH','').split(os.pathsep)] | |
2554 | path = filter(os.path.isdir,path) |
|
2549 | path = filter(os.path.isdir,path) | |
2555 |
|
2550 | |||
2556 | syscmdlist = [] |
|
2551 | syscmdlist = [] | |
2557 | # Now define isexec in a cross platform manner. |
|
2552 | # Now define isexec in a cross platform manner. | |
2558 | if os.name == 'posix': |
|
2553 | if os.name == 'posix': | |
2559 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2554 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2560 | os.access(fname,os.X_OK) |
|
2555 | os.access(fname,os.X_OK) | |
2561 | else: |
|
2556 | else: | |
2562 | try: |
|
2557 | try: | |
2563 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2558 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2564 | except KeyError: |
|
2559 | except KeyError: | |
2565 | winext = 'exe|com|bat|py' |
|
2560 | winext = 'exe|com|bat|py' | |
2566 | if 'py' not in winext: |
|
2561 | if 'py' not in winext: | |
2567 | winext += '|py' |
|
2562 | winext += '|py' | |
2568 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2563 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2569 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2564 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2570 | savedir = os.getcwd() |
|
2565 | savedir = os.getcwd() | |
2571 |
|
2566 | |||
2572 | # Now walk the paths looking for executables to alias. |
|
2567 | # Now walk the paths looking for executables to alias. | |
2573 | try: |
|
2568 | try: | |
2574 | # write the whole loop for posix/Windows so we don't have an if in |
|
2569 | # write the whole loop for posix/Windows so we don't have an if in | |
2575 | # the innermost part |
|
2570 | # the innermost part | |
2576 | if os.name == 'posix': |
|
2571 | if os.name == 'posix': | |
2577 | for pdir in path: |
|
2572 | for pdir in path: | |
2578 | os.chdir(pdir) |
|
2573 | os.chdir(pdir) | |
2579 | for ff in os.listdir(pdir): |
|
2574 | for ff in os.listdir(pdir): | |
2580 | if isexec(ff): |
|
2575 | if isexec(ff): | |
2581 | try: |
|
2576 | try: | |
2582 | # Removes dots from the name since ipython |
|
2577 | # Removes dots from the name since ipython | |
2583 | # will assume names with dots to be python. |
|
2578 | # will assume names with dots to be python. | |
2584 | self.shell.alias_manager.define_alias( |
|
2579 | self.shell.alias_manager.define_alias( | |
2585 | ff.replace('.',''), ff) |
|
2580 | ff.replace('.',''), ff) | |
2586 | except InvalidAliasError: |
|
2581 | except InvalidAliasError: | |
2587 | pass |
|
2582 | pass | |
2588 | else: |
|
2583 | else: | |
2589 | syscmdlist.append(ff) |
|
2584 | syscmdlist.append(ff) | |
2590 | else: |
|
2585 | else: | |
2591 | no_alias = self.shell.alias_manager.no_alias |
|
2586 | no_alias = self.shell.alias_manager.no_alias | |
2592 | for pdir in path: |
|
2587 | for pdir in path: | |
2593 | os.chdir(pdir) |
|
2588 | os.chdir(pdir) | |
2594 | for ff in os.listdir(pdir): |
|
2589 | for ff in os.listdir(pdir): | |
2595 | base, ext = os.path.splitext(ff) |
|
2590 | base, ext = os.path.splitext(ff) | |
2596 | if isexec(ff) and base.lower() not in no_alias: |
|
2591 | if isexec(ff) and base.lower() not in no_alias: | |
2597 | if ext.lower() == '.exe': |
|
2592 | if ext.lower() == '.exe': | |
2598 | ff = base |
|
2593 | ff = base | |
2599 | try: |
|
2594 | try: | |
2600 | # Removes dots from the name since ipython |
|
2595 | # Removes dots from the name since ipython | |
2601 | # will assume names with dots to be python. |
|
2596 | # will assume names with dots to be python. | |
2602 | self.shell.alias_manager.define_alias( |
|
2597 | self.shell.alias_manager.define_alias( | |
2603 | base.lower().replace('.',''), ff) |
|
2598 | base.lower().replace('.',''), ff) | |
2604 | except InvalidAliasError: |
|
2599 | except InvalidAliasError: | |
2605 | pass |
|
2600 | pass | |
2606 | syscmdlist.append(ff) |
|
2601 | syscmdlist.append(ff) | |
2607 | db = self.db |
|
2602 | db = self.db | |
2608 | db['syscmdlist'] = syscmdlist |
|
2603 | db['syscmdlist'] = syscmdlist | |
2609 | finally: |
|
2604 | finally: | |
2610 | os.chdir(savedir) |
|
2605 | os.chdir(savedir) | |
2611 |
|
2606 | |||
2612 | def magic_pwd(self, parameter_s = ''): |
|
2607 | def magic_pwd(self, parameter_s = ''): | |
2613 | """Return the current working directory path.""" |
|
2608 | """Return the current working directory path.""" | |
2614 | return os.getcwd() |
|
2609 | return os.getcwd() | |
2615 |
|
2610 | |||
2616 | def magic_cd(self, parameter_s=''): |
|
2611 | def magic_cd(self, parameter_s=''): | |
2617 | """Change the current working directory. |
|
2612 | """Change the current working directory. | |
2618 |
|
2613 | |||
2619 | This command automatically maintains an internal list of directories |
|
2614 | This command automatically maintains an internal list of directories | |
2620 | you visit during your IPython session, in the variable _dh. The |
|
2615 | you visit during your IPython session, in the variable _dh. The | |
2621 | command %dhist shows this history nicely formatted. You can also |
|
2616 | command %dhist shows this history nicely formatted. You can also | |
2622 | do 'cd -<tab>' to see directory history conveniently. |
|
2617 | do 'cd -<tab>' to see directory history conveniently. | |
2623 |
|
2618 | |||
2624 | Usage: |
|
2619 | Usage: | |
2625 |
|
2620 | |||
2626 | cd 'dir': changes to directory 'dir'. |
|
2621 | cd 'dir': changes to directory 'dir'. | |
2627 |
|
2622 | |||
2628 | cd -: changes to the last visited directory. |
|
2623 | cd -: changes to the last visited directory. | |
2629 |
|
2624 | |||
2630 | cd -<n>: changes to the n-th directory in the directory history. |
|
2625 | cd -<n>: changes to the n-th directory in the directory history. | |
2631 |
|
2626 | |||
2632 | cd --foo: change to directory that matches 'foo' in history |
|
2627 | cd --foo: change to directory that matches 'foo' in history | |
2633 |
|
2628 | |||
2634 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2629 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2635 | (note: cd <bookmark_name> is enough if there is no |
|
2630 | (note: cd <bookmark_name> is enough if there is no | |
2636 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2631 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2637 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2632 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2638 |
|
2633 | |||
2639 | Options: |
|
2634 | Options: | |
2640 |
|
2635 | |||
2641 | -q: quiet. Do not print the working directory after the cd command is |
|
2636 | -q: quiet. Do not print the working directory after the cd command is | |
2642 | executed. By default IPython's cd command does print this directory, |
|
2637 | executed. By default IPython's cd command does print this directory, | |
2643 | since the default prompts do not display path information. |
|
2638 | since the default prompts do not display path information. | |
2644 |
|
2639 | |||
2645 | Note that !cd doesn't work for this purpose because the shell where |
|
2640 | Note that !cd doesn't work for this purpose because the shell where | |
2646 | !command runs is immediately discarded after executing 'command'.""" |
|
2641 | !command runs is immediately discarded after executing 'command'.""" | |
2647 |
|
2642 | |||
2648 | parameter_s = parameter_s.strip() |
|
2643 | parameter_s = parameter_s.strip() | |
2649 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2644 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2650 |
|
2645 | |||
2651 | oldcwd = os.getcwd() |
|
2646 | oldcwd = os.getcwd() | |
2652 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2647 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2653 | # jump in directory history by number |
|
2648 | # jump in directory history by number | |
2654 | if numcd: |
|
2649 | if numcd: | |
2655 | nn = int(numcd.group(2)) |
|
2650 | nn = int(numcd.group(2)) | |
2656 | try: |
|
2651 | try: | |
2657 | ps = self.shell.user_ns['_dh'][nn] |
|
2652 | ps = self.shell.user_ns['_dh'][nn] | |
2658 | except IndexError: |
|
2653 | except IndexError: | |
2659 | print 'The requested directory does not exist in history.' |
|
2654 | print 'The requested directory does not exist in history.' | |
2660 | return |
|
2655 | return | |
2661 | else: |
|
2656 | else: | |
2662 | opts = {} |
|
2657 | opts = {} | |
2663 | elif parameter_s.startswith('--'): |
|
2658 | elif parameter_s.startswith('--'): | |
2664 | ps = None |
|
2659 | ps = None | |
2665 | fallback = None |
|
2660 | fallback = None | |
2666 | pat = parameter_s[2:] |
|
2661 | pat = parameter_s[2:] | |
2667 | dh = self.shell.user_ns['_dh'] |
|
2662 | dh = self.shell.user_ns['_dh'] | |
2668 | # first search only by basename (last component) |
|
2663 | # first search only by basename (last component) | |
2669 | for ent in reversed(dh): |
|
2664 | for ent in reversed(dh): | |
2670 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2665 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2671 | ps = ent |
|
2666 | ps = ent | |
2672 | break |
|
2667 | break | |
2673 |
|
2668 | |||
2674 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2669 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2675 | fallback = ent |
|
2670 | fallback = ent | |
2676 |
|
2671 | |||
2677 | # if we have no last part match, pick the first full path match |
|
2672 | # if we have no last part match, pick the first full path match | |
2678 | if ps is None: |
|
2673 | if ps is None: | |
2679 | ps = fallback |
|
2674 | ps = fallback | |
2680 |
|
2675 | |||
2681 | if ps is None: |
|
2676 | if ps is None: | |
2682 | print "No matching entry in directory history" |
|
2677 | print "No matching entry in directory history" | |
2683 | return |
|
2678 | return | |
2684 | else: |
|
2679 | else: | |
2685 | opts = {} |
|
2680 | opts = {} | |
2686 |
|
2681 | |||
2687 |
|
2682 | |||
2688 | else: |
|
2683 | else: | |
2689 | #turn all non-space-escaping backslashes to slashes, |
|
2684 | #turn all non-space-escaping backslashes to slashes, | |
2690 | # for c:\windows\directory\names\ |
|
2685 | # for c:\windows\directory\names\ | |
2691 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2686 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2692 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2687 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2693 | # jump to previous |
|
2688 | # jump to previous | |
2694 | if ps == '-': |
|
2689 | if ps == '-': | |
2695 | try: |
|
2690 | try: | |
2696 | ps = self.shell.user_ns['_dh'][-2] |
|
2691 | ps = self.shell.user_ns['_dh'][-2] | |
2697 | except IndexError: |
|
2692 | except IndexError: | |
2698 | raise UsageError('%cd -: No previous directory to change to.') |
|
2693 | raise UsageError('%cd -: No previous directory to change to.') | |
2699 | # jump to bookmark if needed |
|
2694 | # jump to bookmark if needed | |
2700 | else: |
|
2695 | else: | |
2701 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2696 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2702 | bkms = self.db.get('bookmarks', {}) |
|
2697 | bkms = self.db.get('bookmarks', {}) | |
2703 |
|
2698 | |||
2704 | if bkms.has_key(ps): |
|
2699 | if bkms.has_key(ps): | |
2705 | target = bkms[ps] |
|
2700 | target = bkms[ps] | |
2706 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2701 | print '(bookmark:%s) -> %s' % (ps,target) | |
2707 | ps = target |
|
2702 | ps = target | |
2708 | else: |
|
2703 | else: | |
2709 | if opts.has_key('b'): |
|
2704 | if opts.has_key('b'): | |
2710 | raise UsageError("Bookmark '%s' not found. " |
|
2705 | raise UsageError("Bookmark '%s' not found. " | |
2711 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2706 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2712 |
|
2707 | |||
2713 | # at this point ps should point to the target dir |
|
2708 | # at this point ps should point to the target dir | |
2714 | if ps: |
|
2709 | if ps: | |
2715 | try: |
|
2710 | try: | |
2716 | os.chdir(os.path.expanduser(ps)) |
|
2711 | os.chdir(os.path.expanduser(ps)) | |
2717 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2712 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2718 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2713 | set_term_title('IPython: ' + abbrev_cwd()) | |
2719 | except OSError: |
|
2714 | except OSError: | |
2720 | print sys.exc_info()[1] |
|
2715 | print sys.exc_info()[1] | |
2721 | else: |
|
2716 | else: | |
2722 | cwd = os.getcwd() |
|
2717 | cwd = os.getcwd() | |
2723 | dhist = self.shell.user_ns['_dh'] |
|
2718 | dhist = self.shell.user_ns['_dh'] | |
2724 | if oldcwd != cwd: |
|
2719 | if oldcwd != cwd: | |
2725 | dhist.append(cwd) |
|
2720 | dhist.append(cwd) | |
2726 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2721 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2727 |
|
2722 | |||
2728 | else: |
|
2723 | else: | |
2729 | os.chdir(self.shell.home_dir) |
|
2724 | os.chdir(self.shell.home_dir) | |
2730 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2725 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2731 | set_term_title('IPython: ' + '~') |
|
2726 | set_term_title('IPython: ' + '~') | |
2732 | cwd = os.getcwd() |
|
2727 | cwd = os.getcwd() | |
2733 | dhist = self.shell.user_ns['_dh'] |
|
2728 | dhist = self.shell.user_ns['_dh'] | |
2734 |
|
2729 | |||
2735 | if oldcwd != cwd: |
|
2730 | if oldcwd != cwd: | |
2736 | dhist.append(cwd) |
|
2731 | dhist.append(cwd) | |
2737 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2732 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2738 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2733 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2739 | print self.shell.user_ns['_dh'][-1] |
|
2734 | print self.shell.user_ns['_dh'][-1] | |
2740 |
|
2735 | |||
2741 |
|
2736 | |||
2742 | def magic_env(self, parameter_s=''): |
|
2737 | def magic_env(self, parameter_s=''): | |
2743 | """List environment variables.""" |
|
2738 | """List environment variables.""" | |
2744 |
|
2739 | |||
2745 | return os.environ.data |
|
2740 | return os.environ.data | |
2746 |
|
2741 | |||
2747 | def magic_pushd(self, parameter_s=''): |
|
2742 | def magic_pushd(self, parameter_s=''): | |
2748 | """Place the current dir on stack and change directory. |
|
2743 | """Place the current dir on stack and change directory. | |
2749 |
|
2744 | |||
2750 | Usage:\\ |
|
2745 | Usage:\\ | |
2751 | %pushd ['dirname'] |
|
2746 | %pushd ['dirname'] | |
2752 | """ |
|
2747 | """ | |
2753 |
|
2748 | |||
2754 | dir_s = self.shell.dir_stack |
|
2749 | dir_s = self.shell.dir_stack | |
2755 | tgt = os.path.expanduser(parameter_s) |
|
2750 | tgt = os.path.expanduser(parameter_s) | |
2756 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2751 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2757 | if tgt: |
|
2752 | if tgt: | |
2758 | self.magic_cd(parameter_s) |
|
2753 | self.magic_cd(parameter_s) | |
2759 | dir_s.insert(0,cwd) |
|
2754 | dir_s.insert(0,cwd) | |
2760 | return self.magic_dirs() |
|
2755 | return self.magic_dirs() | |
2761 |
|
2756 | |||
2762 | def magic_popd(self, parameter_s=''): |
|
2757 | def magic_popd(self, parameter_s=''): | |
2763 | """Change to directory popped off the top of the stack. |
|
2758 | """Change to directory popped off the top of the stack. | |
2764 | """ |
|
2759 | """ | |
2765 | if not self.shell.dir_stack: |
|
2760 | if not self.shell.dir_stack: | |
2766 | raise UsageError("%popd on empty stack") |
|
2761 | raise UsageError("%popd on empty stack") | |
2767 | top = self.shell.dir_stack.pop(0) |
|
2762 | top = self.shell.dir_stack.pop(0) | |
2768 | self.magic_cd(top) |
|
2763 | self.magic_cd(top) | |
2769 | print "popd ->",top |
|
2764 | print "popd ->",top | |
2770 |
|
2765 | |||
2771 | def magic_dirs(self, parameter_s=''): |
|
2766 | def magic_dirs(self, parameter_s=''): | |
2772 | """Return the current directory stack.""" |
|
2767 | """Return the current directory stack.""" | |
2773 |
|
2768 | |||
2774 | return self.shell.dir_stack |
|
2769 | return self.shell.dir_stack | |
2775 |
|
2770 | |||
2776 | def magic_dhist(self, parameter_s=''): |
|
2771 | def magic_dhist(self, parameter_s=''): | |
2777 | """Print your history of visited directories. |
|
2772 | """Print your history of visited directories. | |
2778 |
|
2773 | |||
2779 | %dhist -> print full history\\ |
|
2774 | %dhist -> print full history\\ | |
2780 | %dhist n -> print last n entries only\\ |
|
2775 | %dhist n -> print last n entries only\\ | |
2781 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2776 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2782 |
|
2777 | |||
2783 | This history is automatically maintained by the %cd command, and |
|
2778 | This history is automatically maintained by the %cd command, and | |
2784 | always available as the global list variable _dh. You can use %cd -<n> |
|
2779 | always available as the global list variable _dh. You can use %cd -<n> | |
2785 | to go to directory number <n>. |
|
2780 | to go to directory number <n>. | |
2786 |
|
2781 | |||
2787 | Note that most of time, you should view directory history by entering |
|
2782 | Note that most of time, you should view directory history by entering | |
2788 | cd -<TAB>. |
|
2783 | cd -<TAB>. | |
2789 |
|
2784 | |||
2790 | """ |
|
2785 | """ | |
2791 |
|
2786 | |||
2792 | dh = self.shell.user_ns['_dh'] |
|
2787 | dh = self.shell.user_ns['_dh'] | |
2793 | if parameter_s: |
|
2788 | if parameter_s: | |
2794 | try: |
|
2789 | try: | |
2795 | args = map(int,parameter_s.split()) |
|
2790 | args = map(int,parameter_s.split()) | |
2796 | except: |
|
2791 | except: | |
2797 | self.arg_err(Magic.magic_dhist) |
|
2792 | self.arg_err(Magic.magic_dhist) | |
2798 | return |
|
2793 | return | |
2799 | if len(args) == 1: |
|
2794 | if len(args) == 1: | |
2800 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2795 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2801 | elif len(args) == 2: |
|
2796 | elif len(args) == 2: | |
2802 | ini,fin = args |
|
2797 | ini,fin = args | |
2803 | else: |
|
2798 | else: | |
2804 | self.arg_err(Magic.magic_dhist) |
|
2799 | self.arg_err(Magic.magic_dhist) | |
2805 | return |
|
2800 | return | |
2806 | else: |
|
2801 | else: | |
2807 | ini,fin = 0,len(dh) |
|
2802 | ini,fin = 0,len(dh) | |
2808 | nlprint(dh, |
|
2803 | nlprint(dh, | |
2809 | header = 'Directory history (kept in _dh)', |
|
2804 | header = 'Directory history (kept in _dh)', | |
2810 | start=ini,stop=fin) |
|
2805 | start=ini,stop=fin) | |
2811 |
|
2806 | |||
2812 | @testdec.skip_doctest |
|
2807 | @testdec.skip_doctest | |
2813 | def magic_sc(self, parameter_s=''): |
|
2808 | def magic_sc(self, parameter_s=''): | |
2814 | """Shell capture - execute a shell command and capture its output. |
|
2809 | """Shell capture - execute a shell command and capture its output. | |
2815 |
|
2810 | |||
2816 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2811 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2817 |
|
2812 | |||
2818 | You should use the form 'var = !command' instead. Example: |
|
2813 | You should use the form 'var = !command' instead. Example: | |
2819 |
|
2814 | |||
2820 | "%sc -l myfiles = ls ~" should now be written as |
|
2815 | "%sc -l myfiles = ls ~" should now be written as | |
2821 |
|
2816 | |||
2822 | "myfiles = !ls ~" |
|
2817 | "myfiles = !ls ~" | |
2823 |
|
2818 | |||
2824 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2819 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2825 | below. |
|
2820 | below. | |
2826 |
|
2821 | |||
2827 | -- |
|
2822 | -- | |
2828 | %sc [options] varname=command |
|
2823 | %sc [options] varname=command | |
2829 |
|
2824 | |||
2830 | IPython will run the given command using commands.getoutput(), and |
|
2825 | IPython will run the given command using commands.getoutput(), and | |
2831 | will then update the user's interactive namespace with a variable |
|
2826 | will then update the user's interactive namespace with a variable | |
2832 | called varname, containing the value of the call. Your command can |
|
2827 | called varname, containing the value of the call. Your command can | |
2833 | contain shell wildcards, pipes, etc. |
|
2828 | contain shell wildcards, pipes, etc. | |
2834 |
|
2829 | |||
2835 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2830 | The '=' sign in the syntax is mandatory, and the variable name you | |
2836 | supply must follow Python's standard conventions for valid names. |
|
2831 | supply must follow Python's standard conventions for valid names. | |
2837 |
|
2832 | |||
2838 | (A special format without variable name exists for internal use) |
|
2833 | (A special format without variable name exists for internal use) | |
2839 |
|
2834 | |||
2840 | Options: |
|
2835 | Options: | |
2841 |
|
2836 | |||
2842 | -l: list output. Split the output on newlines into a list before |
|
2837 | -l: list output. Split the output on newlines into a list before | |
2843 | assigning it to the given variable. By default the output is stored |
|
2838 | assigning it to the given variable. By default the output is stored | |
2844 | as a single string. |
|
2839 | as a single string. | |
2845 |
|
2840 | |||
2846 | -v: verbose. Print the contents of the variable. |
|
2841 | -v: verbose. Print the contents of the variable. | |
2847 |
|
2842 | |||
2848 | In most cases you should not need to split as a list, because the |
|
2843 | In most cases you should not need to split as a list, because the | |
2849 | returned value is a special type of string which can automatically |
|
2844 | returned value is a special type of string which can automatically | |
2850 | provide its contents either as a list (split on newlines) or as a |
|
2845 | provide its contents either as a list (split on newlines) or as a | |
2851 | space-separated string. These are convenient, respectively, either |
|
2846 | space-separated string. These are convenient, respectively, either | |
2852 | for sequential processing or to be passed to a shell command. |
|
2847 | for sequential processing or to be passed to a shell command. | |
2853 |
|
2848 | |||
2854 | For example: |
|
2849 | For example: | |
2855 |
|
2850 | |||
2856 | # all-random |
|
2851 | # all-random | |
2857 |
|
2852 | |||
2858 | # Capture into variable a |
|
2853 | # Capture into variable a | |
2859 | In [1]: sc a=ls *py |
|
2854 | In [1]: sc a=ls *py | |
2860 |
|
2855 | |||
2861 | # a is a string with embedded newlines |
|
2856 | # a is a string with embedded newlines | |
2862 | In [2]: a |
|
2857 | In [2]: a | |
2863 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2858 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2864 |
|
2859 | |||
2865 | # which can be seen as a list: |
|
2860 | # which can be seen as a list: | |
2866 | In [3]: a.l |
|
2861 | In [3]: a.l | |
2867 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2862 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2868 |
|
2863 | |||
2869 | # or as a whitespace-separated string: |
|
2864 | # or as a whitespace-separated string: | |
2870 | In [4]: a.s |
|
2865 | In [4]: a.s | |
2871 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2866 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2872 |
|
2867 | |||
2873 | # a.s is useful to pass as a single command line: |
|
2868 | # a.s is useful to pass as a single command line: | |
2874 | In [5]: !wc -l $a.s |
|
2869 | In [5]: !wc -l $a.s | |
2875 | 146 setup.py |
|
2870 | 146 setup.py | |
2876 | 130 win32_manual_post_install.py |
|
2871 | 130 win32_manual_post_install.py | |
2877 | 276 total |
|
2872 | 276 total | |
2878 |
|
2873 | |||
2879 | # while the list form is useful to loop over: |
|
2874 | # while the list form is useful to loop over: | |
2880 | In [6]: for f in a.l: |
|
2875 | In [6]: for f in a.l: | |
2881 | ...: !wc -l $f |
|
2876 | ...: !wc -l $f | |
2882 | ...: |
|
2877 | ...: | |
2883 | 146 setup.py |
|
2878 | 146 setup.py | |
2884 | 130 win32_manual_post_install.py |
|
2879 | 130 win32_manual_post_install.py | |
2885 |
|
2880 | |||
2886 | Similiarly, the lists returned by the -l option are also special, in |
|
2881 | Similiarly, the lists returned by the -l option are also special, in | |
2887 | the sense that you can equally invoke the .s attribute on them to |
|
2882 | the sense that you can equally invoke the .s attribute on them to | |
2888 | automatically get a whitespace-separated string from their contents: |
|
2883 | automatically get a whitespace-separated string from their contents: | |
2889 |
|
2884 | |||
2890 | In [7]: sc -l b=ls *py |
|
2885 | In [7]: sc -l b=ls *py | |
2891 |
|
2886 | |||
2892 | In [8]: b |
|
2887 | In [8]: b | |
2893 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2888 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2894 |
|
2889 | |||
2895 | In [9]: b.s |
|
2890 | In [9]: b.s | |
2896 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2891 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2897 |
|
2892 | |||
2898 | In summary, both the lists and strings used for ouptut capture have |
|
2893 | In summary, both the lists and strings used for ouptut capture have | |
2899 | the following special attributes: |
|
2894 | the following special attributes: | |
2900 |
|
2895 | |||
2901 | .l (or .list) : value as list. |
|
2896 | .l (or .list) : value as list. | |
2902 | .n (or .nlstr): value as newline-separated string. |
|
2897 | .n (or .nlstr): value as newline-separated string. | |
2903 | .s (or .spstr): value as space-separated string. |
|
2898 | .s (or .spstr): value as space-separated string. | |
2904 | """ |
|
2899 | """ | |
2905 |
|
2900 | |||
2906 | opts,args = self.parse_options(parameter_s,'lv') |
|
2901 | opts,args = self.parse_options(parameter_s,'lv') | |
2907 | # Try to get a variable name and command to run |
|
2902 | # Try to get a variable name and command to run | |
2908 | try: |
|
2903 | try: | |
2909 | # the variable name must be obtained from the parse_options |
|
2904 | # the variable name must be obtained from the parse_options | |
2910 | # output, which uses shlex.split to strip options out. |
|
2905 | # output, which uses shlex.split to strip options out. | |
2911 | var,_ = args.split('=',1) |
|
2906 | var,_ = args.split('=',1) | |
2912 | var = var.strip() |
|
2907 | var = var.strip() | |
2913 | # But the the command has to be extracted from the original input |
|
2908 | # But the the command has to be extracted from the original input | |
2914 | # parameter_s, not on what parse_options returns, to avoid the |
|
2909 | # parameter_s, not on what parse_options returns, to avoid the | |
2915 | # quote stripping which shlex.split performs on it. |
|
2910 | # quote stripping which shlex.split performs on it. | |
2916 | _,cmd = parameter_s.split('=',1) |
|
2911 | _,cmd = parameter_s.split('=',1) | |
2917 | except ValueError: |
|
2912 | except ValueError: | |
2918 | var,cmd = '','' |
|
2913 | var,cmd = '','' | |
2919 | # If all looks ok, proceed |
|
2914 | # If all looks ok, proceed | |
2920 | split = 'l' in opts |
|
2915 | split = 'l' in opts | |
2921 | out = self.shell.getoutput(cmd, split=split) |
|
2916 | out = self.shell.getoutput(cmd, split=split) | |
2922 | if opts.has_key('v'): |
|
2917 | if opts.has_key('v'): | |
2923 | print '%s ==\n%s' % (var,pformat(out)) |
|
2918 | print '%s ==\n%s' % (var,pformat(out)) | |
2924 | if var: |
|
2919 | if var: | |
2925 | self.shell.user_ns.update({var:out}) |
|
2920 | self.shell.user_ns.update({var:out}) | |
2926 | else: |
|
2921 | else: | |
2927 | return out |
|
2922 | return out | |
2928 |
|
2923 | |||
2929 | def magic_sx(self, parameter_s=''): |
|
2924 | def magic_sx(self, parameter_s=''): | |
2930 | """Shell execute - run a shell command and capture its output. |
|
2925 | """Shell execute - run a shell command and capture its output. | |
2931 |
|
2926 | |||
2932 | %sx command |
|
2927 | %sx command | |
2933 |
|
2928 | |||
2934 | IPython will run the given command using commands.getoutput(), and |
|
2929 | IPython will run the given command using commands.getoutput(), and | |
2935 | return the result formatted as a list (split on '\\n'). Since the |
|
2930 | return the result formatted as a list (split on '\\n'). Since the | |
2936 | output is _returned_, it will be stored in ipython's regular output |
|
2931 | output is _returned_, it will be stored in ipython's regular output | |
2937 | cache Out[N] and in the '_N' automatic variables. |
|
2932 | cache Out[N] and in the '_N' automatic variables. | |
2938 |
|
2933 | |||
2939 | Notes: |
|
2934 | Notes: | |
2940 |
|
2935 | |||
2941 | 1) If an input line begins with '!!', then %sx is automatically |
|
2936 | 1) If an input line begins with '!!', then %sx is automatically | |
2942 | invoked. That is, while: |
|
2937 | invoked. That is, while: | |
2943 | !ls |
|
2938 | !ls | |
2944 | causes ipython to simply issue system('ls'), typing |
|
2939 | causes ipython to simply issue system('ls'), typing | |
2945 | !!ls |
|
2940 | !!ls | |
2946 | is a shorthand equivalent to: |
|
2941 | is a shorthand equivalent to: | |
2947 | %sx ls |
|
2942 | %sx ls | |
2948 |
|
2943 | |||
2949 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2950 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2945 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2951 | to process line-oriented shell output via further python commands. |
|
2946 | to process line-oriented shell output via further python commands. | |
2952 | %sc is meant to provide much finer control, but requires more |
|
2947 | %sc is meant to provide much finer control, but requires more | |
2953 | typing. |
|
2948 | typing. | |
2954 |
|
2949 | |||
2955 | 3) Just like %sc -l, this is a list with special attributes: |
|
2950 | 3) Just like %sc -l, this is a list with special attributes: | |
2956 |
|
2951 | |||
2957 | .l (or .list) : value as list. |
|
2952 | .l (or .list) : value as list. | |
2958 | .n (or .nlstr): value as newline-separated string. |
|
2953 | .n (or .nlstr): value as newline-separated string. | |
2959 | .s (or .spstr): value as whitespace-separated string. |
|
2954 | .s (or .spstr): value as whitespace-separated string. | |
2960 |
|
2955 | |||
2961 | This is very useful when trying to use such lists as arguments to |
|
2956 | This is very useful when trying to use such lists as arguments to | |
2962 | system commands.""" |
|
2957 | system commands.""" | |
2963 |
|
2958 | |||
2964 | if parameter_s: |
|
2959 | if parameter_s: | |
2965 | return self.shell.getoutput(parameter_s) |
|
2960 | return self.shell.getoutput(parameter_s) | |
2966 |
|
2961 | |||
2967 | def magic_r(self, parameter_s=''): |
|
2962 | def magic_r(self, parameter_s=''): | |
2968 | """Repeat previous input. |
|
2963 | """Repeat previous input. | |
2969 |
|
2964 | |||
2970 | Note: Consider using the more powerfull %rep instead! |
|
2965 | Note: Consider using the more powerfull %rep instead! | |
2971 |
|
2966 | |||
2972 | If given an argument, repeats the previous command which starts with |
|
2967 | If given an argument, repeats the previous command which starts with | |
2973 | the same string, otherwise it just repeats the previous input. |
|
2968 | the same string, otherwise it just repeats the previous input. | |
2974 |
|
2969 | |||
2975 | Shell escaped commands (with ! as first character) are not recognized |
|
2970 | Shell escaped commands (with ! as first character) are not recognized | |
2976 | by this system, only pure python code and magic commands. |
|
2971 | by this system, only pure python code and magic commands. | |
2977 | """ |
|
2972 | """ | |
2978 |
|
2973 | |||
2979 | start = parameter_s.strip() |
|
2974 | start = parameter_s.strip() | |
2980 | esc_magic = ESC_MAGIC |
|
2975 | esc_magic = ESC_MAGIC | |
2981 | # Identify magic commands even if automagic is on (which means |
|
2976 | # Identify magic commands even if automagic is on (which means | |
2982 | # the in-memory version is different from that typed by the user). |
|
2977 | # the in-memory version is different from that typed by the user). | |
2983 | if self.shell.automagic: |
|
2978 | if self.shell.automagic: | |
2984 | start_magic = esc_magic+start |
|
2979 | start_magic = esc_magic+start | |
2985 | else: |
|
2980 | else: | |
2986 | start_magic = start |
|
2981 | start_magic = start | |
2987 | # Look through the input history in reverse |
|
2982 | # Look through the input history in reverse | |
2988 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
2983 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
2989 | input = self.shell.input_hist[n] |
|
2984 | input = self.shell.input_hist[n] | |
2990 | # skip plain 'r' lines so we don't recurse to infinity |
|
2985 | # skip plain 'r' lines so we don't recurse to infinity | |
2991 | if input != '_ip.magic("r")\n' and \ |
|
2986 | if input != '_ip.magic("r")\n' and \ | |
2992 | (input.startswith(start) or input.startswith(start_magic)): |
|
2987 | (input.startswith(start) or input.startswith(start_magic)): | |
2993 | #print 'match',`input` # dbg |
|
2988 | #print 'match',`input` # dbg | |
2994 | print 'Executing:',input, |
|
2989 | print 'Executing:',input, | |
2995 |
self.shell.run |
|
2990 | self.shell.run_cell(input) | |
2996 | return |
|
2991 | return | |
2997 | print 'No previous input matching `%s` found.' % start |
|
2992 | print 'No previous input matching `%s` found.' % start | |
2998 |
|
2993 | |||
2999 |
|
2994 | |||
3000 | def magic_bookmark(self, parameter_s=''): |
|
2995 | def magic_bookmark(self, parameter_s=''): | |
3001 | """Manage IPython's bookmark system. |
|
2996 | """Manage IPython's bookmark system. | |
3002 |
|
2997 | |||
3003 | %bookmark <name> - set bookmark to current dir |
|
2998 | %bookmark <name> - set bookmark to current dir | |
3004 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2999 | %bookmark <name> <dir> - set bookmark to <dir> | |
3005 | %bookmark -l - list all bookmarks |
|
3000 | %bookmark -l - list all bookmarks | |
3006 | %bookmark -d <name> - remove bookmark |
|
3001 | %bookmark -d <name> - remove bookmark | |
3007 | %bookmark -r - remove all bookmarks |
|
3002 | %bookmark -r - remove all bookmarks | |
3008 |
|
3003 | |||
3009 | You can later on access a bookmarked folder with: |
|
3004 | You can later on access a bookmarked folder with: | |
3010 | %cd -b <name> |
|
3005 | %cd -b <name> | |
3011 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3006 | or simply '%cd <name>' if there is no directory called <name> AND | |
3012 | there is such a bookmark defined. |
|
3007 | there is such a bookmark defined. | |
3013 |
|
3008 | |||
3014 | Your bookmarks persist through IPython sessions, but they are |
|
3009 | Your bookmarks persist through IPython sessions, but they are | |
3015 | associated with each profile.""" |
|
3010 | associated with each profile.""" | |
3016 |
|
3011 | |||
3017 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3012 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3018 | if len(args) > 2: |
|
3013 | if len(args) > 2: | |
3019 | raise UsageError("%bookmark: too many arguments") |
|
3014 | raise UsageError("%bookmark: too many arguments") | |
3020 |
|
3015 | |||
3021 | bkms = self.db.get('bookmarks',{}) |
|
3016 | bkms = self.db.get('bookmarks',{}) | |
3022 |
|
3017 | |||
3023 | if opts.has_key('d'): |
|
3018 | if opts.has_key('d'): | |
3024 | try: |
|
3019 | try: | |
3025 | todel = args[0] |
|
3020 | todel = args[0] | |
3026 | except IndexError: |
|
3021 | except IndexError: | |
3027 | raise UsageError( |
|
3022 | raise UsageError( | |
3028 | "%bookmark -d: must provide a bookmark to delete") |
|
3023 | "%bookmark -d: must provide a bookmark to delete") | |
3029 | else: |
|
3024 | else: | |
3030 | try: |
|
3025 | try: | |
3031 | del bkms[todel] |
|
3026 | del bkms[todel] | |
3032 | except KeyError: |
|
3027 | except KeyError: | |
3033 | raise UsageError( |
|
3028 | raise UsageError( | |
3034 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3029 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3035 |
|
3030 | |||
3036 | elif opts.has_key('r'): |
|
3031 | elif opts.has_key('r'): | |
3037 | bkms = {} |
|
3032 | bkms = {} | |
3038 | elif opts.has_key('l'): |
|
3033 | elif opts.has_key('l'): | |
3039 | bks = bkms.keys() |
|
3034 | bks = bkms.keys() | |
3040 | bks.sort() |
|
3035 | bks.sort() | |
3041 | if bks: |
|
3036 | if bks: | |
3042 | size = max(map(len,bks)) |
|
3037 | size = max(map(len,bks)) | |
3043 | else: |
|
3038 | else: | |
3044 | size = 0 |
|
3039 | size = 0 | |
3045 | fmt = '%-'+str(size)+'s -> %s' |
|
3040 | fmt = '%-'+str(size)+'s -> %s' | |
3046 | print 'Current bookmarks:' |
|
3041 | print 'Current bookmarks:' | |
3047 | for bk in bks: |
|
3042 | for bk in bks: | |
3048 | print fmt % (bk,bkms[bk]) |
|
3043 | print fmt % (bk,bkms[bk]) | |
3049 | else: |
|
3044 | else: | |
3050 | if not args: |
|
3045 | if not args: | |
3051 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3046 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3052 | elif len(args)==1: |
|
3047 | elif len(args)==1: | |
3053 | bkms[args[0]] = os.getcwd() |
|
3048 | bkms[args[0]] = os.getcwd() | |
3054 | elif len(args)==2: |
|
3049 | elif len(args)==2: | |
3055 | bkms[args[0]] = args[1] |
|
3050 | bkms[args[0]] = args[1] | |
3056 | self.db['bookmarks'] = bkms |
|
3051 | self.db['bookmarks'] = bkms | |
3057 |
|
3052 | |||
3058 | def magic_pycat(self, parameter_s=''): |
|
3053 | def magic_pycat(self, parameter_s=''): | |
3059 | """Show a syntax-highlighted file through a pager. |
|
3054 | """Show a syntax-highlighted file through a pager. | |
3060 |
|
3055 | |||
3061 | This magic is similar to the cat utility, but it will assume the file |
|
3056 | This magic is similar to the cat utility, but it will assume the file | |
3062 | to be Python source and will show it with syntax highlighting. """ |
|
3057 | to be Python source and will show it with syntax highlighting. """ | |
3063 |
|
3058 | |||
3064 | try: |
|
3059 | try: | |
3065 | filename = get_py_filename(parameter_s) |
|
3060 | filename = get_py_filename(parameter_s) | |
3066 | cont = file_read(filename) |
|
3061 | cont = file_read(filename) | |
3067 | except IOError: |
|
3062 | except IOError: | |
3068 | try: |
|
3063 | try: | |
3069 | cont = eval(parameter_s,self.user_ns) |
|
3064 | cont = eval(parameter_s,self.user_ns) | |
3070 | except NameError: |
|
3065 | except NameError: | |
3071 | cont = None |
|
3066 | cont = None | |
3072 | if cont is None: |
|
3067 | if cont is None: | |
3073 | print "Error: no such file or variable" |
|
3068 | print "Error: no such file or variable" | |
3074 | return |
|
3069 | return | |
3075 |
|
3070 | |||
3076 | page.page(self.shell.pycolorize(cont)) |
|
3071 | page.page(self.shell.pycolorize(cont)) | |
3077 |
|
3072 | |||
3078 | def _rerun_pasted(self): |
|
3073 | def _rerun_pasted(self): | |
3079 | """ Rerun a previously pasted command. |
|
3074 | """ Rerun a previously pasted command. | |
3080 | """ |
|
3075 | """ | |
3081 | b = self.user_ns.get('pasted_block', None) |
|
3076 | b = self.user_ns.get('pasted_block', None) | |
3082 | if b is None: |
|
3077 | if b is None: | |
3083 | raise UsageError('No previous pasted block available') |
|
3078 | raise UsageError('No previous pasted block available') | |
3084 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3079 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3085 | exec b in self.user_ns |
|
3080 | exec b in self.user_ns | |
3086 |
|
3081 | |||
3087 | def _get_pasted_lines(self, sentinel): |
|
3082 | def _get_pasted_lines(self, sentinel): | |
3088 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3083 | """ Yield pasted lines until the user enters the given sentinel value. | |
3089 | """ |
|
3084 | """ | |
3090 | from IPython.core import interactiveshell |
|
3085 | from IPython.core import interactiveshell | |
3091 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3086 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3092 | while True: |
|
3087 | while True: | |
3093 | l = interactiveshell.raw_input_original(':') |
|
3088 | l = interactiveshell.raw_input_original(':') | |
3094 | if l == sentinel: |
|
3089 | if l == sentinel: | |
3095 | return |
|
3090 | return | |
3096 | else: |
|
3091 | else: | |
3097 | yield l |
|
3092 | yield l | |
3098 |
|
3093 | |||
3099 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3094 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3100 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3095 | """ Strip non-code parts of a sequence of lines to return a block of | |
3101 | code. |
|
3096 | code. | |
3102 | """ |
|
3097 | """ | |
3103 | # Regular expressions that declare text we strip from the input: |
|
3098 | # Regular expressions that declare text we strip from the input: | |
3104 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3099 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3105 | r'^\s*(\s?>)+', # Python input prompt |
|
3100 | r'^\s*(\s?>)+', # Python input prompt | |
3106 | r'^\s*\.{3,}', # Continuation prompts |
|
3101 | r'^\s*\.{3,}', # Continuation prompts | |
3107 | r'^\++', |
|
3102 | r'^\++', | |
3108 | ] |
|
3103 | ] | |
3109 |
|
3104 | |||
3110 | strip_from_start = map(re.compile,strip_re) |
|
3105 | strip_from_start = map(re.compile,strip_re) | |
3111 |
|
3106 | |||
3112 | lines = [] |
|
3107 | lines = [] | |
3113 | for l in raw_lines: |
|
3108 | for l in raw_lines: | |
3114 | for pat in strip_from_start: |
|
3109 | for pat in strip_from_start: | |
3115 | l = pat.sub('',l) |
|
3110 | l = pat.sub('',l) | |
3116 | lines.append(l) |
|
3111 | lines.append(l) | |
3117 |
|
3112 | |||
3118 | block = "\n".join(lines) + '\n' |
|
3113 | block = "\n".join(lines) + '\n' | |
3119 | #print "block:\n",block |
|
3114 | #print "block:\n",block | |
3120 | return block |
|
3115 | return block | |
3121 |
|
3116 | |||
3122 | def _execute_block(self, block, par): |
|
3117 | def _execute_block(self, block, par): | |
3123 | """ Execute a block, or store it in a variable, per the user's request. |
|
3118 | """ Execute a block, or store it in a variable, per the user's request. | |
3124 | """ |
|
3119 | """ | |
3125 | if not par: |
|
3120 | if not par: | |
3126 | b = textwrap.dedent(block) |
|
3121 | b = textwrap.dedent(block) | |
3127 | self.user_ns['pasted_block'] = b |
|
3122 | self.user_ns['pasted_block'] = b | |
3128 | exec b in self.user_ns |
|
3123 | exec b in self.user_ns | |
3129 | else: |
|
3124 | else: | |
3130 | self.user_ns[par] = SList(block.splitlines()) |
|
3125 | self.user_ns[par] = SList(block.splitlines()) | |
3131 | print "Block assigned to '%s'" % par |
|
3126 | print "Block assigned to '%s'" % par | |
3132 |
|
3127 | |||
3133 | def magic_quickref(self,arg): |
|
3128 | def magic_quickref(self,arg): | |
3134 | """ Show a quick reference sheet """ |
|
3129 | """ Show a quick reference sheet """ | |
3135 | import IPython.core.usage |
|
3130 | import IPython.core.usage | |
3136 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3131 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3137 |
|
3132 | |||
3138 | page.page(qr) |
|
3133 | page.page(qr) | |
3139 |
|
3134 | |||
3140 | def magic_doctest_mode(self,parameter_s=''): |
|
3135 | def magic_doctest_mode(self,parameter_s=''): | |
3141 | """Toggle doctest mode on and off. |
|
3136 | """Toggle doctest mode on and off. | |
3142 |
|
3137 | |||
3143 | This mode is intended to make IPython behave as much as possible like a |
|
3138 | This mode is intended to make IPython behave as much as possible like a | |
3144 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3139 | plain Python shell, from the perspective of how its prompts, exceptions | |
3145 | and output look. This makes it easy to copy and paste parts of a |
|
3140 | and output look. This makes it easy to copy and paste parts of a | |
3146 | session into doctests. It does so by: |
|
3141 | session into doctests. It does so by: | |
3147 |
|
3142 | |||
3148 | - Changing the prompts to the classic ``>>>`` ones. |
|
3143 | - Changing the prompts to the classic ``>>>`` ones. | |
3149 | - Changing the exception reporting mode to 'Plain'. |
|
3144 | - Changing the exception reporting mode to 'Plain'. | |
3150 | - Disabling pretty-printing of output. |
|
3145 | - Disabling pretty-printing of output. | |
3151 |
|
3146 | |||
3152 | Note that IPython also supports the pasting of code snippets that have |
|
3147 | Note that IPython also supports the pasting of code snippets that have | |
3153 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3148 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3154 | doctests from files or docstrings (even if they have leading |
|
3149 | doctests from files or docstrings (even if they have leading | |
3155 | whitespace), and the code will execute correctly. You can then use |
|
3150 | whitespace), and the code will execute correctly. You can then use | |
3156 | '%history -t' to see the translated history; this will give you the |
|
3151 | '%history -t' to see the translated history; this will give you the | |
3157 | input after removal of all the leading prompts and whitespace, which |
|
3152 | input after removal of all the leading prompts and whitespace, which | |
3158 | can be pasted back into an editor. |
|
3153 | can be pasted back into an editor. | |
3159 |
|
3154 | |||
3160 | With these features, you can switch into this mode easily whenever you |
|
3155 | With these features, you can switch into this mode easily whenever you | |
3161 | need to do testing and changes to doctests, without having to leave |
|
3156 | need to do testing and changes to doctests, without having to leave | |
3162 | your existing IPython session. |
|
3157 | your existing IPython session. | |
3163 | """ |
|
3158 | """ | |
3164 |
|
3159 | |||
3165 | from IPython.utils.ipstruct import Struct |
|
3160 | from IPython.utils.ipstruct import Struct | |
3166 |
|
3161 | |||
3167 | # Shorthands |
|
3162 | # Shorthands | |
3168 | shell = self.shell |
|
3163 | shell = self.shell | |
3169 | oc = shell.displayhook |
|
3164 | oc = shell.displayhook | |
3170 | meta = shell.meta |
|
3165 | meta = shell.meta | |
3171 | # dstore is a data store kept in the instance metadata bag to track any |
|
3166 | # dstore is a data store kept in the instance metadata bag to track any | |
3172 | # changes we make, so we can undo them later. |
|
3167 | # changes we make, so we can undo them later. | |
3173 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3168 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3174 | save_dstore = dstore.setdefault |
|
3169 | save_dstore = dstore.setdefault | |
3175 |
|
3170 | |||
3176 | # save a few values we'll need to recover later |
|
3171 | # save a few values we'll need to recover later | |
3177 | mode = save_dstore('mode',False) |
|
3172 | mode = save_dstore('mode',False) | |
3178 | save_dstore('rc_pprint',shell.pprint) |
|
3173 | save_dstore('rc_pprint',shell.pprint) | |
3179 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3174 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3180 | save_dstore('rc_separate_out',shell.separate_out) |
|
3175 | save_dstore('rc_separate_out',shell.separate_out) | |
3181 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3176 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3182 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3177 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3183 | save_dstore('rc_separate_in',shell.separate_in) |
|
3178 | save_dstore('rc_separate_in',shell.separate_in) | |
3184 |
|
3179 | |||
3185 | if mode == False: |
|
3180 | if mode == False: | |
3186 | # turn on |
|
3181 | # turn on | |
3187 | oc.prompt1.p_template = '>>> ' |
|
3182 | oc.prompt1.p_template = '>>> ' | |
3188 | oc.prompt2.p_template = '... ' |
|
3183 | oc.prompt2.p_template = '... ' | |
3189 | oc.prompt_out.p_template = '' |
|
3184 | oc.prompt_out.p_template = '' | |
3190 |
|
3185 | |||
3191 | # Prompt separators like plain python |
|
3186 | # Prompt separators like plain python | |
3192 | oc.input_sep = oc.prompt1.sep = '' |
|
3187 | oc.input_sep = oc.prompt1.sep = '' | |
3193 | oc.output_sep = '' |
|
3188 | oc.output_sep = '' | |
3194 | oc.output_sep2 = '' |
|
3189 | oc.output_sep2 = '' | |
3195 |
|
3190 | |||
3196 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3191 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3197 | oc.prompt_out.pad_left = False |
|
3192 | oc.prompt_out.pad_left = False | |
3198 |
|
3193 | |||
3199 | shell.pprint = False |
|
3194 | shell.pprint = False | |
3200 |
|
3195 | |||
3201 | shell.magic_xmode('Plain') |
|
3196 | shell.magic_xmode('Plain') | |
3202 | else: |
|
3197 | else: | |
3203 | # turn off |
|
3198 | # turn off | |
3204 | oc.prompt1.p_template = shell.prompt_in1 |
|
3199 | oc.prompt1.p_template = shell.prompt_in1 | |
3205 | oc.prompt2.p_template = shell.prompt_in2 |
|
3200 | oc.prompt2.p_template = shell.prompt_in2 | |
3206 | oc.prompt_out.p_template = shell.prompt_out |
|
3201 | oc.prompt_out.p_template = shell.prompt_out | |
3207 |
|
3202 | |||
3208 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3203 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3209 |
|
3204 | |||
3210 | oc.output_sep = dstore.rc_separate_out |
|
3205 | oc.output_sep = dstore.rc_separate_out | |
3211 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3206 | oc.output_sep2 = dstore.rc_separate_out2 | |
3212 |
|
3207 | |||
3213 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3208 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3214 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3209 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3215 |
|
3210 | |||
3216 | shell.pprint = dstore.rc_pprint |
|
3211 | shell.pprint = dstore.rc_pprint | |
3217 |
|
3212 | |||
3218 | shell.magic_xmode(dstore.xmode) |
|
3213 | shell.magic_xmode(dstore.xmode) | |
3219 |
|
3214 | |||
3220 | # Store new mode and inform |
|
3215 | # Store new mode and inform | |
3221 | dstore.mode = bool(1-int(mode)) |
|
3216 | dstore.mode = bool(1-int(mode)) | |
3222 | mode_label = ['OFF','ON'][dstore.mode] |
|
3217 | mode_label = ['OFF','ON'][dstore.mode] | |
3223 | print 'Doctest mode is:', mode_label |
|
3218 | print 'Doctest mode is:', mode_label | |
3224 |
|
3219 | |||
3225 | def magic_gui(self, parameter_s=''): |
|
3220 | def magic_gui(self, parameter_s=''): | |
3226 | """Enable or disable IPython GUI event loop integration. |
|
3221 | """Enable or disable IPython GUI event loop integration. | |
3227 |
|
3222 | |||
3228 | %gui [GUINAME] |
|
3223 | %gui [GUINAME] | |
3229 |
|
3224 | |||
3230 | This magic replaces IPython's threaded shells that were activated |
|
3225 | This magic replaces IPython's threaded shells that were activated | |
3231 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3226 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3232 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3227 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3233 | interrupts should work without any problems. The following toolkits |
|
3228 | interrupts should work without any problems. The following toolkits | |
3234 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3229 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3235 |
|
3230 | |||
3236 | %gui wx # enable wxPython event loop integration |
|
3231 | %gui wx # enable wxPython event loop integration | |
3237 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3232 | %gui qt4|qt # enable PyQt4 event loop integration | |
3238 | %gui gtk # enable PyGTK event loop integration |
|
3233 | %gui gtk # enable PyGTK event loop integration | |
3239 | %gui tk # enable Tk event loop integration |
|
3234 | %gui tk # enable Tk event loop integration | |
3240 | %gui # disable all event loop integration |
|
3235 | %gui # disable all event loop integration | |
3241 |
|
3236 | |||
3242 | WARNING: after any of these has been called you can simply create |
|
3237 | WARNING: after any of these has been called you can simply create | |
3243 | an application object, but DO NOT start the event loop yourself, as |
|
3238 | an application object, but DO NOT start the event loop yourself, as | |
3244 | we have already handled that. |
|
3239 | we have already handled that. | |
3245 | """ |
|
3240 | """ | |
3246 | from IPython.lib.inputhook import enable_gui |
|
3241 | from IPython.lib.inputhook import enable_gui | |
3247 | opts, arg = self.parse_options(parameter_s, '') |
|
3242 | opts, arg = self.parse_options(parameter_s, '') | |
3248 | if arg=='': arg = None |
|
3243 | if arg=='': arg = None | |
3249 | return enable_gui(arg) |
|
3244 | return enable_gui(arg) | |
3250 |
|
3245 | |||
3251 | def magic_load_ext(self, module_str): |
|
3246 | def magic_load_ext(self, module_str): | |
3252 | """Load an IPython extension by its module name.""" |
|
3247 | """Load an IPython extension by its module name.""" | |
3253 | return self.extension_manager.load_extension(module_str) |
|
3248 | return self.extension_manager.load_extension(module_str) | |
3254 |
|
3249 | |||
3255 | def magic_unload_ext(self, module_str): |
|
3250 | def magic_unload_ext(self, module_str): | |
3256 | """Unload an IPython extension by its module name.""" |
|
3251 | """Unload an IPython extension by its module name.""" | |
3257 | self.extension_manager.unload_extension(module_str) |
|
3252 | self.extension_manager.unload_extension(module_str) | |
3258 |
|
3253 | |||
3259 | def magic_reload_ext(self, module_str): |
|
3254 | def magic_reload_ext(self, module_str): | |
3260 | """Reload an IPython extension by its module name.""" |
|
3255 | """Reload an IPython extension by its module name.""" | |
3261 | self.extension_manager.reload_extension(module_str) |
|
3256 | self.extension_manager.reload_extension(module_str) | |
3262 |
|
3257 | |||
3263 | @testdec.skip_doctest |
|
3258 | @testdec.skip_doctest | |
3264 | def magic_install_profiles(self, s): |
|
3259 | def magic_install_profiles(self, s): | |
3265 | """Install the default IPython profiles into the .ipython dir. |
|
3260 | """Install the default IPython profiles into the .ipython dir. | |
3266 |
|
3261 | |||
3267 | If the default profiles have already been installed, they will not |
|
3262 | If the default profiles have already been installed, they will not | |
3268 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3263 | be overwritten. You can force overwriting them by using the ``-o`` | |
3269 | option:: |
|
3264 | option:: | |
3270 |
|
3265 | |||
3271 | In [1]: %install_profiles -o |
|
3266 | In [1]: %install_profiles -o | |
3272 | """ |
|
3267 | """ | |
3273 | if '-o' in s: |
|
3268 | if '-o' in s: | |
3274 | overwrite = True |
|
3269 | overwrite = True | |
3275 | else: |
|
3270 | else: | |
3276 | overwrite = False |
|
3271 | overwrite = False | |
3277 | from IPython.config import profile |
|
3272 | from IPython.config import profile | |
3278 | profile_dir = os.path.split(profile.__file__)[0] |
|
3273 | profile_dir = os.path.split(profile.__file__)[0] | |
3279 | ipython_dir = self.ipython_dir |
|
3274 | ipython_dir = self.ipython_dir | |
3280 | files = os.listdir(profile_dir) |
|
3275 | files = os.listdir(profile_dir) | |
3281 |
|
3276 | |||
3282 | to_install = [] |
|
3277 | to_install = [] | |
3283 | for f in files: |
|
3278 | for f in files: | |
3284 | if f.startswith('ipython_config'): |
|
3279 | if f.startswith('ipython_config'): | |
3285 | src = os.path.join(profile_dir, f) |
|
3280 | src = os.path.join(profile_dir, f) | |
3286 | dst = os.path.join(ipython_dir, f) |
|
3281 | dst = os.path.join(ipython_dir, f) | |
3287 | if (not os.path.isfile(dst)) or overwrite: |
|
3282 | if (not os.path.isfile(dst)) or overwrite: | |
3288 | to_install.append((f, src, dst)) |
|
3283 | to_install.append((f, src, dst)) | |
3289 | if len(to_install)>0: |
|
3284 | if len(to_install)>0: | |
3290 | print "Installing profiles to: ", ipython_dir |
|
3285 | print "Installing profiles to: ", ipython_dir | |
3291 | for (f, src, dst) in to_install: |
|
3286 | for (f, src, dst) in to_install: | |
3292 | shutil.copy(src, dst) |
|
3287 | shutil.copy(src, dst) | |
3293 | print " %s" % f |
|
3288 | print " %s" % f | |
3294 |
|
3289 | |||
3295 | def magic_install_default_config(self, s): |
|
3290 | def magic_install_default_config(self, s): | |
3296 | """Install IPython's default config file into the .ipython dir. |
|
3291 | """Install IPython's default config file into the .ipython dir. | |
3297 |
|
3292 | |||
3298 | If the default config file (:file:`ipython_config.py`) is already |
|
3293 | If the default config file (:file:`ipython_config.py`) is already | |
3299 | installed, it will not be overwritten. You can force overwriting |
|
3294 | installed, it will not be overwritten. You can force overwriting | |
3300 | by using the ``-o`` option:: |
|
3295 | by using the ``-o`` option:: | |
3301 |
|
3296 | |||
3302 | In [1]: %install_default_config |
|
3297 | In [1]: %install_default_config | |
3303 | """ |
|
3298 | """ | |
3304 | if '-o' in s: |
|
3299 | if '-o' in s: | |
3305 | overwrite = True |
|
3300 | overwrite = True | |
3306 | else: |
|
3301 | else: | |
3307 | overwrite = False |
|
3302 | overwrite = False | |
3308 | from IPython.config import default |
|
3303 | from IPython.config import default | |
3309 | config_dir = os.path.split(default.__file__)[0] |
|
3304 | config_dir = os.path.split(default.__file__)[0] | |
3310 | ipython_dir = self.ipython_dir |
|
3305 | ipython_dir = self.ipython_dir | |
3311 | default_config_file_name = 'ipython_config.py' |
|
3306 | default_config_file_name = 'ipython_config.py' | |
3312 | src = os.path.join(config_dir, default_config_file_name) |
|
3307 | src = os.path.join(config_dir, default_config_file_name) | |
3313 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3308 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3314 | if (not os.path.isfile(dst)) or overwrite: |
|
3309 | if (not os.path.isfile(dst)) or overwrite: | |
3315 | shutil.copy(src, dst) |
|
3310 | shutil.copy(src, dst) | |
3316 | print "Installing default config file: %s" % dst |
|
3311 | print "Installing default config file: %s" % dst | |
3317 |
|
3312 | |||
3318 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3313 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3319 | # handling and modify slightly %run |
|
3314 | # handling and modify slightly %run | |
3320 |
|
3315 | |||
3321 | @testdec.skip_doctest |
|
3316 | @testdec.skip_doctest | |
3322 | def _pylab_magic_run(self, parameter_s=''): |
|
3317 | def _pylab_magic_run(self, parameter_s=''): | |
3323 | Magic.magic_run(self, parameter_s, |
|
3318 | Magic.magic_run(self, parameter_s, | |
3324 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3319 | runner=mpl_runner(self.shell.safe_execfile)) | |
3325 |
|
3320 | |||
3326 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3321 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3327 |
|
3322 | |||
3328 | @testdec.skip_doctest |
|
3323 | @testdec.skip_doctest | |
3329 | def magic_pylab(self, s): |
|
3324 | def magic_pylab(self, s): | |
3330 | """Load numpy and matplotlib to work interactively. |
|
3325 | """Load numpy and matplotlib to work interactively. | |
3331 |
|
3326 | |||
3332 | %pylab [GUINAME] |
|
3327 | %pylab [GUINAME] | |
3333 |
|
3328 | |||
3334 | This function lets you activate pylab (matplotlib, numpy and |
|
3329 | This function lets you activate pylab (matplotlib, numpy and | |
3335 | interactive support) at any point during an IPython session. |
|
3330 | interactive support) at any point during an IPython session. | |
3336 |
|
3331 | |||
3337 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3332 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3338 | pylab and mlab, as well as all names from numpy and pylab. |
|
3333 | pylab and mlab, as well as all names from numpy and pylab. | |
3339 |
|
3334 | |||
3340 | Parameters |
|
3335 | Parameters | |
3341 | ---------- |
|
3336 | ---------- | |
3342 | guiname : optional |
|
3337 | guiname : optional | |
3343 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3338 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3344 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3339 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3345 | otherwise matplotlib's default (which you can override in your |
|
3340 | otherwise matplotlib's default (which you can override in your | |
3346 | matplotlib config file) is used. |
|
3341 | matplotlib config file) is used. | |
3347 |
|
3342 | |||
3348 | Examples |
|
3343 | Examples | |
3349 | -------- |
|
3344 | -------- | |
3350 | In this case, where the MPL default is TkAgg: |
|
3345 | In this case, where the MPL default is TkAgg: | |
3351 | In [2]: %pylab |
|
3346 | In [2]: %pylab | |
3352 |
|
3347 | |||
3353 | Welcome to pylab, a matplotlib-based Python environment. |
|
3348 | Welcome to pylab, a matplotlib-based Python environment. | |
3354 | Backend in use: TkAgg |
|
3349 | Backend in use: TkAgg | |
3355 | For more information, type 'help(pylab)'. |
|
3350 | For more information, type 'help(pylab)'. | |
3356 |
|
3351 | |||
3357 | But you can explicitly request a different backend: |
|
3352 | But you can explicitly request a different backend: | |
3358 | In [3]: %pylab qt |
|
3353 | In [3]: %pylab qt | |
3359 |
|
3354 | |||
3360 | Welcome to pylab, a matplotlib-based Python environment. |
|
3355 | Welcome to pylab, a matplotlib-based Python environment. | |
3361 | Backend in use: Qt4Agg |
|
3356 | Backend in use: Qt4Agg | |
3362 | For more information, type 'help(pylab)'. |
|
3357 | For more information, type 'help(pylab)'. | |
3363 | """ |
|
3358 | """ | |
3364 | self.shell.enable_pylab(s) |
|
3359 | self.shell.enable_pylab(s) | |
3365 |
|
3360 | |||
3366 | def magic_tb(self, s): |
|
3361 | def magic_tb(self, s): | |
3367 | """Print the last traceback with the currently active exception mode. |
|
3362 | """Print the last traceback with the currently active exception mode. | |
3368 |
|
3363 | |||
3369 | See %xmode for changing exception reporting modes.""" |
|
3364 | See %xmode for changing exception reporting modes.""" | |
3370 | self.shell.showtraceback() |
|
3365 | self.shell.showtraceback() | |
3371 |
|
3366 | |||
3372 | # end Magic |
|
3367 | # end Magic |
@@ -1,1014 +1,1000 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | Prefiltering components. |
|
4 | Prefiltering components. | |
5 |
|
5 | |||
6 | Prefilters transform user input before it is exec'd by Python. These |
|
6 | Prefilters transform user input before it is exec'd by Python. These | |
7 | transforms are used to implement additional syntax such as !ls and %magic. |
|
7 | transforms are used to implement additional syntax such as !ls and %magic. | |
8 |
|
8 | |||
9 | Authors: |
|
9 | Authors: | |
10 |
|
10 | |||
11 | * Brian Granger |
|
11 | * Brian Granger | |
12 | * Fernando Perez |
|
12 | * Fernando Perez | |
13 | * Dan Milstein |
|
13 | * Dan Milstein | |
14 | * Ville Vainio |
|
14 | * Ville Vainio | |
15 | """ |
|
15 | """ | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Copyright (C) 2008-2009 The IPython Development Team |
|
18 | # Copyright (C) 2008-2009 The IPython Development Team | |
19 | # |
|
19 | # | |
20 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | # Distributed under the terms of the BSD License. The full license is in | |
21 | # the file COPYING, distributed as part of this software. |
|
21 | # the file COPYING, distributed as part of this software. | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Imports |
|
25 | # Imports | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | import __builtin__ |
|
28 | import __builtin__ | |
29 | import codeop |
|
29 | import codeop | |
30 | import re |
|
30 | import re | |
31 |
|
31 | |||
32 | from IPython.core.alias import AliasManager |
|
32 | from IPython.core.alias import AliasManager | |
33 | from IPython.core.autocall import IPyAutocall |
|
33 | from IPython.core.autocall import IPyAutocall | |
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core.splitinput import split_user_input |
|
35 | from IPython.core.splitinput import split_user_input | |
36 | from IPython.core import page |
|
36 | from IPython.core import page | |
37 |
|
37 | |||
38 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance |
|
38 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance | |
39 | import IPython.utils.io |
|
39 | import IPython.utils.io | |
40 | from IPython.utils.text import make_quoted_expr |
|
40 | from IPython.utils.text import make_quoted_expr | |
41 | from IPython.utils.autoattr import auto_attr |
|
41 | from IPython.utils.autoattr import auto_attr | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Global utilities, errors and constants |
|
44 | # Global utilities, errors and constants | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | # Warning, these cannot be changed unless various regular expressions |
|
47 | # Warning, these cannot be changed unless various regular expressions | |
48 | # are updated in a number of places. Not great, but at least we told you. |
|
48 | # are updated in a number of places. Not great, but at least we told you. | |
49 | ESC_SHELL = '!' |
|
49 | ESC_SHELL = '!' | |
50 | ESC_SH_CAP = '!!' |
|
50 | ESC_SH_CAP = '!!' | |
51 | ESC_HELP = '?' |
|
51 | ESC_HELP = '?' | |
52 | ESC_MAGIC = '%' |
|
52 | ESC_MAGIC = '%' | |
53 | ESC_QUOTE = ',' |
|
53 | ESC_QUOTE = ',' | |
54 | ESC_QUOTE2 = ';' |
|
54 | ESC_QUOTE2 = ';' | |
55 | ESC_PAREN = '/' |
|
55 | ESC_PAREN = '/' | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | class PrefilterError(Exception): |
|
58 | class PrefilterError(Exception): | |
59 | pass |
|
59 | pass | |
60 |
|
60 | |||
61 |
|
61 | |||
62 | # RegExp to identify potential function names |
|
62 | # RegExp to identify potential function names | |
63 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
63 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
64 |
|
64 | |||
65 | # RegExp to exclude strings with this start from autocalling. In |
|
65 | # RegExp to exclude strings with this start from autocalling. In | |
66 | # particular, all binary operators should be excluded, so that if foo is |
|
66 | # particular, all binary operators should be excluded, so that if foo is | |
67 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
67 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The | |
68 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
68 | # characters '!=()' don't need to be checked for, as the checkPythonChars | |
69 | # routine explicitely does so, to catch direct calls and rebindings of |
|
69 | # routine explicitely does so, to catch direct calls and rebindings of | |
70 | # existing names. |
|
70 | # existing names. | |
71 |
|
71 | |||
72 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
72 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
73 | # it affects the rest of the group in square brackets. |
|
73 | # it affects the rest of the group in square brackets. | |
74 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
74 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' | |
75 | r'|^is |^not |^in |^and |^or ') |
|
75 | r'|^is |^not |^in |^and |^or ') | |
76 |
|
76 | |||
77 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
77 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
78 | # (experimental). For this to work, the line_split regexp would need |
|
78 | # (experimental). For this to work, the line_split regexp would need | |
79 | # to be modified so it wouldn't break things at '['. That line is |
|
79 | # to be modified so it wouldn't break things at '['. That line is | |
80 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
80 | # nasty enough that I shouldn't change it until I can test it _well_. | |
81 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
81 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
82 |
|
82 | |||
83 |
|
83 | |||
84 | # Handler Check Utilities |
|
84 | # Handler Check Utilities | |
85 | def is_shadowed(identifier, ip): |
|
85 | def is_shadowed(identifier, ip): | |
86 | """Is the given identifier defined in one of the namespaces which shadow |
|
86 | """Is the given identifier defined in one of the namespaces which shadow | |
87 | the alias and magic namespaces? Note that an identifier is different |
|
87 | the alias and magic namespaces? Note that an identifier is different | |
88 | than ifun, because it can not contain a '.' character.""" |
|
88 | than ifun, because it can not contain a '.' character.""" | |
89 | # This is much safer than calling ofind, which can change state |
|
89 | # This is much safer than calling ofind, which can change state | |
90 | return (identifier in ip.user_ns \ |
|
90 | return (identifier in ip.user_ns \ | |
91 | or identifier in ip.internal_ns \ |
|
91 | or identifier in ip.internal_ns \ | |
92 | or identifier in ip.ns_table['builtin']) |
|
92 | or identifier in ip.ns_table['builtin']) | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 | # The LineInfo class used throughout |
|
96 | # The LineInfo class used throughout | |
97 | #----------------------------------------------------------------------------- |
|
97 | #----------------------------------------------------------------------------- | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | class LineInfo(object): |
|
100 | class LineInfo(object): | |
101 | """A single line of input and associated info. |
|
101 | """A single line of input and associated info. | |
102 |
|
102 | |||
103 | Includes the following as properties: |
|
103 | Includes the following as properties: | |
104 |
|
104 | |||
105 | line |
|
105 | line | |
106 | The original, raw line |
|
106 | The original, raw line | |
107 |
|
107 | |||
108 | continue_prompt |
|
108 | continue_prompt | |
109 | Is this line a continuation in a sequence of multiline input? |
|
109 | Is this line a continuation in a sequence of multiline input? | |
110 |
|
110 | |||
111 | pre |
|
111 | pre | |
112 | The initial esc character or whitespace. |
|
112 | The initial esc character or whitespace. | |
113 |
|
113 | |||
114 | pre_char |
|
114 | pre_char | |
115 | The escape character(s) in pre or the empty string if there isn't one. |
|
115 | The escape character(s) in pre or the empty string if there isn't one. | |
116 | Note that '!!' is a possible value for pre_char. Otherwise it will |
|
116 | Note that '!!' is a possible value for pre_char. Otherwise it will | |
117 | always be a single character. |
|
117 | always be a single character. | |
118 |
|
118 | |||
119 | pre_whitespace |
|
119 | pre_whitespace | |
120 | The leading whitespace from pre if it exists. If there is a pre_char, |
|
120 | The leading whitespace from pre if it exists. If there is a pre_char, | |
121 | this is just ''. |
|
121 | this is just ''. | |
122 |
|
122 | |||
123 | ifun |
|
123 | ifun | |
124 | The 'function part', which is basically the maximal initial sequence |
|
124 | The 'function part', which is basically the maximal initial sequence | |
125 | of valid python identifiers and the '.' character. This is what is |
|
125 | of valid python identifiers and the '.' character. This is what is | |
126 | checked for alias and magic transformations, used for auto-calling, |
|
126 | checked for alias and magic transformations, used for auto-calling, | |
127 | etc. |
|
127 | etc. | |
128 |
|
128 | |||
129 | the_rest |
|
129 | the_rest | |
130 | Everything else on the line. |
|
130 | Everything else on the line. | |
131 | """ |
|
131 | """ | |
132 | def __init__(self, line, continue_prompt): |
|
132 | def __init__(self, line, continue_prompt): | |
133 | self.line = line |
|
133 | self.line = line | |
134 | self.continue_prompt = continue_prompt |
|
134 | self.continue_prompt = continue_prompt | |
135 | self.pre, self.ifun, self.the_rest = split_user_input(line) |
|
135 | self.pre, self.ifun, self.the_rest = split_user_input(line) | |
136 |
|
136 | |||
137 | self.pre_char = self.pre.strip() |
|
137 | self.pre_char = self.pre.strip() | |
138 | if self.pre_char: |
|
138 | if self.pre_char: | |
139 | self.pre_whitespace = '' # No whitespace allowd before esc chars |
|
139 | self.pre_whitespace = '' # No whitespace allowd before esc chars | |
140 | else: |
|
140 | else: | |
141 | self.pre_whitespace = self.pre |
|
141 | self.pre_whitespace = self.pre | |
142 |
|
142 | |||
143 | self._oinfo = None |
|
143 | self._oinfo = None | |
144 |
|
144 | |||
145 | def ofind(self, ip): |
|
145 | def ofind(self, ip): | |
146 | """Do a full, attribute-walking lookup of the ifun in the various |
|
146 | """Do a full, attribute-walking lookup of the ifun in the various | |
147 | namespaces for the given IPython InteractiveShell instance. |
|
147 | namespaces for the given IPython InteractiveShell instance. | |
148 |
|
148 | |||
149 | Return a dict with keys: found,obj,ospace,ismagic |
|
149 | Return a dict with keys: found,obj,ospace,ismagic | |
150 |
|
150 | |||
151 | Note: can cause state changes because of calling getattr, but should |
|
151 | Note: can cause state changes because of calling getattr, but should | |
152 | only be run if autocall is on and if the line hasn't matched any |
|
152 | only be run if autocall is on and if the line hasn't matched any | |
153 | other, less dangerous handlers. |
|
153 | other, less dangerous handlers. | |
154 |
|
154 | |||
155 | Does cache the results of the call, so can be called multiple times |
|
155 | Does cache the results of the call, so can be called multiple times | |
156 | without worrying about *further* damaging state. |
|
156 | without worrying about *further* damaging state. | |
157 | """ |
|
157 | """ | |
158 | if not self._oinfo: |
|
158 | if not self._oinfo: | |
159 | # ip.shell._ofind is actually on the Magic class! |
|
159 | # ip.shell._ofind is actually on the Magic class! | |
160 | self._oinfo = ip.shell._ofind(self.ifun) |
|
160 | self._oinfo = ip.shell._ofind(self.ifun) | |
161 | return self._oinfo |
|
161 | return self._oinfo | |
162 |
|
162 | |||
163 | def __str__(self): |
|
163 | def __str__(self): | |
164 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) |
|
164 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) | |
165 |
|
165 | |||
166 |
|
166 | |||
167 | #----------------------------------------------------------------------------- |
|
167 | #----------------------------------------------------------------------------- | |
168 | # Main Prefilter manager |
|
168 | # Main Prefilter manager | |
169 | #----------------------------------------------------------------------------- |
|
169 | #----------------------------------------------------------------------------- | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | class PrefilterManager(Configurable): |
|
172 | class PrefilterManager(Configurable): | |
173 | """Main prefilter component. |
|
173 | """Main prefilter component. | |
174 |
|
174 | |||
175 | The IPython prefilter is run on all user input before it is run. The |
|
175 | The IPython prefilter is run on all user input before it is run. The | |
176 | prefilter consumes lines of input and produces transformed lines of |
|
176 | prefilter consumes lines of input and produces transformed lines of | |
177 | input. |
|
177 | input. | |
178 |
|
178 | |||
179 | The iplementation consists of two phases: |
|
179 | The iplementation consists of two phases: | |
180 |
|
180 | |||
181 | 1. Transformers |
|
181 | 1. Transformers | |
182 | 2. Checkers and handlers |
|
182 | 2. Checkers and handlers | |
183 |
|
183 | |||
184 | Over time, we plan on deprecating the checkers and handlers and doing |
|
184 | Over time, we plan on deprecating the checkers and handlers and doing | |
185 | everything in the transformers. |
|
185 | everything in the transformers. | |
186 |
|
186 | |||
187 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
187 | The transformers are instances of :class:`PrefilterTransformer` and have | |
188 | a single method :meth:`transform` that takes a line and returns a |
|
188 | a single method :meth:`transform` that takes a line and returns a | |
189 | transformed line. The transformation can be accomplished using any |
|
189 | transformed line. The transformation can be accomplished using any | |
190 | tool, but our current ones use regular expressions for speed. We also |
|
190 | tool, but our current ones use regular expressions for speed. We also | |
191 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. |
|
191 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. | |
192 |
|
192 | |||
193 | After all the transformers have been run, the line is fed to the checkers, |
|
193 | After all the transformers have been run, the line is fed to the checkers, | |
194 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
194 | which are instances of :class:`PrefilterChecker`. The line is passed to | |
195 | the :meth:`check` method, which either returns `None` or a |
|
195 | the :meth:`check` method, which either returns `None` or a | |
196 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
196 | :class:`PrefilterHandler` instance. If `None` is returned, the other | |
197 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
197 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, | |
198 | the line is passed to the :meth:`handle` method of the returned |
|
198 | the line is passed to the :meth:`handle` method of the returned | |
199 | handler and no further checkers are tried. |
|
199 | handler and no further checkers are tried. | |
200 |
|
200 | |||
201 | Both transformers and checkers have a `priority` attribute, that determines |
|
201 | Both transformers and checkers have a `priority` attribute, that determines | |
202 | the order in which they are called. Smaller priorities are tried first. |
|
202 | the order in which they are called. Smaller priorities are tried first. | |
203 |
|
203 | |||
204 | Both transformers and checkers also have `enabled` attribute, which is |
|
204 | Both transformers and checkers also have `enabled` attribute, which is | |
205 | a boolean that determines if the instance is used. |
|
205 | a boolean that determines if the instance is used. | |
206 |
|
206 | |||
207 | Users or developers can change the priority or enabled attribute of |
|
207 | Users or developers can change the priority or enabled attribute of | |
208 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
208 | transformers or checkers, but they must call the :meth:`sort_checkers` | |
209 | or :meth:`sort_transformers` method after changing the priority. |
|
209 | or :meth:`sort_transformers` method after changing the priority. | |
210 | """ |
|
210 | """ | |
211 |
|
211 | |||
212 | multi_line_specials = CBool(True, config=True) |
|
212 | multi_line_specials = CBool(True, config=True) | |
213 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
213 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
214 |
|
214 | |||
215 | def __init__(self, shell=None, config=None): |
|
215 | def __init__(self, shell=None, config=None): | |
216 | super(PrefilterManager, self).__init__(shell=shell, config=config) |
|
216 | super(PrefilterManager, self).__init__(shell=shell, config=config) | |
217 | self.shell = shell |
|
217 | self.shell = shell | |
218 | self.init_transformers() |
|
218 | self.init_transformers() | |
219 | self.init_handlers() |
|
219 | self.init_handlers() | |
220 | self.init_checkers() |
|
220 | self.init_checkers() | |
221 |
|
221 | |||
222 | #------------------------------------------------------------------------- |
|
222 | #------------------------------------------------------------------------- | |
223 | # API for managing transformers |
|
223 | # API for managing transformers | |
224 | #------------------------------------------------------------------------- |
|
224 | #------------------------------------------------------------------------- | |
225 |
|
225 | |||
226 | def init_transformers(self): |
|
226 | def init_transformers(self): | |
227 | """Create the default transformers.""" |
|
227 | """Create the default transformers.""" | |
228 | self._transformers = [] |
|
228 | self._transformers = [] | |
229 | for transformer_cls in _default_transformers: |
|
229 | for transformer_cls in _default_transformers: | |
230 | transformer_cls( |
|
230 | transformer_cls( | |
231 | shell=self.shell, prefilter_manager=self, config=self.config |
|
231 | shell=self.shell, prefilter_manager=self, config=self.config | |
232 | ) |
|
232 | ) | |
233 |
|
233 | |||
234 | def sort_transformers(self): |
|
234 | def sort_transformers(self): | |
235 | """Sort the transformers by priority. |
|
235 | """Sort the transformers by priority. | |
236 |
|
236 | |||
237 | This must be called after the priority of a transformer is changed. |
|
237 | This must be called after the priority of a transformer is changed. | |
238 | The :meth:`register_transformer` method calls this automatically. |
|
238 | The :meth:`register_transformer` method calls this automatically. | |
239 | """ |
|
239 | """ | |
240 | self._transformers.sort(key=lambda x: x.priority) |
|
240 | self._transformers.sort(key=lambda x: x.priority) | |
241 |
|
241 | |||
242 | @property |
|
242 | @property | |
243 | def transformers(self): |
|
243 | def transformers(self): | |
244 | """Return a list of checkers, sorted by priority.""" |
|
244 | """Return a list of checkers, sorted by priority.""" | |
245 | return self._transformers |
|
245 | return self._transformers | |
246 |
|
246 | |||
247 | def register_transformer(self, transformer): |
|
247 | def register_transformer(self, transformer): | |
248 | """Register a transformer instance.""" |
|
248 | """Register a transformer instance.""" | |
249 | if transformer not in self._transformers: |
|
249 | if transformer not in self._transformers: | |
250 | self._transformers.append(transformer) |
|
250 | self._transformers.append(transformer) | |
251 | self.sort_transformers() |
|
251 | self.sort_transformers() | |
252 |
|
252 | |||
253 | def unregister_transformer(self, transformer): |
|
253 | def unregister_transformer(self, transformer): | |
254 | """Unregister a transformer instance.""" |
|
254 | """Unregister a transformer instance.""" | |
255 | if transformer in self._transformers: |
|
255 | if transformer in self._transformers: | |
256 | self._transformers.remove(transformer) |
|
256 | self._transformers.remove(transformer) | |
257 |
|
257 | |||
258 | #------------------------------------------------------------------------- |
|
258 | #------------------------------------------------------------------------- | |
259 | # API for managing checkers |
|
259 | # API for managing checkers | |
260 | #------------------------------------------------------------------------- |
|
260 | #------------------------------------------------------------------------- | |
261 |
|
261 | |||
262 | def init_checkers(self): |
|
262 | def init_checkers(self): | |
263 | """Create the default checkers.""" |
|
263 | """Create the default checkers.""" | |
264 | self._checkers = [] |
|
264 | self._checkers = [] | |
265 | for checker in _default_checkers: |
|
265 | for checker in _default_checkers: | |
266 | checker( |
|
266 | checker( | |
267 | shell=self.shell, prefilter_manager=self, config=self.config |
|
267 | shell=self.shell, prefilter_manager=self, config=self.config | |
268 | ) |
|
268 | ) | |
269 |
|
269 | |||
270 | def sort_checkers(self): |
|
270 | def sort_checkers(self): | |
271 | """Sort the checkers by priority. |
|
271 | """Sort the checkers by priority. | |
272 |
|
272 | |||
273 | This must be called after the priority of a checker is changed. |
|
273 | This must be called after the priority of a checker is changed. | |
274 | The :meth:`register_checker` method calls this automatically. |
|
274 | The :meth:`register_checker` method calls this automatically. | |
275 | """ |
|
275 | """ | |
276 | self._checkers.sort(key=lambda x: x.priority) |
|
276 | self._checkers.sort(key=lambda x: x.priority) | |
277 |
|
277 | |||
278 | @property |
|
278 | @property | |
279 | def checkers(self): |
|
279 | def checkers(self): | |
280 | """Return a list of checkers, sorted by priority.""" |
|
280 | """Return a list of checkers, sorted by priority.""" | |
281 | return self._checkers |
|
281 | return self._checkers | |
282 |
|
282 | |||
283 | def register_checker(self, checker): |
|
283 | def register_checker(self, checker): | |
284 | """Register a checker instance.""" |
|
284 | """Register a checker instance.""" | |
285 | if checker not in self._checkers: |
|
285 | if checker not in self._checkers: | |
286 | self._checkers.append(checker) |
|
286 | self._checkers.append(checker) | |
287 | self.sort_checkers() |
|
287 | self.sort_checkers() | |
288 |
|
288 | |||
289 | def unregister_checker(self, checker): |
|
289 | def unregister_checker(self, checker): | |
290 | """Unregister a checker instance.""" |
|
290 | """Unregister a checker instance.""" | |
291 | if checker in self._checkers: |
|
291 | if checker in self._checkers: | |
292 | self._checkers.remove(checker) |
|
292 | self._checkers.remove(checker) | |
293 |
|
293 | |||
294 | #------------------------------------------------------------------------- |
|
294 | #------------------------------------------------------------------------- | |
295 | # API for managing checkers |
|
295 | # API for managing checkers | |
296 | #------------------------------------------------------------------------- |
|
296 | #------------------------------------------------------------------------- | |
297 |
|
297 | |||
298 | def init_handlers(self): |
|
298 | def init_handlers(self): | |
299 | """Create the default handlers.""" |
|
299 | """Create the default handlers.""" | |
300 | self._handlers = {} |
|
300 | self._handlers = {} | |
301 | self._esc_handlers = {} |
|
301 | self._esc_handlers = {} | |
302 | for handler in _default_handlers: |
|
302 | for handler in _default_handlers: | |
303 | handler( |
|
303 | handler( | |
304 | shell=self.shell, prefilter_manager=self, config=self.config |
|
304 | shell=self.shell, prefilter_manager=self, config=self.config | |
305 | ) |
|
305 | ) | |
306 |
|
306 | |||
307 | @property |
|
307 | @property | |
308 | def handlers(self): |
|
308 | def handlers(self): | |
309 | """Return a dict of all the handlers.""" |
|
309 | """Return a dict of all the handlers.""" | |
310 | return self._handlers |
|
310 | return self._handlers | |
311 |
|
311 | |||
312 | def register_handler(self, name, handler, esc_strings): |
|
312 | def register_handler(self, name, handler, esc_strings): | |
313 | """Register a handler instance by name with esc_strings.""" |
|
313 | """Register a handler instance by name with esc_strings.""" | |
314 | self._handlers[name] = handler |
|
314 | self._handlers[name] = handler | |
315 | for esc_str in esc_strings: |
|
315 | for esc_str in esc_strings: | |
316 | self._esc_handlers[esc_str] = handler |
|
316 | self._esc_handlers[esc_str] = handler | |
317 |
|
317 | |||
318 | def unregister_handler(self, name, handler, esc_strings): |
|
318 | def unregister_handler(self, name, handler, esc_strings): | |
319 | """Unregister a handler instance by name with esc_strings.""" |
|
319 | """Unregister a handler instance by name with esc_strings.""" | |
320 | try: |
|
320 | try: | |
321 | del self._handlers[name] |
|
321 | del self._handlers[name] | |
322 | except KeyError: |
|
322 | except KeyError: | |
323 | pass |
|
323 | pass | |
324 | for esc_str in esc_strings: |
|
324 | for esc_str in esc_strings: | |
325 | h = self._esc_handlers.get(esc_str) |
|
325 | h = self._esc_handlers.get(esc_str) | |
326 | if h is handler: |
|
326 | if h is handler: | |
327 | del self._esc_handlers[esc_str] |
|
327 | del self._esc_handlers[esc_str] | |
328 |
|
328 | |||
329 | def get_handler_by_name(self, name): |
|
329 | def get_handler_by_name(self, name): | |
330 | """Get a handler by its name.""" |
|
330 | """Get a handler by its name.""" | |
331 | return self._handlers.get(name) |
|
331 | return self._handlers.get(name) | |
332 |
|
332 | |||
333 | def get_handler_by_esc(self, esc_str): |
|
333 | def get_handler_by_esc(self, esc_str): | |
334 | """Get a handler by its escape string.""" |
|
334 | """Get a handler by its escape string.""" | |
335 | return self._esc_handlers.get(esc_str) |
|
335 | return self._esc_handlers.get(esc_str) | |
336 |
|
336 | |||
337 | #------------------------------------------------------------------------- |
|
337 | #------------------------------------------------------------------------- | |
338 | # Main prefiltering API |
|
338 | # Main prefiltering API | |
339 | #------------------------------------------------------------------------- |
|
339 | #------------------------------------------------------------------------- | |
340 |
|
340 | |||
341 | def prefilter_line_info(self, line_info): |
|
341 | def prefilter_line_info(self, line_info): | |
342 | """Prefilter a line that has been converted to a LineInfo object. |
|
342 | """Prefilter a line that has been converted to a LineInfo object. | |
343 |
|
343 | |||
344 | This implements the checker/handler part of the prefilter pipe. |
|
344 | This implements the checker/handler part of the prefilter pipe. | |
345 | """ |
|
345 | """ | |
346 | # print "prefilter_line_info: ", line_info |
|
346 | # print "prefilter_line_info: ", line_info | |
347 | handler = self.find_handler(line_info) |
|
347 | handler = self.find_handler(line_info) | |
348 | return handler.handle(line_info) |
|
348 | return handler.handle(line_info) | |
349 |
|
349 | |||
350 | def find_handler(self, line_info): |
|
350 | def find_handler(self, line_info): | |
351 | """Find a handler for the line_info by trying checkers.""" |
|
351 | """Find a handler for the line_info by trying checkers.""" | |
352 | for checker in self.checkers: |
|
352 | for checker in self.checkers: | |
353 | if checker.enabled: |
|
353 | if checker.enabled: | |
354 | handler = checker.check(line_info) |
|
354 | handler = checker.check(line_info) | |
355 | if handler: |
|
355 | if handler: | |
356 | return handler |
|
356 | return handler | |
357 | return self.get_handler_by_name('normal') |
|
357 | return self.get_handler_by_name('normal') | |
358 |
|
358 | |||
359 | def transform_line(self, line, continue_prompt): |
|
359 | def transform_line(self, line, continue_prompt): | |
360 | """Calls the enabled transformers in order of increasing priority.""" |
|
360 | """Calls the enabled transformers in order of increasing priority.""" | |
361 | for transformer in self.transformers: |
|
361 | for transformer in self.transformers: | |
362 | if transformer.enabled: |
|
362 | if transformer.enabled: | |
363 | line = transformer.transform(line, continue_prompt) |
|
363 | line = transformer.transform(line, continue_prompt) | |
364 | return line |
|
364 | return line | |
365 |
|
365 | |||
366 | def prefilter_line(self, line, continue_prompt=False): |
|
366 | def prefilter_line(self, line, continue_prompt=False): | |
367 | """Prefilter a single input line as text. |
|
367 | """Prefilter a single input line as text. | |
368 |
|
368 | |||
369 | This method prefilters a single line of text by calling the |
|
369 | This method prefilters a single line of text by calling the | |
370 | transformers and then the checkers/handlers. |
|
370 | transformers and then the checkers/handlers. | |
371 | """ |
|
371 | """ | |
372 |
|
372 | |||
373 | # print "prefilter_line: ", line, continue_prompt |
|
373 | # print "prefilter_line: ", line, continue_prompt | |
374 | # All handlers *must* return a value, even if it's blank (''). |
|
374 | # All handlers *must* return a value, even if it's blank (''). | |
375 |
|
375 | |||
376 | # Lines are NOT logged here. Handlers should process the line as |
|
|||
377 | # needed, update the cache AND log it (so that the input cache array |
|
|||
378 | # stays synced). |
|
|||
379 |
|
||||
380 | # save the line away in case we crash, so the post-mortem handler can |
|
376 | # save the line away in case we crash, so the post-mortem handler can | |
381 | # record it |
|
377 | # record it | |
382 | self.shell._last_input_line = line |
|
378 | self.shell._last_input_line = line | |
383 |
|
379 | |||
384 | if not line: |
|
380 | if not line: | |
385 | # Return immediately on purely empty lines, so that if the user |
|
381 | # Return immediately on purely empty lines, so that if the user | |
386 | # previously typed some whitespace that started a continuation |
|
382 | # previously typed some whitespace that started a continuation | |
387 | # prompt, he can break out of that loop with just an empty line. |
|
383 | # prompt, he can break out of that loop with just an empty line. | |
388 | # This is how the default python prompt works. |
|
384 | # This is how the default python prompt works. | |
389 |
|
385 | |||
390 | # Only return if the accumulated input buffer was just whitespace! |
|
386 | # Only return if the accumulated input buffer was just whitespace! | |
391 | if ''.join(self.shell.buffer).isspace(): |
|
387 | if ''.join(self.shell.buffer).isspace(): | |
392 | self.shell.buffer[:] = [] |
|
388 | self.shell.buffer[:] = [] | |
393 | return '' |
|
389 | return '' | |
394 |
|
390 | |||
395 | # At this point, we invoke our transformers. |
|
391 | # At this point, we invoke our transformers. | |
396 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
392 | if not continue_prompt or (continue_prompt and self.multi_line_specials): | |
397 | line = self.transform_line(line, continue_prompt) |
|
393 | line = self.transform_line(line, continue_prompt) | |
398 |
|
394 | |||
399 | # Now we compute line_info for the checkers and handlers |
|
395 | # Now we compute line_info for the checkers and handlers | |
400 | line_info = LineInfo(line, continue_prompt) |
|
396 | line_info = LineInfo(line, continue_prompt) | |
401 |
|
397 | |||
402 | # the input history needs to track even empty lines |
|
398 | # the input history needs to track even empty lines | |
403 | stripped = line.strip() |
|
399 | stripped = line.strip() | |
404 |
|
400 | |||
405 | normal_handler = self.get_handler_by_name('normal') |
|
401 | normal_handler = self.get_handler_by_name('normal') | |
406 | if not stripped: |
|
402 | if not stripped: | |
407 | if not continue_prompt: |
|
403 | if not continue_prompt: | |
408 | self.shell.displayhook.prompt_count -= 1 |
|
404 | self.shell.displayhook.prompt_count -= 1 | |
409 |
|
405 | |||
410 | return normal_handler.handle(line_info) |
|
406 | return normal_handler.handle(line_info) | |
411 |
|
407 | |||
412 | # special handlers are only allowed for single line statements |
|
408 | # special handlers are only allowed for single line statements | |
413 | if continue_prompt and not self.multi_line_specials: |
|
409 | if continue_prompt and not self.multi_line_specials: | |
414 | return normal_handler.handle(line_info) |
|
410 | return normal_handler.handle(line_info) | |
415 |
|
411 | |||
416 | prefiltered = self.prefilter_line_info(line_info) |
|
412 | prefiltered = self.prefilter_line_info(line_info) | |
417 | # print "prefiltered line: %r" % prefiltered |
|
413 | # print "prefiltered line: %r" % prefiltered | |
418 | return prefiltered |
|
414 | return prefiltered | |
419 |
|
415 | |||
420 | def prefilter_lines(self, lines, continue_prompt=False): |
|
416 | def prefilter_lines(self, lines, continue_prompt=False): | |
421 | """Prefilter multiple input lines of text. |
|
417 | """Prefilter multiple input lines of text. | |
422 |
|
418 | |||
423 | This is the main entry point for prefiltering multiple lines of |
|
419 | This is the main entry point for prefiltering multiple lines of | |
424 | input. This simply calls :meth:`prefilter_line` for each line of |
|
420 | input. This simply calls :meth:`prefilter_line` for each line of | |
425 | input. |
|
421 | input. | |
426 |
|
422 | |||
427 | This covers cases where there are multiple lines in the user entry, |
|
423 | This covers cases where there are multiple lines in the user entry, | |
428 | which is the case when the user goes back to a multiline history |
|
424 | which is the case when the user goes back to a multiline history | |
429 | entry and presses enter. |
|
425 | entry and presses enter. | |
430 | """ |
|
426 | """ | |
431 | llines = lines.rstrip('\n').split('\n') |
|
427 | llines = lines.rstrip('\n').split('\n') | |
432 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
428 | # We can get multiple lines in one shot, where multiline input 'blends' | |
433 | # into one line, in cases like recalling from the readline history |
|
429 | # into one line, in cases like recalling from the readline history | |
434 | # buffer. We need to make sure that in such cases, we correctly |
|
430 | # buffer. We need to make sure that in such cases, we correctly | |
435 | # communicate downstream which line is first and which are continuation |
|
431 | # communicate downstream which line is first and which are continuation | |
436 | # ones. |
|
432 | # ones. | |
437 | if len(llines) > 1: |
|
433 | if len(llines) > 1: | |
438 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
434 | out = '\n'.join([self.prefilter_line(line, lnum>0) | |
439 | for lnum, line in enumerate(llines) ]) |
|
435 | for lnum, line in enumerate(llines) ]) | |
440 | else: |
|
436 | else: | |
441 | out = self.prefilter_line(llines[0], continue_prompt) |
|
437 | out = self.prefilter_line(llines[0], continue_prompt) | |
442 |
|
438 | |||
443 | return out |
|
439 | return out | |
444 |
|
440 | |||
445 | #----------------------------------------------------------------------------- |
|
441 | #----------------------------------------------------------------------------- | |
446 | # Prefilter transformers |
|
442 | # Prefilter transformers | |
447 | #----------------------------------------------------------------------------- |
|
443 | #----------------------------------------------------------------------------- | |
448 |
|
444 | |||
449 |
|
445 | |||
450 | class PrefilterTransformer(Configurable): |
|
446 | class PrefilterTransformer(Configurable): | |
451 | """Transform a line of user input.""" |
|
447 | """Transform a line of user input.""" | |
452 |
|
448 | |||
453 | priority = Int(100, config=True) |
|
449 | priority = Int(100, config=True) | |
454 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
450 | # Transformers don't currently use shell or prefilter_manager, but as we | |
455 | # move away from checkers and handlers, they will need them. |
|
451 | # move away from checkers and handlers, they will need them. | |
456 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
452 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
457 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
453 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
458 | enabled = Bool(True, config=True) |
|
454 | enabled = Bool(True, config=True) | |
459 |
|
455 | |||
460 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
456 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
461 | super(PrefilterTransformer, self).__init__( |
|
457 | super(PrefilterTransformer, self).__init__( | |
462 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
458 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
463 | ) |
|
459 | ) | |
464 | self.prefilter_manager.register_transformer(self) |
|
460 | self.prefilter_manager.register_transformer(self) | |
465 |
|
461 | |||
466 | def transform(self, line, continue_prompt): |
|
462 | def transform(self, line, continue_prompt): | |
467 | """Transform a line, returning the new one.""" |
|
463 | """Transform a line, returning the new one.""" | |
468 | return None |
|
464 | return None | |
469 |
|
465 | |||
470 | def __repr__(self): |
|
466 | def __repr__(self): | |
471 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
467 | return "<%s(priority=%r, enabled=%r)>" % ( | |
472 | self.__class__.__name__, self.priority, self.enabled) |
|
468 | self.__class__.__name__, self.priority, self.enabled) | |
473 |
|
469 | |||
474 |
|
470 | |||
475 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
471 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
476 | r'\s*=\s*!(?P<cmd>.*)') |
|
472 | r'\s*=\s*!(?P<cmd>.*)') | |
477 |
|
473 | |||
478 |
|
474 | |||
479 | class AssignSystemTransformer(PrefilterTransformer): |
|
475 | class AssignSystemTransformer(PrefilterTransformer): | |
480 | """Handle the `files = !ls` syntax.""" |
|
476 | """Handle the `files = !ls` syntax.""" | |
481 |
|
477 | |||
482 | priority = Int(100, config=True) |
|
478 | priority = Int(100, config=True) | |
483 |
|
479 | |||
484 | def transform(self, line, continue_prompt): |
|
480 | def transform(self, line, continue_prompt): | |
485 | m = _assign_system_re.match(line) |
|
481 | m = _assign_system_re.match(line) | |
486 | if m is not None: |
|
482 | if m is not None: | |
487 | cmd = m.group('cmd') |
|
483 | cmd = m.group('cmd') | |
488 | lhs = m.group('lhs') |
|
484 | lhs = m.group('lhs') | |
489 | expr = make_quoted_expr("sc =%s" % cmd) |
|
485 | expr = make_quoted_expr("sc =%s" % cmd) | |
490 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
486 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
491 | return new_line |
|
487 | return new_line | |
492 | return line |
|
488 | return line | |
493 |
|
489 | |||
494 |
|
490 | |||
495 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
491 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
496 | r'\s*=\s*%(?P<cmd>.*)') |
|
492 | r'\s*=\s*%(?P<cmd>.*)') | |
497 |
|
493 | |||
498 | class AssignMagicTransformer(PrefilterTransformer): |
|
494 | class AssignMagicTransformer(PrefilterTransformer): | |
499 | """Handle the `a = %who` syntax.""" |
|
495 | """Handle the `a = %who` syntax.""" | |
500 |
|
496 | |||
501 | priority = Int(200, config=True) |
|
497 | priority = Int(200, config=True) | |
502 |
|
498 | |||
503 | def transform(self, line, continue_prompt): |
|
499 | def transform(self, line, continue_prompt): | |
504 | m = _assign_magic_re.match(line) |
|
500 | m = _assign_magic_re.match(line) | |
505 | if m is not None: |
|
501 | if m is not None: | |
506 | cmd = m.group('cmd') |
|
502 | cmd = m.group('cmd') | |
507 | lhs = m.group('lhs') |
|
503 | lhs = m.group('lhs') | |
508 | expr = make_quoted_expr(cmd) |
|
504 | expr = make_quoted_expr(cmd) | |
509 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
505 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
510 | return new_line |
|
506 | return new_line | |
511 | return line |
|
507 | return line | |
512 |
|
508 | |||
513 |
|
509 | |||
514 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
510 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') | |
515 |
|
511 | |||
516 | class PyPromptTransformer(PrefilterTransformer): |
|
512 | class PyPromptTransformer(PrefilterTransformer): | |
517 | """Handle inputs that start with '>>> ' syntax.""" |
|
513 | """Handle inputs that start with '>>> ' syntax.""" | |
518 |
|
514 | |||
519 | priority = Int(50, config=True) |
|
515 | priority = Int(50, config=True) | |
520 |
|
516 | |||
521 | def transform(self, line, continue_prompt): |
|
517 | def transform(self, line, continue_prompt): | |
522 |
|
518 | |||
523 | if not line or line.isspace() or line.strip() == '...': |
|
519 | if not line or line.isspace() or line.strip() == '...': | |
524 | # This allows us to recognize multiple input prompts separated by |
|
520 | # This allows us to recognize multiple input prompts separated by | |
525 | # blank lines and pasted in a single chunk, very common when |
|
521 | # blank lines and pasted in a single chunk, very common when | |
526 | # pasting doctests or long tutorial passages. |
|
522 | # pasting doctests or long tutorial passages. | |
527 | return '' |
|
523 | return '' | |
528 | m = _classic_prompt_re.match(line) |
|
524 | m = _classic_prompt_re.match(line) | |
529 | if m: |
|
525 | if m: | |
530 | return line[len(m.group(0)):] |
|
526 | return line[len(m.group(0)):] | |
531 | else: |
|
527 | else: | |
532 | return line |
|
528 | return line | |
533 |
|
529 | |||
534 |
|
530 | |||
535 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
531 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
536 |
|
532 | |||
537 | class IPyPromptTransformer(PrefilterTransformer): |
|
533 | class IPyPromptTransformer(PrefilterTransformer): | |
538 | """Handle inputs that start classic IPython prompt syntax.""" |
|
534 | """Handle inputs that start classic IPython prompt syntax.""" | |
539 |
|
535 | |||
540 | priority = Int(50, config=True) |
|
536 | priority = Int(50, config=True) | |
541 |
|
537 | |||
542 | def transform(self, line, continue_prompt): |
|
538 | def transform(self, line, continue_prompt): | |
543 |
|
539 | |||
544 | if not line or line.isspace() or line.strip() == '...': |
|
540 | if not line or line.isspace() or line.strip() == '...': | |
545 | # This allows us to recognize multiple input prompts separated by |
|
541 | # This allows us to recognize multiple input prompts separated by | |
546 | # blank lines and pasted in a single chunk, very common when |
|
542 | # blank lines and pasted in a single chunk, very common when | |
547 | # pasting doctests or long tutorial passages. |
|
543 | # pasting doctests or long tutorial passages. | |
548 | return '' |
|
544 | return '' | |
549 | m = _ipy_prompt_re.match(line) |
|
545 | m = _ipy_prompt_re.match(line) | |
550 | if m: |
|
546 | if m: | |
551 | return line[len(m.group(0)):] |
|
547 | return line[len(m.group(0)):] | |
552 | else: |
|
548 | else: | |
553 | return line |
|
549 | return line | |
554 |
|
550 | |||
555 | #----------------------------------------------------------------------------- |
|
551 | #----------------------------------------------------------------------------- | |
556 | # Prefilter checkers |
|
552 | # Prefilter checkers | |
557 | #----------------------------------------------------------------------------- |
|
553 | #----------------------------------------------------------------------------- | |
558 |
|
554 | |||
559 |
|
555 | |||
560 | class PrefilterChecker(Configurable): |
|
556 | class PrefilterChecker(Configurable): | |
561 | """Inspect an input line and return a handler for that line.""" |
|
557 | """Inspect an input line and return a handler for that line.""" | |
562 |
|
558 | |||
563 | priority = Int(100, config=True) |
|
559 | priority = Int(100, config=True) | |
564 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
560 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
565 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
561 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
566 | enabled = Bool(True, config=True) |
|
562 | enabled = Bool(True, config=True) | |
567 |
|
563 | |||
568 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
564 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
569 | super(PrefilterChecker, self).__init__( |
|
565 | super(PrefilterChecker, self).__init__( | |
570 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
566 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
571 | ) |
|
567 | ) | |
572 | self.prefilter_manager.register_checker(self) |
|
568 | self.prefilter_manager.register_checker(self) | |
573 |
|
569 | |||
574 | def check(self, line_info): |
|
570 | def check(self, line_info): | |
575 | """Inspect line_info and return a handler instance or None.""" |
|
571 | """Inspect line_info and return a handler instance or None.""" | |
576 | return None |
|
572 | return None | |
577 |
|
573 | |||
578 | def __repr__(self): |
|
574 | def __repr__(self): | |
579 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
575 | return "<%s(priority=%r, enabled=%r)>" % ( | |
580 | self.__class__.__name__, self.priority, self.enabled) |
|
576 | self.__class__.__name__, self.priority, self.enabled) | |
581 |
|
577 | |||
582 |
|
578 | |||
583 | class EmacsChecker(PrefilterChecker): |
|
579 | class EmacsChecker(PrefilterChecker): | |
584 |
|
580 | |||
585 | priority = Int(100, config=True) |
|
581 | priority = Int(100, config=True) | |
586 | enabled = Bool(False, config=True) |
|
582 | enabled = Bool(False, config=True) | |
587 |
|
583 | |||
588 | def check(self, line_info): |
|
584 | def check(self, line_info): | |
589 | "Emacs ipython-mode tags certain input lines." |
|
585 | "Emacs ipython-mode tags certain input lines." | |
590 | if line_info.line.endswith('# PYTHON-MODE'): |
|
586 | if line_info.line.endswith('# PYTHON-MODE'): | |
591 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
587 | return self.prefilter_manager.get_handler_by_name('emacs') | |
592 | else: |
|
588 | else: | |
593 | return None |
|
589 | return None | |
594 |
|
590 | |||
595 |
|
591 | |||
596 | class ShellEscapeChecker(PrefilterChecker): |
|
592 | class ShellEscapeChecker(PrefilterChecker): | |
597 |
|
593 | |||
598 | priority = Int(200, config=True) |
|
594 | priority = Int(200, config=True) | |
599 |
|
595 | |||
600 | def check(self, line_info): |
|
596 | def check(self, line_info): | |
601 | if line_info.line.lstrip().startswith(ESC_SHELL): |
|
597 | if line_info.line.lstrip().startswith(ESC_SHELL): | |
602 | return self.prefilter_manager.get_handler_by_name('shell') |
|
598 | return self.prefilter_manager.get_handler_by_name('shell') | |
603 |
|
599 | |||
604 |
|
600 | |||
605 | class IPyAutocallChecker(PrefilterChecker): |
|
601 | class IPyAutocallChecker(PrefilterChecker): | |
606 |
|
602 | |||
607 | priority = Int(300, config=True) |
|
603 | priority = Int(300, config=True) | |
608 |
|
604 | |||
609 | def check(self, line_info): |
|
605 | def check(self, line_info): | |
610 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
606 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
611 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
607 | obj = self.shell.user_ns.get(line_info.ifun, None) | |
612 | if isinstance(obj, IPyAutocall): |
|
608 | if isinstance(obj, IPyAutocall): | |
613 | obj.set_ip(self.shell) |
|
609 | obj.set_ip(self.shell) | |
614 | return self.prefilter_manager.get_handler_by_name('auto') |
|
610 | return self.prefilter_manager.get_handler_by_name('auto') | |
615 | else: |
|
611 | else: | |
616 | return None |
|
612 | return None | |
617 |
|
613 | |||
618 |
|
614 | |||
619 | class MultiLineMagicChecker(PrefilterChecker): |
|
615 | class MultiLineMagicChecker(PrefilterChecker): | |
620 |
|
616 | |||
621 | priority = Int(400, config=True) |
|
617 | priority = Int(400, config=True) | |
622 |
|
618 | |||
623 | def check(self, line_info): |
|
619 | def check(self, line_info): | |
624 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
620 | "Allow ! and !! in multi-line statements if multi_line_specials is on" | |
625 | # Note that this one of the only places we check the first character of |
|
621 | # Note that this one of the only places we check the first character of | |
626 | # ifun and *not* the pre_char. Also note that the below test matches |
|
622 | # ifun and *not* the pre_char. Also note that the below test matches | |
627 | # both ! and !!. |
|
623 | # both ! and !!. | |
628 | if line_info.continue_prompt \ |
|
624 | if line_info.continue_prompt \ | |
629 | and self.prefilter_manager.multi_line_specials: |
|
625 | and self.prefilter_manager.multi_line_specials: | |
630 | if line_info.ifun.startswith(ESC_MAGIC): |
|
626 | if line_info.ifun.startswith(ESC_MAGIC): | |
631 | return self.prefilter_manager.get_handler_by_name('magic') |
|
627 | return self.prefilter_manager.get_handler_by_name('magic') | |
632 | else: |
|
628 | else: | |
633 | return None |
|
629 | return None | |
634 |
|
630 | |||
635 |
|
631 | |||
636 | class EscCharsChecker(PrefilterChecker): |
|
632 | class EscCharsChecker(PrefilterChecker): | |
637 |
|
633 | |||
638 | priority = Int(500, config=True) |
|
634 | priority = Int(500, config=True) | |
639 |
|
635 | |||
640 | def check(self, line_info): |
|
636 | def check(self, line_info): | |
641 | """Check for escape character and return either a handler to handle it, |
|
637 | """Check for escape character and return either a handler to handle it, | |
642 | or None if there is no escape char.""" |
|
638 | or None if there is no escape char.""" | |
643 | if line_info.line[-1] == ESC_HELP \ |
|
639 | if line_info.line[-1] == ESC_HELP \ | |
644 | and line_info.pre_char != ESC_SHELL \ |
|
640 | and line_info.pre_char != ESC_SHELL \ | |
645 | and line_info.pre_char != ESC_SH_CAP: |
|
641 | and line_info.pre_char != ESC_SH_CAP: | |
646 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
642 | # the ? can be at the end, but *not* for either kind of shell escape, | |
647 | # because a ? can be a vaild final char in a shell cmd |
|
643 | # because a ? can be a vaild final char in a shell cmd | |
648 | return self.prefilter_manager.get_handler_by_name('help') |
|
644 | return self.prefilter_manager.get_handler_by_name('help') | |
649 | else: |
|
645 | else: | |
650 | # This returns None like it should if no handler exists |
|
646 | # This returns None like it should if no handler exists | |
651 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) |
|
647 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) | |
652 |
|
648 | |||
653 |
|
649 | |||
654 | class AssignmentChecker(PrefilterChecker): |
|
650 | class AssignmentChecker(PrefilterChecker): | |
655 |
|
651 | |||
656 | priority = Int(600, config=True) |
|
652 | priority = Int(600, config=True) | |
657 |
|
653 | |||
658 | def check(self, line_info): |
|
654 | def check(self, line_info): | |
659 | """Check to see if user is assigning to a var for the first time, in |
|
655 | """Check to see if user is assigning to a var for the first time, in | |
660 | which case we want to avoid any sort of automagic / autocall games. |
|
656 | which case we want to avoid any sort of automagic / autocall games. | |
661 |
|
657 | |||
662 | This allows users to assign to either alias or magic names true python |
|
658 | This allows users to assign to either alias or magic names true python | |
663 | variables (the magic/alias systems always take second seat to true |
|
659 | variables (the magic/alias systems always take second seat to true | |
664 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
660 | python code). E.g. ls='hi', or ls,that=1,2""" | |
665 | if line_info.the_rest: |
|
661 | if line_info.the_rest: | |
666 | if line_info.the_rest[0] in '=,': |
|
662 | if line_info.the_rest[0] in '=,': | |
667 | return self.prefilter_manager.get_handler_by_name('normal') |
|
663 | return self.prefilter_manager.get_handler_by_name('normal') | |
668 | else: |
|
664 | else: | |
669 | return None |
|
665 | return None | |
670 |
|
666 | |||
671 |
|
667 | |||
672 | class AutoMagicChecker(PrefilterChecker): |
|
668 | class AutoMagicChecker(PrefilterChecker): | |
673 |
|
669 | |||
674 | priority = Int(700, config=True) |
|
670 | priority = Int(700, config=True) | |
675 |
|
671 | |||
676 | def check(self, line_info): |
|
672 | def check(self, line_info): | |
677 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
673 | """If the ifun is magic, and automagic is on, run it. Note: normal, | |
678 | non-auto magic would already have been triggered via '%' in |
|
674 | non-auto magic would already have been triggered via '%' in | |
679 | check_esc_chars. This just checks for automagic. Also, before |
|
675 | check_esc_chars. This just checks for automagic. Also, before | |
680 | triggering the magic handler, make sure that there is nothing in the |
|
676 | triggering the magic handler, make sure that there is nothing in the | |
681 | user namespace which could shadow it.""" |
|
677 | user namespace which could shadow it.""" | |
682 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): |
|
678 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): | |
683 | return None |
|
679 | return None | |
684 |
|
680 | |||
685 | # We have a likely magic method. Make sure we should actually call it. |
|
681 | # We have a likely magic method. Make sure we should actually call it. | |
686 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
682 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: | |
687 | return None |
|
683 | return None | |
688 |
|
684 | |||
689 | head = line_info.ifun.split('.',1)[0] |
|
685 | head = line_info.ifun.split('.',1)[0] | |
690 | if is_shadowed(head, self.shell): |
|
686 | if is_shadowed(head, self.shell): | |
691 | return None |
|
687 | return None | |
692 |
|
688 | |||
693 | return self.prefilter_manager.get_handler_by_name('magic') |
|
689 | return self.prefilter_manager.get_handler_by_name('magic') | |
694 |
|
690 | |||
695 |
|
691 | |||
696 | class AliasChecker(PrefilterChecker): |
|
692 | class AliasChecker(PrefilterChecker): | |
697 |
|
693 | |||
698 | priority = Int(800, config=True) |
|
694 | priority = Int(800, config=True) | |
699 |
|
695 | |||
700 | def check(self, line_info): |
|
696 | def check(self, line_info): | |
701 | "Check if the initital identifier on the line is an alias." |
|
697 | "Check if the initital identifier on the line is an alias." | |
702 | # Note: aliases can not contain '.' |
|
698 | # Note: aliases can not contain '.' | |
703 | head = line_info.ifun.split('.',1)[0] |
|
699 | head = line_info.ifun.split('.',1)[0] | |
704 | if line_info.ifun not in self.shell.alias_manager \ |
|
700 | if line_info.ifun not in self.shell.alias_manager \ | |
705 | or head not in self.shell.alias_manager \ |
|
701 | or head not in self.shell.alias_manager \ | |
706 | or is_shadowed(head, self.shell): |
|
702 | or is_shadowed(head, self.shell): | |
707 | return None |
|
703 | return None | |
708 |
|
704 | |||
709 | return self.prefilter_manager.get_handler_by_name('alias') |
|
705 | return self.prefilter_manager.get_handler_by_name('alias') | |
710 |
|
706 | |||
711 |
|
707 | |||
712 | class PythonOpsChecker(PrefilterChecker): |
|
708 | class PythonOpsChecker(PrefilterChecker): | |
713 |
|
709 | |||
714 | priority = Int(900, config=True) |
|
710 | priority = Int(900, config=True) | |
715 |
|
711 | |||
716 | def check(self, line_info): |
|
712 | def check(self, line_info): | |
717 | """If the 'rest' of the line begins with a function call or pretty much |
|
713 | """If the 'rest' of the line begins with a function call or pretty much | |
718 | any python operator, we should simply execute the line (regardless of |
|
714 | any python operator, we should simply execute the line (regardless of | |
719 | whether or not there's a possible autocall expansion). This avoids |
|
715 | whether or not there's a possible autocall expansion). This avoids | |
720 | spurious (and very confusing) geattr() accesses.""" |
|
716 | spurious (and very confusing) geattr() accesses.""" | |
721 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
717 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': | |
722 | return self.prefilter_manager.get_handler_by_name('normal') |
|
718 | return self.prefilter_manager.get_handler_by_name('normal') | |
723 | else: |
|
719 | else: | |
724 | return None |
|
720 | return None | |
725 |
|
721 | |||
726 |
|
722 | |||
727 | class AutocallChecker(PrefilterChecker): |
|
723 | class AutocallChecker(PrefilterChecker): | |
728 |
|
724 | |||
729 | priority = Int(1000, config=True) |
|
725 | priority = Int(1000, config=True) | |
730 |
|
726 | |||
731 | def check(self, line_info): |
|
727 | def check(self, line_info): | |
732 | "Check if the initial word/function is callable and autocall is on." |
|
728 | "Check if the initial word/function is callable and autocall is on." | |
733 | if not self.shell.autocall: |
|
729 | if not self.shell.autocall: | |
734 | return None |
|
730 | return None | |
735 |
|
731 | |||
736 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
732 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr | |
737 | if not oinfo['found']: |
|
733 | if not oinfo['found']: | |
738 | return None |
|
734 | return None | |
739 |
|
735 | |||
740 | if callable(oinfo['obj']) \ |
|
736 | if callable(oinfo['obj']) \ | |
741 | and (not re_exclude_auto.match(line_info.the_rest)) \ |
|
737 | and (not re_exclude_auto.match(line_info.the_rest)) \ | |
742 | and re_fun_name.match(line_info.ifun): |
|
738 | and re_fun_name.match(line_info.ifun): | |
743 | return self.prefilter_manager.get_handler_by_name('auto') |
|
739 | return self.prefilter_manager.get_handler_by_name('auto') | |
744 | else: |
|
740 | else: | |
745 | return None |
|
741 | return None | |
746 |
|
742 | |||
747 |
|
743 | |||
748 | #----------------------------------------------------------------------------- |
|
744 | #----------------------------------------------------------------------------- | |
749 | # Prefilter handlers |
|
745 | # Prefilter handlers | |
750 | #----------------------------------------------------------------------------- |
|
746 | #----------------------------------------------------------------------------- | |
751 |
|
747 | |||
752 |
|
748 | |||
753 | class PrefilterHandler(Configurable): |
|
749 | class PrefilterHandler(Configurable): | |
754 |
|
750 | |||
755 | handler_name = Str('normal') |
|
751 | handler_name = Str('normal') | |
756 | esc_strings = List([]) |
|
752 | esc_strings = List([]) | |
757 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
753 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
758 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
754 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
759 |
|
755 | |||
760 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
756 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
761 | super(PrefilterHandler, self).__init__( |
|
757 | super(PrefilterHandler, self).__init__( | |
762 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
758 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
763 | ) |
|
759 | ) | |
764 | self.prefilter_manager.register_handler( |
|
760 | self.prefilter_manager.register_handler( | |
765 | self.handler_name, |
|
761 | self.handler_name, | |
766 | self, |
|
762 | self, | |
767 | self.esc_strings |
|
763 | self.esc_strings | |
768 | ) |
|
764 | ) | |
769 |
|
765 | |||
770 | def handle(self, line_info): |
|
766 | def handle(self, line_info): | |
771 | # print "normal: ", line_info |
|
767 | # print "normal: ", line_info | |
772 | """Handle normal input lines. Use as a template for handlers.""" |
|
768 | """Handle normal input lines. Use as a template for handlers.""" | |
773 |
|
769 | |||
774 | # With autoindent on, we need some way to exit the input loop, and I |
|
770 | # With autoindent on, we need some way to exit the input loop, and I | |
775 | # don't want to force the user to have to backspace all the way to |
|
771 | # don't want to force the user to have to backspace all the way to | |
776 | # clear the line. The rule will be in this case, that either two |
|
772 | # clear the line. The rule will be in this case, that either two | |
777 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
773 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
778 | # of a size different to the indent level, will exit the input loop. |
|
774 | # of a size different to the indent level, will exit the input loop. | |
779 | line = line_info.line |
|
775 | line = line_info.line | |
780 | continue_prompt = line_info.continue_prompt |
|
776 | continue_prompt = line_info.continue_prompt | |
781 |
|
777 | |||
782 | if (continue_prompt and |
|
778 | if (continue_prompt and | |
783 | self.shell.autoindent and |
|
779 | self.shell.autoindent and | |
784 | line.isspace() and |
|
780 | line.isspace() and | |
785 |
|
781 | |||
786 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 |
|
782 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 | |
787 | or |
|
783 | or | |
788 | not self.shell.buffer |
|
784 | not self.shell.buffer | |
789 | or |
|
785 | or | |
790 | (self.shell.buffer[-1]).isspace() |
|
786 | (self.shell.buffer[-1]).isspace() | |
791 | ) |
|
787 | ) | |
792 | ): |
|
788 | ): | |
793 | line = '' |
|
789 | line = '' | |
794 |
|
790 | |||
795 | self.shell.log(line, line, continue_prompt) |
|
|||
796 | return line |
|
791 | return line | |
797 |
|
792 | |||
798 | def __str__(self): |
|
793 | def __str__(self): | |
799 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
794 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) | |
800 |
|
795 | |||
801 |
|
796 | |||
802 | class AliasHandler(PrefilterHandler): |
|
797 | class AliasHandler(PrefilterHandler): | |
803 |
|
798 | |||
804 | handler_name = Str('alias') |
|
799 | handler_name = Str('alias') | |
805 |
|
800 | |||
806 | def handle(self, line_info): |
|
801 | def handle(self, line_info): | |
807 | """Handle alias input lines. """ |
|
802 | """Handle alias input lines. """ | |
808 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) |
|
803 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) | |
809 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
804 | # pre is needed, because it carries the leading whitespace. Otherwise | |
810 | # aliases won't work in indented sections. |
|
805 | # aliases won't work in indented sections. | |
811 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
806 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
812 | make_quoted_expr(transformed)) |
|
807 | make_quoted_expr(transformed)) | |
813 |
|
808 | |||
814 | self.shell.log(line_info.line, line_out, line_info.continue_prompt) |
|
|||
815 | return line_out |
|
809 | return line_out | |
816 |
|
810 | |||
817 |
|
811 | |||
818 | class ShellEscapeHandler(PrefilterHandler): |
|
812 | class ShellEscapeHandler(PrefilterHandler): | |
819 |
|
813 | |||
820 | handler_name = Str('shell') |
|
814 | handler_name = Str('shell') | |
821 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) |
|
815 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) | |
822 |
|
816 | |||
823 | def handle(self, line_info): |
|
817 | def handle(self, line_info): | |
824 | """Execute the line in a shell, empty return value""" |
|
818 | """Execute the line in a shell, empty return value""" | |
825 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') |
|
819 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') | |
826 |
|
820 | |||
827 | line = line_info.line |
|
821 | line = line_info.line | |
828 | if line.lstrip().startswith(ESC_SH_CAP): |
|
822 | if line.lstrip().startswith(ESC_SH_CAP): | |
829 | # rewrite LineInfo's line, ifun and the_rest to properly hold the |
|
823 | # rewrite LineInfo's line, ifun and the_rest to properly hold the | |
830 | # call to %sx and the actual command to be executed, so |
|
824 | # call to %sx and the actual command to be executed, so | |
831 | # handle_magic can work correctly. Note that this works even if |
|
825 | # handle_magic can work correctly. Note that this works even if | |
832 | # the line is indented, so it handles multi_line_specials |
|
826 | # the line is indented, so it handles multi_line_specials | |
833 | # properly. |
|
827 | # properly. | |
834 | new_rest = line.lstrip()[2:] |
|
828 | new_rest = line.lstrip()[2:] | |
835 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) |
|
829 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) | |
836 | line_info.ifun = 'sx' |
|
830 | line_info.ifun = 'sx' | |
837 | line_info.the_rest = new_rest |
|
831 | line_info.the_rest = new_rest | |
838 | return magic_handler.handle(line_info) |
|
832 | return magic_handler.handle(line_info) | |
839 | else: |
|
833 | else: | |
840 | cmd = line.lstrip().lstrip(ESC_SHELL) |
|
834 | cmd = line.lstrip().lstrip(ESC_SHELL) | |
841 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
835 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
842 | make_quoted_expr(cmd)) |
|
836 | make_quoted_expr(cmd)) | |
843 | # update cache/log and return |
|
|||
844 | self.shell.log(line, line_out, line_info.continue_prompt) |
|
|||
845 | return line_out |
|
837 | return line_out | |
846 |
|
838 | |||
847 |
|
839 | |||
848 | class MagicHandler(PrefilterHandler): |
|
840 | class MagicHandler(PrefilterHandler): | |
849 |
|
841 | |||
850 | handler_name = Str('magic') |
|
842 | handler_name = Str('magic') | |
851 | esc_strings = List([ESC_MAGIC]) |
|
843 | esc_strings = List([ESC_MAGIC]) | |
852 |
|
844 | |||
853 | def handle(self, line_info): |
|
845 | def handle(self, line_info): | |
854 | """Execute magic functions.""" |
|
846 | """Execute magic functions.""" | |
855 | ifun = line_info.ifun |
|
847 | ifun = line_info.ifun | |
856 | the_rest = line_info.the_rest |
|
848 | the_rest = line_info.the_rest | |
857 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, |
|
849 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, | |
858 | make_quoted_expr(ifun + " " + the_rest)) |
|
850 | make_quoted_expr(ifun + " " + the_rest)) | |
859 | self.shell.log(line_info.line, cmd, line_info.continue_prompt) |
|
|||
860 | return cmd |
|
851 | return cmd | |
861 |
|
852 | |||
862 |
|
853 | |||
863 | class AutoHandler(PrefilterHandler): |
|
854 | class AutoHandler(PrefilterHandler): | |
864 |
|
855 | |||
865 | handler_name = Str('auto') |
|
856 | handler_name = Str('auto') | |
866 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
857 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) | |
867 |
|
858 | |||
868 | def handle(self, line_info): |
|
859 | def handle(self, line_info): | |
869 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
860 | """Handle lines which can be auto-executed, quoting if requested.""" | |
870 | line = line_info.line |
|
861 | line = line_info.line | |
871 | ifun = line_info.ifun |
|
862 | ifun = line_info.ifun | |
872 | the_rest = line_info.the_rest |
|
863 | the_rest = line_info.the_rest | |
873 | pre = line_info.pre |
|
864 | pre = line_info.pre | |
874 | continue_prompt = line_info.continue_prompt |
|
865 | continue_prompt = line_info.continue_prompt | |
875 | obj = line_info.ofind(self)['obj'] |
|
866 | obj = line_info.ofind(self)['obj'] | |
876 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
867 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg | |
877 |
|
868 | |||
878 | # This should only be active for single-line input! |
|
869 | # This should only be active for single-line input! | |
879 | if continue_prompt: |
|
870 | if continue_prompt: | |
880 | self.shell.log(line,line,continue_prompt) |
|
|||
881 | return line |
|
871 | return line | |
882 |
|
872 | |||
883 | force_auto = isinstance(obj, IPyAutocall) |
|
873 | force_auto = isinstance(obj, IPyAutocall) | |
884 | auto_rewrite = True |
|
874 | auto_rewrite = True | |
885 |
|
875 | |||
886 | if pre == ESC_QUOTE: |
|
876 | if pre == ESC_QUOTE: | |
887 | # Auto-quote splitting on whitespace |
|
877 | # Auto-quote splitting on whitespace | |
888 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
878 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) | |
889 | elif pre == ESC_QUOTE2: |
|
879 | elif pre == ESC_QUOTE2: | |
890 | # Auto-quote whole string |
|
880 | # Auto-quote whole string | |
891 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
881 | newcmd = '%s("%s")' % (ifun,the_rest) | |
892 | elif pre == ESC_PAREN: |
|
882 | elif pre == ESC_PAREN: | |
893 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
883 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) | |
894 | else: |
|
884 | else: | |
895 | # Auto-paren. |
|
885 | # Auto-paren. | |
896 | # We only apply it to argument-less calls if the autocall |
|
886 | # We only apply it to argument-less calls if the autocall | |
897 | # parameter is set to 2. We only need to check that autocall is < |
|
887 | # parameter is set to 2. We only need to check that autocall is < | |
898 | # 2, since this function isn't called unless it's at least 1. |
|
888 | # 2, since this function isn't called unless it's at least 1. | |
899 | if not the_rest and (self.shell.autocall < 2) and not force_auto: |
|
889 | if not the_rest and (self.shell.autocall < 2) and not force_auto: | |
900 | newcmd = '%s %s' % (ifun,the_rest) |
|
890 | newcmd = '%s %s' % (ifun,the_rest) | |
901 | auto_rewrite = False |
|
891 | auto_rewrite = False | |
902 | else: |
|
892 | else: | |
903 | if not force_auto and the_rest.startswith('['): |
|
893 | if not force_auto and the_rest.startswith('['): | |
904 | if hasattr(obj,'__getitem__'): |
|
894 | if hasattr(obj,'__getitem__'): | |
905 | # Don't autocall in this case: item access for an object |
|
895 | # Don't autocall in this case: item access for an object | |
906 | # which is BOTH callable and implements __getitem__. |
|
896 | # which is BOTH callable and implements __getitem__. | |
907 | newcmd = '%s %s' % (ifun,the_rest) |
|
897 | newcmd = '%s %s' % (ifun,the_rest) | |
908 | auto_rewrite = False |
|
898 | auto_rewrite = False | |
909 | else: |
|
899 | else: | |
910 | # if the object doesn't support [] access, go ahead and |
|
900 | # if the object doesn't support [] access, go ahead and | |
911 | # autocall |
|
901 | # autocall | |
912 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) |
|
902 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) | |
913 | elif the_rest.endswith(';'): |
|
903 | elif the_rest.endswith(';'): | |
914 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
904 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) | |
915 | else: |
|
905 | else: | |
916 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
906 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) | |
917 |
|
907 | |||
918 | if auto_rewrite: |
|
908 | if auto_rewrite: | |
919 | self.shell.auto_rewrite_input(newcmd) |
|
909 | self.shell.auto_rewrite_input(newcmd) | |
920 |
|
910 | |||
921 | # log what is now valid Python, not the actual user input (without the |
|
|||
922 | # final newline) |
|
|||
923 | self.shell.log(line,newcmd,continue_prompt) |
|
|||
924 | return newcmd |
|
911 | return newcmd | |
925 |
|
912 | |||
926 |
|
913 | |||
927 | class HelpHandler(PrefilterHandler): |
|
914 | class HelpHandler(PrefilterHandler): | |
928 |
|
915 | |||
929 | handler_name = Str('help') |
|
916 | handler_name = Str('help') | |
930 | esc_strings = List([ESC_HELP]) |
|
917 | esc_strings = List([ESC_HELP]) | |
931 |
|
918 | |||
932 | def handle(self, line_info): |
|
919 | def handle(self, line_info): | |
933 | """Try to get some help for the object. |
|
920 | """Try to get some help for the object. | |
934 |
|
921 | |||
935 | obj? or ?obj -> basic information. |
|
922 | obj? or ?obj -> basic information. | |
936 | obj?? or ??obj -> more details. |
|
923 | obj?? or ??obj -> more details. | |
937 | """ |
|
924 | """ | |
938 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
925 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') | |
939 | line = line_info.line |
|
926 | line = line_info.line | |
940 | # We need to make sure that we don't process lines which would be |
|
927 | # We need to make sure that we don't process lines which would be | |
941 | # otherwise valid python, such as "x=1 # what?" |
|
928 | # otherwise valid python, such as "x=1 # what?" | |
942 | try: |
|
929 | try: | |
943 | codeop.compile_command(line) |
|
930 | codeop.compile_command(line) | |
944 | except SyntaxError: |
|
931 | except SyntaxError: | |
945 | # We should only handle as help stuff which is NOT valid syntax |
|
932 | # We should only handle as help stuff which is NOT valid syntax | |
946 | if line[0]==ESC_HELP: |
|
933 | if line[0]==ESC_HELP: | |
947 | line = line[1:] |
|
934 | line = line[1:] | |
948 | elif line[-1]==ESC_HELP: |
|
935 | elif line[-1]==ESC_HELP: | |
949 | line = line[:-1] |
|
936 | line = line[:-1] | |
950 | self.shell.log(line, '#?'+line, line_info.continue_prompt) |
|
|||
951 | if line: |
|
937 | if line: | |
952 | #print 'line:<%r>' % line # dbg |
|
938 | #print 'line:<%r>' % line # dbg | |
953 | self.shell.magic_pinfo(line) |
|
939 | self.shell.magic_pinfo(line) | |
954 | else: |
|
940 | else: | |
955 | self.shell.show_usage() |
|
941 | self.shell.show_usage() | |
956 | return '' # Empty string is needed here! |
|
942 | return '' # Empty string is needed here! | |
957 | except: |
|
943 | except: | |
958 | raise |
|
944 | raise | |
959 | # Pass any other exceptions through to the normal handler |
|
945 | # Pass any other exceptions through to the normal handler | |
960 | return normal_handler.handle(line_info) |
|
946 | return normal_handler.handle(line_info) | |
961 | else: |
|
947 | else: | |
962 | # If the code compiles ok, we should handle it normally |
|
948 | # If the code compiles ok, we should handle it normally | |
963 | return normal_handler.handle(line_info) |
|
949 | return normal_handler.handle(line_info) | |
964 |
|
950 | |||
965 |
|
951 | |||
966 | class EmacsHandler(PrefilterHandler): |
|
952 | class EmacsHandler(PrefilterHandler): | |
967 |
|
953 | |||
968 | handler_name = Str('emacs') |
|
954 | handler_name = Str('emacs') | |
969 | esc_strings = List([]) |
|
955 | esc_strings = List([]) | |
970 |
|
956 | |||
971 | def handle(self, line_info): |
|
957 | def handle(self, line_info): | |
972 | """Handle input lines marked by python-mode.""" |
|
958 | """Handle input lines marked by python-mode.""" | |
973 |
|
959 | |||
974 | # Currently, nothing is done. Later more functionality can be added |
|
960 | # Currently, nothing is done. Later more functionality can be added | |
975 | # here if needed. |
|
961 | # here if needed. | |
976 |
|
962 | |||
977 | # The input cache shouldn't be updated |
|
963 | # The input cache shouldn't be updated | |
978 | return line_info.line |
|
964 | return line_info.line | |
979 |
|
965 | |||
980 |
|
966 | |||
981 | #----------------------------------------------------------------------------- |
|
967 | #----------------------------------------------------------------------------- | |
982 | # Defaults |
|
968 | # Defaults | |
983 | #----------------------------------------------------------------------------- |
|
969 | #----------------------------------------------------------------------------- | |
984 |
|
970 | |||
985 |
|
971 | |||
986 | _default_transformers = [ |
|
972 | _default_transformers = [ | |
987 | AssignSystemTransformer, |
|
973 | AssignSystemTransformer, | |
988 | AssignMagicTransformer, |
|
974 | AssignMagicTransformer, | |
989 | PyPromptTransformer, |
|
975 | PyPromptTransformer, | |
990 | IPyPromptTransformer, |
|
976 | IPyPromptTransformer, | |
991 | ] |
|
977 | ] | |
992 |
|
978 | |||
993 | _default_checkers = [ |
|
979 | _default_checkers = [ | |
994 | EmacsChecker, |
|
980 | EmacsChecker, | |
995 | ShellEscapeChecker, |
|
981 | ShellEscapeChecker, | |
996 | IPyAutocallChecker, |
|
982 | IPyAutocallChecker, | |
997 | MultiLineMagicChecker, |
|
983 | MultiLineMagicChecker, | |
998 | EscCharsChecker, |
|
984 | EscCharsChecker, | |
999 | AssignmentChecker, |
|
985 | AssignmentChecker, | |
1000 | AutoMagicChecker, |
|
986 | AutoMagicChecker, | |
1001 | AliasChecker, |
|
987 | AliasChecker, | |
1002 | PythonOpsChecker, |
|
988 | PythonOpsChecker, | |
1003 | AutocallChecker |
|
989 | AutocallChecker | |
1004 | ] |
|
990 | ] | |
1005 |
|
991 | |||
1006 | _default_handlers = [ |
|
992 | _default_handlers = [ | |
1007 | PrefilterHandler, |
|
993 | PrefilterHandler, | |
1008 | AliasHandler, |
|
994 | AliasHandler, | |
1009 | ShellEscapeHandler, |
|
995 | ShellEscapeHandler, | |
1010 | MagicHandler, |
|
996 | MagicHandler, | |
1011 | AutoHandler, |
|
997 | AutoHandler, | |
1012 | HelpHandler, |
|
998 | HelpHandler, | |
1013 | EmacsHandler |
|
999 | EmacsHandler | |
1014 | ] |
|
1000 | ] |
@@ -1,444 +1,436 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Classes for handling input/output prompts. |
|
2 | """Classes for handling input/output prompts. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Fernando Perez |
|
6 | * Fernando Perez | |
7 | * Brian Granger |
|
7 | * Brian Granger | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2010 The IPython Development Team |
|
11 | # Copyright (C) 2008-2010 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | import os |
|
22 | import os | |
23 | import re |
|
23 | import re | |
24 | import socket |
|
24 | import socket | |
25 | import sys |
|
25 | import sys | |
26 |
|
26 | |||
27 | from IPython.core import release |
|
27 | from IPython.core import release | |
28 | from IPython.external.Itpl import ItplNS |
|
28 | from IPython.external.Itpl import ItplNS | |
29 | from IPython.utils import coloransi |
|
29 | from IPython.utils import coloransi | |
30 |
|
30 | |||
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 | # Color schemes for prompts |
|
32 | # Color schemes for prompts | |
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 |
|
34 | |||
35 | PromptColors = coloransi.ColorSchemeTable() |
|
35 | PromptColors = coloransi.ColorSchemeTable() | |
36 | InputColors = coloransi.InputTermColors # just a shorthand |
|
36 | InputColors = coloransi.InputTermColors # just a shorthand | |
37 | Colors = coloransi.TermColors # just a shorthand |
|
37 | Colors = coloransi.TermColors # just a shorthand | |
38 |
|
38 | |||
39 | PromptColors.add_scheme(coloransi.ColorScheme( |
|
39 | PromptColors.add_scheme(coloransi.ColorScheme( | |
40 | 'NoColor', |
|
40 | 'NoColor', | |
41 | in_prompt = InputColors.NoColor, # Input prompt |
|
41 | in_prompt = InputColors.NoColor, # Input prompt | |
42 | in_number = InputColors.NoColor, # Input prompt number |
|
42 | in_number = InputColors.NoColor, # Input prompt number | |
43 | in_prompt2 = InputColors.NoColor, # Continuation prompt |
|
43 | in_prompt2 = InputColors.NoColor, # Continuation prompt | |
44 | in_normal = InputColors.NoColor, # color off (usu. Colors.Normal) |
|
44 | in_normal = InputColors.NoColor, # color off (usu. Colors.Normal) | |
45 |
|
45 | |||
46 | out_prompt = Colors.NoColor, # Output prompt |
|
46 | out_prompt = Colors.NoColor, # Output prompt | |
47 | out_number = Colors.NoColor, # Output prompt number |
|
47 | out_number = Colors.NoColor, # Output prompt number | |
48 |
|
48 | |||
49 | normal = Colors.NoColor # color off (usu. Colors.Normal) |
|
49 | normal = Colors.NoColor # color off (usu. Colors.Normal) | |
50 | )) |
|
50 | )) | |
51 |
|
51 | |||
52 | # make some schemes as instances so we can copy them for modification easily: |
|
52 | # make some schemes as instances so we can copy them for modification easily: | |
53 | __PColLinux = coloransi.ColorScheme( |
|
53 | __PColLinux = coloransi.ColorScheme( | |
54 | 'Linux', |
|
54 | 'Linux', | |
55 | in_prompt = InputColors.Green, |
|
55 | in_prompt = InputColors.Green, | |
56 | in_number = InputColors.LightGreen, |
|
56 | in_number = InputColors.LightGreen, | |
57 | in_prompt2 = InputColors.Green, |
|
57 | in_prompt2 = InputColors.Green, | |
58 | in_normal = InputColors.Normal, # color off (usu. Colors.Normal) |
|
58 | in_normal = InputColors.Normal, # color off (usu. Colors.Normal) | |
59 |
|
59 | |||
60 | out_prompt = Colors.Red, |
|
60 | out_prompt = Colors.Red, | |
61 | out_number = Colors.LightRed, |
|
61 | out_number = Colors.LightRed, | |
62 |
|
62 | |||
63 | normal = Colors.Normal |
|
63 | normal = Colors.Normal | |
64 | ) |
|
64 | ) | |
65 | # Don't forget to enter it into the table! |
|
65 | # Don't forget to enter it into the table! | |
66 | PromptColors.add_scheme(__PColLinux) |
|
66 | PromptColors.add_scheme(__PColLinux) | |
67 |
|
67 | |||
68 | # Slightly modified Linux for light backgrounds |
|
68 | # Slightly modified Linux for light backgrounds | |
69 | __PColLightBG = __PColLinux.copy('LightBG') |
|
69 | __PColLightBG = __PColLinux.copy('LightBG') | |
70 |
|
70 | |||
71 | __PColLightBG.colors.update( |
|
71 | __PColLightBG.colors.update( | |
72 | in_prompt = InputColors.Blue, |
|
72 | in_prompt = InputColors.Blue, | |
73 | in_number = InputColors.LightBlue, |
|
73 | in_number = InputColors.LightBlue, | |
74 | in_prompt2 = InputColors.Blue |
|
74 | in_prompt2 = InputColors.Blue | |
75 | ) |
|
75 | ) | |
76 | PromptColors.add_scheme(__PColLightBG) |
|
76 | PromptColors.add_scheme(__PColLightBG) | |
77 |
|
77 | |||
78 | del Colors,InputColors |
|
78 | del Colors,InputColors | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | def multiple_replace(dict, text): |
|
84 | def multiple_replace(dict, text): | |
85 | """ Replace in 'text' all occurences of any key in the given |
|
85 | """ Replace in 'text' all occurences of any key in the given | |
86 | dictionary by its corresponding value. Returns the new string.""" |
|
86 | dictionary by its corresponding value. Returns the new string.""" | |
87 |
|
87 | |||
88 | # Function by Xavier Defrang, originally found at: |
|
88 | # Function by Xavier Defrang, originally found at: | |
89 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 |
|
89 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 | |
90 |
|
90 | |||
91 | # Create a regular expression from the dictionary keys |
|
91 | # Create a regular expression from the dictionary keys | |
92 | regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) |
|
92 | regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) | |
93 | # For each match, look-up corresponding value in dictionary |
|
93 | # For each match, look-up corresponding value in dictionary | |
94 | return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) |
|
94 | return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) | |
95 |
|
95 | |||
96 | #----------------------------------------------------------------------------- |
|
96 | #----------------------------------------------------------------------------- | |
97 | # Special characters that can be used in prompt templates, mainly bash-like |
|
97 | # Special characters that can be used in prompt templates, mainly bash-like | |
98 | #----------------------------------------------------------------------------- |
|
98 | #----------------------------------------------------------------------------- | |
99 |
|
99 | |||
100 | # If $HOME isn't defined (Windows), make it an absurd string so that it can |
|
100 | # If $HOME isn't defined (Windows), make it an absurd string so that it can | |
101 | # never be expanded out into '~'. Basically anything which can never be a |
|
101 | # never be expanded out into '~'. Basically anything which can never be a | |
102 | # reasonable directory name will do, we just want the $HOME -> '~' operation |
|
102 | # reasonable directory name will do, we just want the $HOME -> '~' operation | |
103 | # to become a no-op. We pre-compute $HOME here so it's not done on every |
|
103 | # to become a no-op. We pre-compute $HOME here so it's not done on every | |
104 | # prompt call. |
|
104 | # prompt call. | |
105 |
|
105 | |||
106 | # FIXME: |
|
106 | # FIXME: | |
107 |
|
107 | |||
108 | # - This should be turned into a class which does proper namespace management, |
|
108 | # - This should be turned into a class which does proper namespace management, | |
109 | # since the prompt specials need to be evaluated in a certain namespace. |
|
109 | # since the prompt specials need to be evaluated in a certain namespace. | |
110 | # Currently it's just globals, which need to be managed manually by code |
|
110 | # Currently it's just globals, which need to be managed manually by code | |
111 | # below. |
|
111 | # below. | |
112 |
|
112 | |||
113 | # - I also need to split up the color schemes from the prompt specials |
|
113 | # - I also need to split up the color schemes from the prompt specials | |
114 | # somehow. I don't have a clean design for that quite yet. |
|
114 | # somehow. I don't have a clean design for that quite yet. | |
115 |
|
115 | |||
116 | HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~") |
|
116 | HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~") | |
117 |
|
117 | |||
118 | # We precompute a few more strings here for the prompt_specials, which are |
|
118 | # We precompute a few more strings here for the prompt_specials, which are | |
119 | # fixed once ipython starts. This reduces the runtime overhead of computing |
|
119 | # fixed once ipython starts. This reduces the runtime overhead of computing | |
120 | # prompt strings. |
|
120 | # prompt strings. | |
121 | USER = os.environ.get("USER") |
|
121 | USER = os.environ.get("USER") | |
122 | HOSTNAME = socket.gethostname() |
|
122 | HOSTNAME = socket.gethostname() | |
123 | HOSTNAME_SHORT = HOSTNAME.split(".")[0] |
|
123 | HOSTNAME_SHORT = HOSTNAME.split(".")[0] | |
124 | ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0] |
|
124 | ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0] | |
125 |
|
125 | |||
126 | prompt_specials_color = { |
|
126 | prompt_specials_color = { | |
127 | # Prompt/history count |
|
127 | # Prompt/history count | |
128 | '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', |
|
128 | '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', | |
129 | r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', |
|
129 | r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}', | |
130 | # Just the prompt counter number, WITHOUT any coloring wrappers, so users |
|
130 | # Just the prompt counter number, WITHOUT any coloring wrappers, so users | |
131 | # can get numbers displayed in whatever color they want. |
|
131 | # can get numbers displayed in whatever color they want. | |
132 | r'\N': '${self.cache.prompt_count}', |
|
132 | r'\N': '${self.cache.prompt_count}', | |
133 |
|
133 | |||
134 | # Prompt/history count, with the actual digits replaced by dots. Used |
|
134 | # Prompt/history count, with the actual digits replaced by dots. Used | |
135 | # mainly in continuation prompts (prompt_in2) |
|
135 | # mainly in continuation prompts (prompt_in2) | |
136 | #r'\D': '${"."*len(str(self.cache.prompt_count))}', |
|
136 | #r'\D': '${"."*len(str(self.cache.prompt_count))}', | |
137 |
|
137 | |||
138 | # More robust form of the above expression, that uses the __builtin__ |
|
138 | # More robust form of the above expression, that uses the __builtin__ | |
139 | # module. Note that we can NOT use __builtins__ (note the 's'), because |
|
139 | # module. Note that we can NOT use __builtins__ (note the 's'), because | |
140 | # that can either be a dict or a module, and can even mutate at runtime, |
|
140 | # that can either be a dict or a module, and can even mutate at runtime, | |
141 | # depending on the context (Python makes no guarantees on it). In |
|
141 | # depending on the context (Python makes no guarantees on it). In | |
142 | # contrast, __builtin__ is always a module object, though it must be |
|
142 | # contrast, __builtin__ is always a module object, though it must be | |
143 | # explicitly imported. |
|
143 | # explicitly imported. | |
144 | r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}', |
|
144 | r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}', | |
145 |
|
145 | |||
146 | # Current working directory |
|
146 | # Current working directory | |
147 | r'\w': '${os.getcwd()}', |
|
147 | r'\w': '${os.getcwd()}', | |
148 | # Current time |
|
148 | # Current time | |
149 | r'\t' : '${time.strftime("%H:%M:%S")}', |
|
149 | r'\t' : '${time.strftime("%H:%M:%S")}', | |
150 | # Basename of current working directory. |
|
150 | # Basename of current working directory. | |
151 | # (use os.sep to make this portable across OSes) |
|
151 | # (use os.sep to make this portable across OSes) | |
152 | r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep, |
|
152 | r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep, | |
153 | # These X<N> are an extension to the normal bash prompts. They return |
|
153 | # These X<N> are an extension to the normal bash prompts. They return | |
154 | # N terms of the path, after replacing $HOME with '~' |
|
154 | # N terms of the path, after replacing $HOME with '~' | |
155 | r'\X0': '${os.getcwd().replace("%s","~")}' % HOME, |
|
155 | r'\X0': '${os.getcwd().replace("%s","~")}' % HOME, | |
156 | r'\X1': '${self.cwd_filt(1)}', |
|
156 | r'\X1': '${self.cwd_filt(1)}', | |
157 | r'\X2': '${self.cwd_filt(2)}', |
|
157 | r'\X2': '${self.cwd_filt(2)}', | |
158 | r'\X3': '${self.cwd_filt(3)}', |
|
158 | r'\X3': '${self.cwd_filt(3)}', | |
159 | r'\X4': '${self.cwd_filt(4)}', |
|
159 | r'\X4': '${self.cwd_filt(4)}', | |
160 | r'\X5': '${self.cwd_filt(5)}', |
|
160 | r'\X5': '${self.cwd_filt(5)}', | |
161 | # Y<N> are similar to X<N>, but they show '~' if it's the directory |
|
161 | # Y<N> are similar to X<N>, but they show '~' if it's the directory | |
162 | # N+1 in the list. Somewhat like %cN in tcsh. |
|
162 | # N+1 in the list. Somewhat like %cN in tcsh. | |
163 | r'\Y0': '${self.cwd_filt2(0)}', |
|
163 | r'\Y0': '${self.cwd_filt2(0)}', | |
164 | r'\Y1': '${self.cwd_filt2(1)}', |
|
164 | r'\Y1': '${self.cwd_filt2(1)}', | |
165 | r'\Y2': '${self.cwd_filt2(2)}', |
|
165 | r'\Y2': '${self.cwd_filt2(2)}', | |
166 | r'\Y3': '${self.cwd_filt2(3)}', |
|
166 | r'\Y3': '${self.cwd_filt2(3)}', | |
167 | r'\Y4': '${self.cwd_filt2(4)}', |
|
167 | r'\Y4': '${self.cwd_filt2(4)}', | |
168 | r'\Y5': '${self.cwd_filt2(5)}', |
|
168 | r'\Y5': '${self.cwd_filt2(5)}', | |
169 | # Hostname up to first . |
|
169 | # Hostname up to first . | |
170 | r'\h': HOSTNAME_SHORT, |
|
170 | r'\h': HOSTNAME_SHORT, | |
171 | # Full hostname |
|
171 | # Full hostname | |
172 | r'\H': HOSTNAME, |
|
172 | r'\H': HOSTNAME, | |
173 | # Username of current user |
|
173 | # Username of current user | |
174 | r'\u': USER, |
|
174 | r'\u': USER, | |
175 | # Escaped '\' |
|
175 | # Escaped '\' | |
176 | '\\\\': '\\', |
|
176 | '\\\\': '\\', | |
177 | # Newline |
|
177 | # Newline | |
178 | r'\n': '\n', |
|
178 | r'\n': '\n', | |
179 | # Carriage return |
|
179 | # Carriage return | |
180 | r'\r': '\r', |
|
180 | r'\r': '\r', | |
181 | # Release version |
|
181 | # Release version | |
182 | r'\v': release.version, |
|
182 | r'\v': release.version, | |
183 | # Root symbol ($ or #) |
|
183 | # Root symbol ($ or #) | |
184 | r'\$': ROOT_SYMBOL, |
|
184 | r'\$': ROOT_SYMBOL, | |
185 | } |
|
185 | } | |
186 |
|
186 | |||
187 | # A copy of the prompt_specials dictionary but with all color escapes removed, |
|
187 | # A copy of the prompt_specials dictionary but with all color escapes removed, | |
188 | # so we can correctly compute the prompt length for the auto_rewrite method. |
|
188 | # so we can correctly compute the prompt length for the auto_rewrite method. | |
189 | prompt_specials_nocolor = prompt_specials_color.copy() |
|
189 | prompt_specials_nocolor = prompt_specials_color.copy() | |
190 | prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}' |
|
190 | prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}' | |
191 | prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}' |
|
191 | prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}' | |
192 |
|
192 | |||
193 | # Add in all the InputTermColors color escapes as valid prompt characters. |
|
193 | # Add in all the InputTermColors color escapes as valid prompt characters. | |
194 | # They all get added as \\C_COLORNAME, so that we don't have any conflicts |
|
194 | # They all get added as \\C_COLORNAME, so that we don't have any conflicts | |
195 | # with a color name which may begin with a letter used by any other of the |
|
195 | # with a color name which may begin with a letter used by any other of the | |
196 | # allowed specials. This of course means that \\C will never be allowed for |
|
196 | # allowed specials. This of course means that \\C will never be allowed for | |
197 | # anything else. |
|
197 | # anything else. | |
198 | input_colors = coloransi.InputTermColors |
|
198 | input_colors = coloransi.InputTermColors | |
199 | for _color in dir(input_colors): |
|
199 | for _color in dir(input_colors): | |
200 | if _color[0] != '_': |
|
200 | if _color[0] != '_': | |
201 | c_name = r'\C_'+_color |
|
201 | c_name = r'\C_'+_color | |
202 | prompt_specials_color[c_name] = getattr(input_colors,_color) |
|
202 | prompt_specials_color[c_name] = getattr(input_colors,_color) | |
203 | prompt_specials_nocolor[c_name] = '' |
|
203 | prompt_specials_nocolor[c_name] = '' | |
204 |
|
204 | |||
205 | # we default to no color for safety. Note that prompt_specials is a global |
|
205 | # we default to no color for safety. Note that prompt_specials is a global | |
206 | # variable used by all prompt objects. |
|
206 | # variable used by all prompt objects. | |
207 | prompt_specials = prompt_specials_nocolor |
|
207 | prompt_specials = prompt_specials_nocolor | |
208 |
|
208 | |||
209 | #----------------------------------------------------------------------------- |
|
209 | #----------------------------------------------------------------------------- | |
210 | # More utilities |
|
210 | # More utilities | |
211 | #----------------------------------------------------------------------------- |
|
211 | #----------------------------------------------------------------------------- | |
212 |
|
212 | |||
213 | def str_safe(arg): |
|
213 | def str_safe(arg): | |
214 | """Convert to a string, without ever raising an exception. |
|
214 | """Convert to a string, without ever raising an exception. | |
215 |
|
215 | |||
216 | If str(arg) fails, <ERROR: ... > is returned, where ... is the exception |
|
216 | If str(arg) fails, <ERROR: ... > is returned, where ... is the exception | |
217 | error message.""" |
|
217 | error message.""" | |
218 |
|
218 | |||
219 | try: |
|
219 | try: | |
220 | out = str(arg) |
|
220 | out = str(arg) | |
221 | except UnicodeError: |
|
221 | except UnicodeError: | |
222 | try: |
|
222 | try: | |
223 | out = arg.encode('utf_8','replace') |
|
223 | out = arg.encode('utf_8','replace') | |
224 | except Exception,msg: |
|
224 | except Exception,msg: | |
225 | # let's keep this little duplication here, so that the most common |
|
225 | # let's keep this little duplication here, so that the most common | |
226 | # case doesn't suffer from a double try wrapping. |
|
226 | # case doesn't suffer from a double try wrapping. | |
227 | out = '<ERROR: %s>' % msg |
|
227 | out = '<ERROR: %s>' % msg | |
228 | except Exception,msg: |
|
228 | except Exception,msg: | |
229 | out = '<ERROR: %s>' % msg |
|
229 | out = '<ERROR: %s>' % msg | |
230 | #raise # dbg |
|
230 | #raise # dbg | |
231 | return out |
|
231 | return out | |
232 |
|
232 | |||
233 | #----------------------------------------------------------------------------- |
|
233 | #----------------------------------------------------------------------------- | |
234 | # Prompt classes |
|
234 | # Prompt classes | |
235 | #----------------------------------------------------------------------------- |
|
235 | #----------------------------------------------------------------------------- | |
236 |
|
236 | |||
237 | class BasePrompt(object): |
|
237 | class BasePrompt(object): | |
238 | """Interactive prompt similar to Mathematica's.""" |
|
238 | """Interactive prompt similar to Mathematica's.""" | |
239 |
|
239 | |||
240 | def _get_p_template(self): |
|
240 | def _get_p_template(self): | |
241 | return self._p_template |
|
241 | return self._p_template | |
242 |
|
242 | |||
243 | def _set_p_template(self,val): |
|
243 | def _set_p_template(self,val): | |
244 | self._p_template = val |
|
244 | self._p_template = val | |
245 | self.set_p_str() |
|
245 | self.set_p_str() | |
246 |
|
246 | |||
247 | p_template = property(_get_p_template,_set_p_template, |
|
247 | p_template = property(_get_p_template,_set_p_template, | |
248 | doc='Template for prompt string creation') |
|
248 | doc='Template for prompt string creation') | |
249 |
|
249 | |||
250 | def __init__(self, cache, sep, prompt, pad_left=False): |
|
250 | def __init__(self, cache, sep, prompt, pad_left=False): | |
251 |
|
251 | |||
252 | # Hack: we access information about the primary prompt through the |
|
252 | # Hack: we access information about the primary prompt through the | |
253 | # cache argument. We need this, because we want the secondary prompt |
|
253 | # cache argument. We need this, because we want the secondary prompt | |
254 | # to be aligned with the primary one. Color table info is also shared |
|
254 | # to be aligned with the primary one. Color table info is also shared | |
255 | # by all prompt classes through the cache. Nice OO spaghetti code! |
|
255 | # by all prompt classes through the cache. Nice OO spaghetti code! | |
256 | self.cache = cache |
|
256 | self.cache = cache | |
257 | self.sep = sep |
|
257 | self.sep = sep | |
258 |
|
258 | |||
259 | # regexp to count the number of spaces at the end of a prompt |
|
259 | # regexp to count the number of spaces at the end of a prompt | |
260 | # expression, useful for prompt auto-rewriting |
|
260 | # expression, useful for prompt auto-rewriting | |
261 | self.rspace = re.compile(r'(\s*)$') |
|
261 | self.rspace = re.compile(r'(\s*)$') | |
262 | # Flag to left-pad prompt strings to match the length of the primary |
|
262 | # Flag to left-pad prompt strings to match the length of the primary | |
263 | # prompt |
|
263 | # prompt | |
264 | self.pad_left = pad_left |
|
264 | self.pad_left = pad_left | |
265 |
|
265 | |||
266 | # Set template to create each actual prompt (where numbers change). |
|
266 | # Set template to create each actual prompt (where numbers change). | |
267 | # Use a property |
|
267 | # Use a property | |
268 | self.p_template = prompt |
|
268 | self.p_template = prompt | |
269 | self.set_p_str() |
|
269 | self.set_p_str() | |
270 |
|
270 | |||
271 | def set_p_str(self): |
|
271 | def set_p_str(self): | |
272 | """ Set the interpolating prompt strings. |
|
272 | """ Set the interpolating prompt strings. | |
273 |
|
273 | |||
274 | This must be called every time the color settings change, because the |
|
274 | This must be called every time the color settings change, because the | |
275 | prompt_specials global may have changed.""" |
|
275 | prompt_specials global may have changed.""" | |
276 |
|
276 | |||
277 | import os,time # needed in locals for prompt string handling |
|
277 | import os,time # needed in locals for prompt string handling | |
278 | loc = locals() |
|
278 | loc = locals() | |
279 | try: |
|
279 | try: | |
280 | self.p_str = ItplNS('%s%s%s' % |
|
280 | self.p_str = ItplNS('%s%s%s' % | |
281 | ('${self.sep}${self.col_p}', |
|
281 | ('${self.sep}${self.col_p}', | |
282 | multiple_replace(prompt_specials, self.p_template), |
|
282 | multiple_replace(prompt_specials, self.p_template), | |
283 | '${self.col_norm}'),self.cache.shell.user_ns,loc) |
|
283 | '${self.col_norm}'),self.cache.shell.user_ns,loc) | |
284 |
|
284 | |||
285 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, |
|
285 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, | |
286 | self.p_template), |
|
286 | self.p_template), | |
287 | self.cache.shell.user_ns,loc) |
|
287 | self.cache.shell.user_ns,loc) | |
288 | except: |
|
288 | except: | |
289 | print "Illegal prompt template (check $ usage!):",self.p_template |
|
289 | print "Illegal prompt template (check $ usage!):",self.p_template | |
290 | self.p_str = self.p_template |
|
290 | self.p_str = self.p_template | |
291 | self.p_str_nocolor = self.p_template |
|
291 | self.p_str_nocolor = self.p_template | |
292 |
|
292 | |||
293 | def write(self, msg): |
|
293 | def write(self, msg): | |
294 | sys.stdout.write(msg) |
|
294 | sys.stdout.write(msg) | |
295 | return '' |
|
295 | return '' | |
296 |
|
296 | |||
297 | def __str__(self): |
|
297 | def __str__(self): | |
298 | """Return a string form of the prompt. |
|
298 | """Return a string form of the prompt. | |
299 |
|
299 | |||
300 | This for is useful for continuation and output prompts, since it is |
|
300 | This for is useful for continuation and output prompts, since it is | |
301 | left-padded to match lengths with the primary one (if the |
|
301 | left-padded to match lengths with the primary one (if the | |
302 | self.pad_left attribute is set).""" |
|
302 | self.pad_left attribute is set).""" | |
303 |
|
303 | |||
304 | out_str = str_safe(self.p_str) |
|
304 | out_str = str_safe(self.p_str) | |
305 | if self.pad_left: |
|
305 | if self.pad_left: | |
306 | # We must find the amount of padding required to match lengths, |
|
306 | # We must find the amount of padding required to match lengths, | |
307 | # taking the color escapes (which are invisible on-screen) into |
|
307 | # taking the color escapes (which are invisible on-screen) into | |
308 | # account. |
|
308 | # account. | |
309 | esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor)) |
|
309 | esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor)) | |
310 | format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad) |
|
310 | format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad) | |
311 | return format % out_str |
|
311 | return format % out_str | |
312 | else: |
|
312 | else: | |
313 | return out_str |
|
313 | return out_str | |
314 |
|
314 | |||
315 | # these path filters are put in as methods so that we can control the |
|
315 | # these path filters are put in as methods so that we can control the | |
316 | # namespace where the prompt strings get evaluated |
|
316 | # namespace where the prompt strings get evaluated | |
317 | def cwd_filt(self, depth): |
|
317 | def cwd_filt(self, depth): | |
318 | """Return the last depth elements of the current working directory. |
|
318 | """Return the last depth elements of the current working directory. | |
319 |
|
319 | |||
320 | $HOME is always replaced with '~'. |
|
320 | $HOME is always replaced with '~'. | |
321 | If depth==0, the full path is returned.""" |
|
321 | If depth==0, the full path is returned.""" | |
322 |
|
322 | |||
323 | cwd = os.getcwd().replace(HOME,"~") |
|
323 | cwd = os.getcwd().replace(HOME,"~") | |
324 | out = os.sep.join(cwd.split(os.sep)[-depth:]) |
|
324 | out = os.sep.join(cwd.split(os.sep)[-depth:]) | |
325 | if out: |
|
325 | if out: | |
326 | return out |
|
326 | return out | |
327 | else: |
|
327 | else: | |
328 | return os.sep |
|
328 | return os.sep | |
329 |
|
329 | |||
330 | def cwd_filt2(self, depth): |
|
330 | def cwd_filt2(self, depth): | |
331 | """Return the last depth elements of the current working directory. |
|
331 | """Return the last depth elements of the current working directory. | |
332 |
|
332 | |||
333 | $HOME is always replaced with '~'. |
|
333 | $HOME is always replaced with '~'. | |
334 | If depth==0, the full path is returned.""" |
|
334 | If depth==0, the full path is returned.""" | |
335 |
|
335 | |||
336 | full_cwd = os.getcwd() |
|
336 | full_cwd = os.getcwd() | |
337 | cwd = full_cwd.replace(HOME,"~").split(os.sep) |
|
337 | cwd = full_cwd.replace(HOME,"~").split(os.sep) | |
338 | if '~' in cwd and len(cwd) == depth+1: |
|
338 | if '~' in cwd and len(cwd) == depth+1: | |
339 | depth += 1 |
|
339 | depth += 1 | |
340 | drivepart = '' |
|
340 | drivepart = '' | |
341 | if sys.platform == 'win32' and len(cwd) > depth: |
|
341 | if sys.platform == 'win32' and len(cwd) > depth: | |
342 | drivepart = os.path.splitdrive(full_cwd)[0] |
|
342 | drivepart = os.path.splitdrive(full_cwd)[0] | |
343 | out = drivepart + '/'.join(cwd[-depth:]) |
|
343 | out = drivepart + '/'.join(cwd[-depth:]) | |
344 |
|
344 | |||
345 | if out: |
|
345 | if out: | |
346 | return out |
|
346 | return out | |
347 | else: |
|
347 | else: | |
348 | return os.sep |
|
348 | return os.sep | |
349 |
|
349 | |||
350 | def __nonzero__(self): |
|
350 | def __nonzero__(self): | |
351 | """Implement boolean behavior. |
|
351 | """Implement boolean behavior. | |
352 |
|
352 | |||
353 | Checks whether the p_str attribute is non-empty""" |
|
353 | Checks whether the p_str attribute is non-empty""" | |
354 |
|
354 | |||
355 | return bool(self.p_template) |
|
355 | return bool(self.p_template) | |
356 |
|
356 | |||
357 |
|
357 | |||
358 | class Prompt1(BasePrompt): |
|
358 | class Prompt1(BasePrompt): | |
359 | """Input interactive prompt similar to Mathematica's.""" |
|
359 | """Input interactive prompt similar to Mathematica's.""" | |
360 |
|
360 | |||
361 | def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True): |
|
361 | def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True): | |
362 | BasePrompt.__init__(self, cache, sep, prompt, pad_left) |
|
362 | BasePrompt.__init__(self, cache, sep, prompt, pad_left) | |
363 |
|
363 | |||
364 | def set_colors(self): |
|
364 | def set_colors(self): | |
365 | self.set_p_str() |
|
365 | self.set_p_str() | |
366 | Colors = self.cache.color_table.active_colors # shorthand |
|
366 | Colors = self.cache.color_table.active_colors # shorthand | |
367 | self.col_p = Colors.in_prompt |
|
367 | self.col_p = Colors.in_prompt | |
368 | self.col_num = Colors.in_number |
|
368 | self.col_num = Colors.in_number | |
369 | self.col_norm = Colors.in_normal |
|
369 | self.col_norm = Colors.in_normal | |
370 | # We need a non-input version of these escapes for the '--->' |
|
370 | # We need a non-input version of these escapes for the '--->' | |
371 | # auto-call prompts used in the auto_rewrite() method. |
|
371 | # auto-call prompts used in the auto_rewrite() method. | |
372 | self.col_p_ni = self.col_p.replace('\001','').replace('\002','') |
|
372 | self.col_p_ni = self.col_p.replace('\001','').replace('\002','') | |
373 | self.col_norm_ni = Colors.normal |
|
373 | self.col_norm_ni = Colors.normal | |
374 |
|
374 | |||
375 | def peek_next_prompt(self): |
|
|||
376 | """Get the next prompt, but don't increment the counter.""" |
|
|||
377 | self.cache.prompt_count += 1 |
|
|||
378 | next_prompt = str_safe(self.p_str) |
|
|||
379 | self.cache.prompt_count -= 1 |
|
|||
380 | return next_prompt |
|
|||
381 |
|
||||
382 | def __str__(self): |
|
375 | def __str__(self): | |
383 | self.cache.prompt_count += 1 |
|
|||
384 | self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1] |
|
376 | self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1] | |
385 | return str_safe(self.p_str) |
|
377 | return str_safe(self.p_str) | |
386 |
|
378 | |||
387 | def auto_rewrite(self): |
|
379 | def auto_rewrite(self): | |
388 | """Return a string of the form '--->' which lines up with the previous |
|
380 | """Return a string of the form '--->' which lines up with the previous | |
389 | input string. Useful for systems which re-write the user input when |
|
381 | input string. Useful for systems which re-write the user input when | |
390 | handling automatically special syntaxes.""" |
|
382 | handling automatically special syntaxes.""" | |
391 |
|
383 | |||
392 | curr = str(self.cache.last_prompt) |
|
384 | curr = str(self.cache.last_prompt) | |
393 | nrspaces = len(self.rspace.search(curr).group()) |
|
385 | nrspaces = len(self.rspace.search(curr).group()) | |
394 | return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1), |
|
386 | return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1), | |
395 | ' '*nrspaces,self.col_norm_ni) |
|
387 | ' '*nrspaces,self.col_norm_ni) | |
396 |
|
388 | |||
397 |
|
389 | |||
398 | class PromptOut(BasePrompt): |
|
390 | class PromptOut(BasePrompt): | |
399 | """Output interactive prompt similar to Mathematica's.""" |
|
391 | """Output interactive prompt similar to Mathematica's.""" | |
400 |
|
392 | |||
401 | def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True): |
|
393 | def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True): | |
402 | BasePrompt.__init__(self, cache, sep, prompt, pad_left) |
|
394 | BasePrompt.__init__(self, cache, sep, prompt, pad_left) | |
403 | if not self.p_template: |
|
395 | if not self.p_template: | |
404 | self.__str__ = lambda: '' |
|
396 | self.__str__ = lambda: '' | |
405 |
|
397 | |||
406 | def set_colors(self): |
|
398 | def set_colors(self): | |
407 | self.set_p_str() |
|
399 | self.set_p_str() | |
408 | Colors = self.cache.color_table.active_colors # shorthand |
|
400 | Colors = self.cache.color_table.active_colors # shorthand | |
409 | self.col_p = Colors.out_prompt |
|
401 | self.col_p = Colors.out_prompt | |
410 | self.col_num = Colors.out_number |
|
402 | self.col_num = Colors.out_number | |
411 | self.col_norm = Colors.normal |
|
403 | self.col_norm = Colors.normal | |
412 |
|
404 | |||
413 |
|
405 | |||
414 | class Prompt2(BasePrompt): |
|
406 | class Prompt2(BasePrompt): | |
415 | """Interactive continuation prompt.""" |
|
407 | """Interactive continuation prompt.""" | |
416 |
|
408 | |||
417 | def __init__(self, cache, prompt=' .\\D.: ', pad_left=True): |
|
409 | def __init__(self, cache, prompt=' .\\D.: ', pad_left=True): | |
418 | self.cache = cache |
|
410 | self.cache = cache | |
419 | self.p_template = prompt |
|
411 | self.p_template = prompt | |
420 | self.pad_left = pad_left |
|
412 | self.pad_left = pad_left | |
421 | self.set_p_str() |
|
413 | self.set_p_str() | |
422 |
|
414 | |||
423 | def set_p_str(self): |
|
415 | def set_p_str(self): | |
424 | import os,time # needed in locals for prompt string handling |
|
416 | import os,time # needed in locals for prompt string handling | |
425 | loc = locals() |
|
417 | loc = locals() | |
426 | self.p_str = ItplNS('%s%s%s' % |
|
418 | self.p_str = ItplNS('%s%s%s' % | |
427 | ('${self.col_p2}', |
|
419 | ('${self.col_p2}', | |
428 | multiple_replace(prompt_specials, self.p_template), |
|
420 | multiple_replace(prompt_specials, self.p_template), | |
429 | '$self.col_norm'), |
|
421 | '$self.col_norm'), | |
430 | self.cache.shell.user_ns,loc) |
|
422 | self.cache.shell.user_ns,loc) | |
431 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, |
|
423 | self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor, | |
432 | self.p_template), |
|
424 | self.p_template), | |
433 | self.cache.shell.user_ns,loc) |
|
425 | self.cache.shell.user_ns,loc) | |
434 |
|
426 | |||
435 | def set_colors(self): |
|
427 | def set_colors(self): | |
436 | self.set_p_str() |
|
428 | self.set_p_str() | |
437 | Colors = self.cache.color_table.active_colors |
|
429 | Colors = self.cache.color_table.active_colors | |
438 | self.col_p2 = Colors.in_prompt2 |
|
430 | self.col_p2 = Colors.in_prompt2 | |
439 | self.col_norm = Colors.in_normal |
|
431 | self.col_norm = Colors.in_normal | |
440 | # FIXME (2004-06-16) HACK: prevent crashes for users who haven't |
|
432 | # FIXME (2004-06-16) HACK: prevent crashes for users who haven't | |
441 | # updated their prompt_in2 definitions. Remove eventually. |
|
433 | # updated their prompt_in2 definitions. Remove eventually. | |
442 | self.col_p = Colors.out_prompt |
|
434 | self.col_p = Colors.out_prompt | |
443 | self.col_num = Colors.out_number |
|
435 | self.col_num = Colors.out_number | |
444 |
|
436 |
@@ -1,658 +1,675 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tests for the inputsplitter module. |
|
2 | """Tests for the inputsplitter module. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2010 The IPython Development Team |
|
5 | # Copyright (C) 2010 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # stdlib |
|
14 | # stdlib | |
15 | import unittest |
|
15 | import unittest | |
16 | import sys |
|
16 | import sys | |
17 |
|
17 | |||
18 | # Third party |
|
18 | # Third party | |
19 | import nose.tools as nt |
|
19 | import nose.tools as nt | |
20 |
|
20 | |||
21 | # Our own |
|
21 | # Our own | |
22 | from IPython.core import inputsplitter as isp |
|
22 | from IPython.core import inputsplitter as isp | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Semi-complete examples (also used as tests) |
|
25 | # Semi-complete examples (also used as tests) | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | # Note: at the bottom, there's a slightly more complete version of this that |
|
28 | # Note: at the bottom, there's a slightly more complete version of this that | |
29 | # can be useful during development of code here. |
|
29 | # can be useful during development of code here. | |
30 |
|
30 | |||
31 | def mini_interactive_loop(input_func): |
|
31 | def mini_interactive_loop(input_func): | |
32 | """Minimal example of the logic of an interactive interpreter loop. |
|
32 | """Minimal example of the logic of an interactive interpreter loop. | |
33 |
|
33 | |||
34 | This serves as an example, and it is used by the test system with a fake |
|
34 | This serves as an example, and it is used by the test system with a fake | |
35 | raw_input that simulates interactive input.""" |
|
35 | raw_input that simulates interactive input.""" | |
36 |
|
36 | |||
37 | from IPython.core.inputsplitter import InputSplitter |
|
37 | from IPython.core.inputsplitter import InputSplitter | |
38 |
|
38 | |||
39 | isp = InputSplitter() |
|
39 | isp = InputSplitter() | |
40 | # In practice, this input loop would be wrapped in an outside loop to read |
|
40 | # In practice, this input loop would be wrapped in an outside loop to read | |
41 | # input indefinitely, until some exit/quit command was issued. Here we |
|
41 | # input indefinitely, until some exit/quit command was issued. Here we | |
42 | # only illustrate the basic inner loop. |
|
42 | # only illustrate the basic inner loop. | |
43 | while isp.push_accepts_more(): |
|
43 | while isp.push_accepts_more(): | |
44 | indent = ' '*isp.indent_spaces |
|
44 | indent = ' '*isp.indent_spaces | |
45 | prompt = '>>> ' + indent |
|
45 | prompt = '>>> ' + indent | |
46 | line = indent + input_func(prompt) |
|
46 | line = indent + input_func(prompt) | |
47 | isp.push(line) |
|
47 | isp.push(line) | |
48 |
|
48 | |||
49 | # Here we just return input so we can use it in a test suite, but a real |
|
49 | # Here we just return input so we can use it in a test suite, but a real | |
50 | # interpreter would instead send it for execution somewhere. |
|
50 | # interpreter would instead send it for execution somewhere. | |
51 | src = isp.source_reset() |
|
51 | src = isp.source_reset() | |
52 | #print 'Input source was:\n', src # dbg |
|
52 | #print 'Input source was:\n', src # dbg | |
53 | return src |
|
53 | return src | |
54 |
|
54 | |||
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 | # Test utilities, just for local use |
|
56 | # Test utilities, just for local use | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 |
|
58 | |||
59 | def assemble(block): |
|
59 | def assemble(block): | |
60 | """Assemble a block into multi-line sub-blocks.""" |
|
60 | """Assemble a block into multi-line sub-blocks.""" | |
61 | return ['\n'.join(sub_block)+'\n' for sub_block in block] |
|
61 | return ['\n'.join(sub_block)+'\n' for sub_block in block] | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def pseudo_input(lines): |
|
64 | def pseudo_input(lines): | |
65 | """Return a function that acts like raw_input but feeds the input list.""" |
|
65 | """Return a function that acts like raw_input but feeds the input list.""" | |
66 | ilines = iter(lines) |
|
66 | ilines = iter(lines) | |
67 | def raw_in(prompt): |
|
67 | def raw_in(prompt): | |
68 | try: |
|
68 | try: | |
69 | return next(ilines) |
|
69 | return next(ilines) | |
70 | except StopIteration: |
|
70 | except StopIteration: | |
71 | return '' |
|
71 | return '' | |
72 | return raw_in |
|
72 | return raw_in | |
73 |
|
73 | |||
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 | # Tests |
|
75 | # Tests | |
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | def test_spaces(): |
|
77 | def test_spaces(): | |
78 | tests = [('', 0), |
|
78 | tests = [('', 0), | |
79 | (' ', 1), |
|
79 | (' ', 1), | |
80 | ('\n', 0), |
|
80 | ('\n', 0), | |
81 | (' \n', 1), |
|
81 | (' \n', 1), | |
82 | ('x', 0), |
|
82 | ('x', 0), | |
83 | (' x', 1), |
|
83 | (' x', 1), | |
84 | (' x',2), |
|
84 | (' x',2), | |
85 | (' x',4), |
|
85 | (' x',4), | |
86 | # Note: tabs are counted as a single whitespace! |
|
86 | # Note: tabs are counted as a single whitespace! | |
87 | ('\tx', 1), |
|
87 | ('\tx', 1), | |
88 | ('\t x', 2), |
|
88 | ('\t x', 2), | |
89 | ] |
|
89 | ] | |
90 |
|
90 | |||
91 | for s, nsp in tests: |
|
91 | for s, nsp in tests: | |
92 | nt.assert_equal(isp.num_ini_spaces(s), nsp) |
|
92 | nt.assert_equal(isp.num_ini_spaces(s), nsp) | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | def test_remove_comments(): |
|
95 | def test_remove_comments(): | |
96 | tests = [('text', 'text'), |
|
96 | tests = [('text', 'text'), | |
97 | ('text # comment', 'text '), |
|
97 | ('text # comment', 'text '), | |
98 | ('text # comment\n', 'text \n'), |
|
98 | ('text # comment\n', 'text \n'), | |
99 | ('text # comment \n', 'text \n'), |
|
99 | ('text # comment \n', 'text \n'), | |
100 | ('line # c \nline\n','line \nline\n'), |
|
100 | ('line # c \nline\n','line \nline\n'), | |
101 | ('line # c \nline#c2 \nline\nline #c\n\n', |
|
101 | ('line # c \nline#c2 \nline\nline #c\n\n', | |
102 | 'line \nline\nline\nline \n\n'), |
|
102 | 'line \nline\nline\nline \n\n'), | |
103 | ] |
|
103 | ] | |
104 |
|
104 | |||
105 | for inp, out in tests: |
|
105 | for inp, out in tests: | |
106 | nt.assert_equal(isp.remove_comments(inp), out) |
|
106 | nt.assert_equal(isp.remove_comments(inp), out) | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | def test_get_input_encoding(): |
|
109 | def test_get_input_encoding(): | |
110 | encoding = isp.get_input_encoding() |
|
110 | encoding = isp.get_input_encoding() | |
111 | nt.assert_true(isinstance(encoding, basestring)) |
|
111 | nt.assert_true(isinstance(encoding, basestring)) | |
112 | # simple-minded check that at least encoding a simple string works with the |
|
112 | # simple-minded check that at least encoding a simple string works with the | |
113 | # encoding we got. |
|
113 | # encoding we got. | |
114 | nt.assert_equal('test'.encode(encoding), 'test') |
|
114 | nt.assert_equal('test'.encode(encoding), 'test') | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | class NoInputEncodingTestCase(unittest.TestCase): |
|
117 | class NoInputEncodingTestCase(unittest.TestCase): | |
118 | def setUp(self): |
|
118 | def setUp(self): | |
119 | self.old_stdin = sys.stdin |
|
119 | self.old_stdin = sys.stdin | |
120 | class X: pass |
|
120 | class X: pass | |
121 | fake_stdin = X() |
|
121 | fake_stdin = X() | |
122 | sys.stdin = fake_stdin |
|
122 | sys.stdin = fake_stdin | |
123 |
|
123 | |||
124 | def test(self): |
|
124 | def test(self): | |
125 | # Verify that if sys.stdin has no 'encoding' attribute we do the right |
|
125 | # Verify that if sys.stdin has no 'encoding' attribute we do the right | |
126 | # thing |
|
126 | # thing | |
127 | enc = isp.get_input_encoding() |
|
127 | enc = isp.get_input_encoding() | |
128 | self.assertEqual(enc, 'ascii') |
|
128 | self.assertEqual(enc, 'ascii') | |
129 |
|
129 | |||
130 | def tearDown(self): |
|
130 | def tearDown(self): | |
131 | sys.stdin = self.old_stdin |
|
131 | sys.stdin = self.old_stdin | |
132 |
|
132 | |||
133 |
|
133 | |||
134 | class InputSplitterTestCase(unittest.TestCase): |
|
134 | class InputSplitterTestCase(unittest.TestCase): | |
135 | def setUp(self): |
|
135 | def setUp(self): | |
136 | self.isp = isp.InputSplitter() |
|
136 | self.isp = isp.InputSplitter() | |
137 |
|
137 | |||
138 | def test_reset(self): |
|
138 | def test_reset(self): | |
139 | isp = self.isp |
|
139 | isp = self.isp | |
140 | isp.push('x=1') |
|
140 | isp.push('x=1') | |
141 | isp.reset() |
|
141 | isp.reset() | |
142 | self.assertEqual(isp._buffer, []) |
|
142 | self.assertEqual(isp._buffer, []) | |
143 | self.assertEqual(isp.indent_spaces, 0) |
|
143 | self.assertEqual(isp.indent_spaces, 0) | |
144 | self.assertEqual(isp.source, '') |
|
144 | self.assertEqual(isp.source, '') | |
145 | self.assertEqual(isp.code, None) |
|
145 | self.assertEqual(isp.code, None) | |
146 | self.assertEqual(isp._is_complete, False) |
|
146 | self.assertEqual(isp._is_complete, False) | |
147 |
|
147 | |||
148 | def test_source(self): |
|
148 | def test_source(self): | |
149 | self.isp._store('1') |
|
149 | self.isp._store('1') | |
150 | self.isp._store('2') |
|
150 | self.isp._store('2') | |
151 | self.assertEqual(self.isp.source, '1\n2\n') |
|
151 | self.assertEqual(self.isp.source, '1\n2\n') | |
152 | self.assertTrue(len(self.isp._buffer)>0) |
|
152 | self.assertTrue(len(self.isp._buffer)>0) | |
153 | self.assertEqual(self.isp.source_reset(), '1\n2\n') |
|
153 | self.assertEqual(self.isp.source_reset(), '1\n2\n') | |
154 | self.assertEqual(self.isp._buffer, []) |
|
154 | self.assertEqual(self.isp._buffer, []) | |
155 | self.assertEqual(self.isp.source, '') |
|
155 | self.assertEqual(self.isp.source, '') | |
156 |
|
156 | |||
157 | def test_indent(self): |
|
157 | def test_indent(self): | |
158 | isp = self.isp # shorthand |
|
158 | isp = self.isp # shorthand | |
159 | isp.push('x=1') |
|
159 | isp.push('x=1') | |
160 | self.assertEqual(isp.indent_spaces, 0) |
|
160 | self.assertEqual(isp.indent_spaces, 0) | |
161 | isp.push('if 1:\n x=1') |
|
161 | isp.push('if 1:\n x=1') | |
162 | self.assertEqual(isp.indent_spaces, 4) |
|
162 | self.assertEqual(isp.indent_spaces, 4) | |
163 | isp.push('y=2\n') |
|
163 | isp.push('y=2\n') | |
164 | self.assertEqual(isp.indent_spaces, 0) |
|
164 | self.assertEqual(isp.indent_spaces, 0) | |
|
165 | ||||
|
166 | def test_indent2(self): | |||
|
167 | # In cell mode, inputs must be fed in whole blocks, so skip this test | |||
|
168 | if self.isp.input_mode == 'cell': return | |||
|
169 | ||||
|
170 | isp = self.isp | |||
165 | isp.push('if 1:') |
|
171 | isp.push('if 1:') | |
166 | self.assertEqual(isp.indent_spaces, 4) |
|
172 | self.assertEqual(isp.indent_spaces, 4) | |
167 | isp.push(' x=1') |
|
173 | isp.push(' x=1') | |
168 | self.assertEqual(isp.indent_spaces, 4) |
|
174 | self.assertEqual(isp.indent_spaces, 4) | |
169 | # Blank lines shouldn't change the indent level |
|
175 | # Blank lines shouldn't change the indent level | |
170 | isp.push(' '*2) |
|
176 | isp.push(' '*2) | |
171 | self.assertEqual(isp.indent_spaces, 4) |
|
177 | self.assertEqual(isp.indent_spaces, 4) | |
172 |
|
178 | |||
173 |
def test_indent |
|
179 | def test_indent3(self): | |
|
180 | # In cell mode, inputs must be fed in whole blocks, so skip this test | |||
|
181 | if self.isp.input_mode == 'cell': return | |||
|
182 | ||||
174 | isp = self.isp |
|
183 | isp = self.isp | |
175 | # When a multiline statement contains parens or multiline strings, we |
|
184 | # When a multiline statement contains parens or multiline strings, we | |
176 | # shouldn't get confused. |
|
185 | # shouldn't get confused. | |
177 | isp.push("if 1:") |
|
186 | isp.push("if 1:") | |
178 | isp.push(" x = (1+\n 2)") |
|
187 | isp.push(" x = (1+\n 2)") | |
179 | self.assertEqual(isp.indent_spaces, 4) |
|
188 | self.assertEqual(isp.indent_spaces, 4) | |
180 |
|
189 | |||
181 | def test_dedent(self): |
|
190 | def test_dedent(self): | |
182 | isp = self.isp # shorthand |
|
191 | isp = self.isp # shorthand | |
183 | isp.push('if 1:') |
|
192 | isp.push('if 1:') | |
184 | self.assertEqual(isp.indent_spaces, 4) |
|
193 | self.assertEqual(isp.indent_spaces, 4) | |
185 | isp.push(' pass') |
|
194 | isp.push(' pass') | |
186 | self.assertEqual(isp.indent_spaces, 0) |
|
195 | self.assertEqual(isp.indent_spaces, 0) | |
187 |
|
196 | |||
188 | def test_push(self): |
|
197 | def test_push(self): | |
189 | isp = self.isp |
|
198 | isp = self.isp | |
190 | self.assertTrue(isp.push('x=1')) |
|
199 | self.assertTrue(isp.push('x=1')) | |
191 |
|
200 | |||
192 | def test_push2(self): |
|
201 | def test_push2(self): | |
193 | isp = self.isp |
|
202 | isp = self.isp | |
194 | self.assertFalse(isp.push('if 1:')) |
|
203 | self.assertFalse(isp.push('if 1:')) | |
195 | for line in [' x=1', '# a comment', ' y=2']: |
|
204 | for line in [' x=1', '# a comment', ' y=2']: | |
196 | self.assertTrue(isp.push(line)) |
|
205 | self.assertTrue(isp.push(line)) | |
197 |
|
206 | |||
198 | def test_push3(self): |
|
|||
199 | """Test input with leading whitespace""" |
|
|||
200 | isp = self.isp |
|
|||
201 | isp.push(' x=1') |
|
|||
202 | isp.push(' y=2') |
|
|||
203 | self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n') |
|
|||
204 |
|
||||
205 | def test_replace_mode(self): |
|
207 | def test_replace_mode(self): | |
206 | isp = self.isp |
|
208 | isp = self.isp | |
207 | isp.input_mode = 'cell' |
|
209 | isp.input_mode = 'cell' | |
208 | isp.push('x=1') |
|
210 | isp.push('x=1') | |
209 | self.assertEqual(isp.source, 'x=1\n') |
|
211 | self.assertEqual(isp.source, 'x=1\n') | |
210 | isp.push('x=2') |
|
212 | isp.push('x=2') | |
211 | self.assertEqual(isp.source, 'x=2\n') |
|
213 | self.assertEqual(isp.source, 'x=2\n') | |
212 |
|
214 | |||
213 | def test_push_accepts_more(self): |
|
215 | def test_push_accepts_more(self): | |
214 | isp = self.isp |
|
216 | isp = self.isp | |
215 | isp.push('x=1') |
|
217 | isp.push('x=1') | |
216 | self.assertFalse(isp.push_accepts_more()) |
|
218 | self.assertFalse(isp.push_accepts_more()) | |
217 |
|
219 | |||
218 | def test_push_accepts_more2(self): |
|
220 | def test_push_accepts_more2(self): | |
|
221 | # In cell mode, inputs must be fed in whole blocks, so skip this test | |||
|
222 | if self.isp.input_mode == 'cell': return | |||
|
223 | ||||
219 | isp = self.isp |
|
224 | isp = self.isp | |
220 | isp.push('if 1:') |
|
225 | isp.push('if 1:') | |
221 | self.assertTrue(isp.push_accepts_more()) |
|
226 | self.assertTrue(isp.push_accepts_more()) | |
222 | isp.push(' x=1') |
|
227 | isp.push(' x=1') | |
223 | self.assertTrue(isp.push_accepts_more()) |
|
228 | self.assertTrue(isp.push_accepts_more()) | |
224 | isp.push('') |
|
229 | isp.push('') | |
225 | self.assertFalse(isp.push_accepts_more()) |
|
230 | self.assertFalse(isp.push_accepts_more()) | |
226 |
|
231 | |||
227 | def test_push_accepts_more3(self): |
|
232 | def test_push_accepts_more3(self): | |
228 | isp = self.isp |
|
233 | isp = self.isp | |
229 | isp.push("x = (2+\n3)") |
|
234 | isp.push("x = (2+\n3)") | |
230 | self.assertFalse(isp.push_accepts_more()) |
|
235 | self.assertFalse(isp.push_accepts_more()) | |
231 |
|
236 | |||
232 | def test_push_accepts_more4(self): |
|
237 | def test_push_accepts_more4(self): | |
|
238 | # In cell mode, inputs must be fed in whole blocks, so skip this test | |||
|
239 | if self.isp.input_mode == 'cell': return | |||
|
240 | ||||
233 | isp = self.isp |
|
241 | isp = self.isp | |
234 | # When a multiline statement contains parens or multiline strings, we |
|
242 | # When a multiline statement contains parens or multiline strings, we | |
235 | # shouldn't get confused. |
|
243 | # shouldn't get confused. | |
236 | # FIXME: we should be able to better handle de-dents in statements like |
|
244 | # FIXME: we should be able to better handle de-dents in statements like | |
237 | # multiline strings and multiline expressions (continued with \ or |
|
245 | # multiline strings and multiline expressions (continued with \ or | |
238 | # parens). Right now we aren't handling the indentation tracking quite |
|
246 | # parens). Right now we aren't handling the indentation tracking quite | |
239 | # correctly with this, though in practice it may not be too much of a |
|
247 | # correctly with this, though in practice it may not be too much of a | |
240 | # problem. We'll need to see. |
|
248 | # problem. We'll need to see. | |
241 | isp.push("if 1:") |
|
249 | isp.push("if 1:") | |
242 | isp.push(" x = (2+") |
|
250 | isp.push(" x = (2+") | |
243 | isp.push(" 3)") |
|
251 | isp.push(" 3)") | |
244 | self.assertTrue(isp.push_accepts_more()) |
|
252 | self.assertTrue(isp.push_accepts_more()) | |
245 | isp.push(" y = 3") |
|
253 | isp.push(" y = 3") | |
246 | self.assertTrue(isp.push_accepts_more()) |
|
254 | self.assertTrue(isp.push_accepts_more()) | |
247 | isp.push('') |
|
255 | isp.push('') | |
248 | self.assertFalse(isp.push_accepts_more()) |
|
256 | self.assertFalse(isp.push_accepts_more()) | |
249 |
|
257 | |||
250 | def test_continuation(self): |
|
258 | def test_continuation(self): | |
251 | isp = self.isp |
|
259 | isp = self.isp | |
252 | isp.push("import os, \\") |
|
260 | isp.push("import os, \\") | |
253 | self.assertTrue(isp.push_accepts_more()) |
|
261 | self.assertTrue(isp.push_accepts_more()) | |
254 | isp.push("sys") |
|
262 | isp.push("sys") | |
255 | self.assertFalse(isp.push_accepts_more()) |
|
263 | self.assertFalse(isp.push_accepts_more()) | |
256 |
|
264 | |||
257 | def test_syntax_error(self): |
|
265 | def test_syntax_error(self): | |
258 | isp = self.isp |
|
266 | isp = self.isp | |
259 | # Syntax errors immediately produce a 'ready' block, so the invalid |
|
267 | # Syntax errors immediately produce a 'ready' block, so the invalid | |
260 | # Python can be sent to the kernel for evaluation with possible ipython |
|
268 | # Python can be sent to the kernel for evaluation with possible ipython | |
261 | # special-syntax conversion. |
|
269 | # special-syntax conversion. | |
262 | isp.push('run foo') |
|
270 | isp.push('run foo') | |
263 | self.assertFalse(isp.push_accepts_more()) |
|
271 | self.assertFalse(isp.push_accepts_more()) | |
264 |
|
272 | |||
265 | def check_split(self, block_lines, compile=True): |
|
273 | def check_split(self, block_lines, compile=True): | |
266 | blocks = assemble(block_lines) |
|
274 | blocks = assemble(block_lines) | |
267 | lines = ''.join(blocks) |
|
275 | lines = ''.join(blocks) | |
268 | oblock = self.isp.split_blocks(lines) |
|
276 | oblock = self.isp.split_blocks(lines) | |
269 | self.assertEqual(oblock, blocks) |
|
277 | self.assertEqual(oblock, blocks) | |
270 | if compile: |
|
278 | if compile: | |
271 | for block in blocks: |
|
279 | for block in blocks: | |
272 | self.isp._compile(block) |
|
280 | self.isp._compile(block) | |
273 |
|
281 | |||
274 | def test_split(self): |
|
282 | def test_split(self): | |
275 | # All blocks of input we want to test in a list. The format for each |
|
283 | # All blocks of input we want to test in a list. The format for each | |
276 | # block is a list of lists, with each inner lists consisting of all the |
|
284 | # block is a list of lists, with each inner lists consisting of all the | |
277 | # lines (as single-lines) that should make up a sub-block. |
|
285 | # lines (as single-lines) that should make up a sub-block. | |
278 |
|
286 | |||
279 | # Note: do NOT put here sub-blocks that don't compile, as the |
|
287 | # Note: do NOT put here sub-blocks that don't compile, as the | |
280 | # check_split() routine makes a final verification pass to check that |
|
288 | # check_split() routine makes a final verification pass to check that | |
281 | # each sub_block, as returned by split_blocks(), does compile |
|
289 | # each sub_block, as returned by split_blocks(), does compile | |
282 | # correctly. |
|
290 | # correctly. | |
283 | all_blocks = [ [['x=1']], |
|
291 | all_blocks = [ [['x=1']], | |
284 |
|
292 | |||
285 | [['x=1'], |
|
293 | [['x=1'], | |
286 | ['y=2']], |
|
294 | ['y=2']], | |
287 |
|
295 | |||
288 | [['x=1', |
|
296 | [['x=1', | |
289 | '# a comment'], |
|
297 | '# a comment'], | |
290 | ['y=11']], |
|
298 | ['y=11']], | |
291 |
|
299 | |||
292 | [['if 1:', |
|
300 | [['if 1:', | |
293 | ' x=1'], |
|
301 | ' x=1'], | |
294 | ['y=3']], |
|
302 | ['y=3']], | |
295 |
|
303 | |||
296 | [['def f(x):', |
|
304 | [['def f(x):', | |
297 | ' return x'], |
|
305 | ' return x'], | |
298 | ['x=1']], |
|
306 | ['x=1']], | |
299 |
|
307 | |||
300 | [['def f(x):', |
|
308 | [['def f(x):', | |
301 | ' x+=1', |
|
309 | ' x+=1', | |
302 | ' ', |
|
310 | ' ', | |
303 | ' return x'], |
|
311 | ' return x'], | |
304 | ['x=1']], |
|
312 | ['x=1']], | |
305 |
|
313 | |||
306 | [['def f(x):', |
|
314 | [['def f(x):', | |
307 | ' if x>0:', |
|
315 | ' if x>0:', | |
308 | ' y=1', |
|
316 | ' y=1', | |
309 | ' # a comment', |
|
317 | ' # a comment', | |
310 | ' else:', |
|
318 | ' else:', | |
311 | ' y=4', |
|
319 | ' y=4', | |
312 | ' ', |
|
320 | ' ', | |
313 | ' return y'], |
|
321 | ' return y'], | |
314 | ['x=1'], |
|
322 | ['x=1'], | |
315 | ['if 1:', |
|
323 | ['if 1:', | |
316 | ' y=11'] ], |
|
324 | ' y=11'] ], | |
317 |
|
325 | |||
318 | [['for i in range(10):' |
|
326 | [['for i in range(10):' | |
319 | ' x=i**2']], |
|
327 | ' x=i**2']], | |
320 |
|
328 | |||
321 | [['for i in range(10):' |
|
329 | [['for i in range(10):' | |
322 | ' x=i**2'], |
|
330 | ' x=i**2'], | |
323 | ['z = 1']], |
|
331 | ['z = 1']], | |
324 | ] |
|
332 | ] | |
325 | for block_lines in all_blocks: |
|
333 | for block_lines in all_blocks: | |
326 | self.check_split(block_lines) |
|
334 | self.check_split(block_lines) | |
327 |
|
335 | |||
328 | def test_split_syntax_errors(self): |
|
336 | def test_split_syntax_errors(self): | |
329 | # Block splitting with invalid syntax |
|
337 | # Block splitting with invalid syntax | |
330 | all_blocks = [ [['a syntax error']], |
|
338 | all_blocks = [ [['a syntax error']], | |
331 |
|
339 | |||
332 | [['x=1', |
|
340 | [['x=1', | |
333 | 'another syntax error']], |
|
341 | 'another syntax error']], | |
334 |
|
342 | |||
335 | [['for i in range(10):' |
|
343 | [['for i in range(10):' | |
336 | ' yet another error']], |
|
344 | ' yet another error']], | |
337 |
|
345 | |||
338 | ] |
|
346 | ] | |
339 | for block_lines in all_blocks: |
|
347 | for block_lines in all_blocks: | |
340 | self.check_split(block_lines, compile=False) |
|
348 | self.check_split(block_lines, compile=False) | |
341 |
|
349 | |||
342 |
|
350 | |||
343 | class InteractiveLoopTestCase(unittest.TestCase): |
|
351 | class InteractiveLoopTestCase(unittest.TestCase): | |
344 | """Tests for an interactive loop like a python shell. |
|
352 | """Tests for an interactive loop like a python shell. | |
345 | """ |
|
353 | """ | |
346 | def check_ns(self, lines, ns): |
|
354 | def check_ns(self, lines, ns): | |
347 | """Validate that the given input lines produce the resulting namespace. |
|
355 | """Validate that the given input lines produce the resulting namespace. | |
348 |
|
356 | |||
349 | Note: the input lines are given exactly as they would be typed in an |
|
357 | Note: the input lines are given exactly as they would be typed in an | |
350 | auto-indenting environment, as mini_interactive_loop above already does |
|
358 | auto-indenting environment, as mini_interactive_loop above already does | |
351 | auto-indenting and prepends spaces to the input. |
|
359 | auto-indenting and prepends spaces to the input. | |
352 | """ |
|
360 | """ | |
353 | src = mini_interactive_loop(pseudo_input(lines)) |
|
361 | src = mini_interactive_loop(pseudo_input(lines)) | |
354 | test_ns = {} |
|
362 | test_ns = {} | |
355 | exec src in test_ns |
|
363 | exec src in test_ns | |
356 | # We can't check that the provided ns is identical to the test_ns, |
|
364 | # We can't check that the provided ns is identical to the test_ns, | |
357 | # because Python fills test_ns with extra keys (copyright, etc). But |
|
365 | # because Python fills test_ns with extra keys (copyright, etc). But | |
358 | # we can check that the given dict is *contained* in test_ns |
|
366 | # we can check that the given dict is *contained* in test_ns | |
359 | for k,v in ns.iteritems(): |
|
367 | for k,v in ns.iteritems(): | |
360 | self.assertEqual(test_ns[k], v) |
|
368 | self.assertEqual(test_ns[k], v) | |
361 |
|
369 | |||
362 | def test_simple(self): |
|
370 | def test_simple(self): | |
363 | self.check_ns(['x=1'], dict(x=1)) |
|
371 | self.check_ns(['x=1'], dict(x=1)) | |
364 |
|
372 | |||
365 | def test_simple2(self): |
|
373 | def test_simple2(self): | |
366 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) |
|
374 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) | |
367 |
|
375 | |||
368 | def test_xy(self): |
|
376 | def test_xy(self): | |
369 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) |
|
377 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) | |
370 |
|
378 | |||
371 | def test_abc(self): |
|
379 | def test_abc(self): | |
372 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) |
|
380 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) | |
373 |
|
381 | |||
374 | def test_multi(self): |
|
382 | def test_multi(self): | |
375 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) |
|
383 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) | |
376 |
|
384 | |||
377 |
|
385 | |||
378 | def test_LineInfo(): |
|
386 | def test_LineInfo(): | |
379 | """Simple test for LineInfo construction and str()""" |
|
387 | """Simple test for LineInfo construction and str()""" | |
380 | linfo = isp.LineInfo(' %cd /home') |
|
388 | linfo = isp.LineInfo(' %cd /home') | |
381 | nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]') |
|
389 | nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]') | |
382 |
|
390 | |||
383 |
|
391 | |||
384 | def test_split_user_input(): |
|
392 | def test_split_user_input(): | |
385 | """Unicode test - split_user_input already has good doctests""" |
|
393 | """Unicode test - split_user_input already has good doctests""" | |
386 | line = u"Pérez Fernando" |
|
394 | line = u"Pérez Fernando" | |
387 | parts = isp.split_user_input(line) |
|
395 | parts = isp.split_user_input(line) | |
388 | parts_expected = (u'', u'', u'', line) |
|
396 | parts_expected = (u'', u'', u'', line) | |
389 | nt.assert_equal(parts, parts_expected) |
|
397 | nt.assert_equal(parts, parts_expected) | |
390 |
|
398 | |||
391 |
|
399 | |||
392 | # Transformer tests |
|
400 | # Transformer tests | |
393 | def transform_checker(tests, func): |
|
401 | def transform_checker(tests, func): | |
394 | """Utility to loop over test inputs""" |
|
402 | """Utility to loop over test inputs""" | |
395 | for inp, tr in tests: |
|
403 | for inp, tr in tests: | |
396 | nt.assert_equals(func(inp), tr) |
|
404 | nt.assert_equals(func(inp), tr) | |
397 |
|
405 | |||
398 | # Data for all the syntax tests in the form of lists of pairs of |
|
406 | # Data for all the syntax tests in the form of lists of pairs of | |
399 | # raw/transformed input. We store it here as a global dict so that we can use |
|
407 | # raw/transformed input. We store it here as a global dict so that we can use | |
400 | # it both within single-function tests and also to validate the behavior of the |
|
408 | # it both within single-function tests and also to validate the behavior of the | |
401 | # larger objects |
|
409 | # larger objects | |
402 |
|
410 | |||
403 | syntax = \ |
|
411 | syntax = \ | |
404 | dict(assign_system = |
|
412 | dict(assign_system = | |
405 | [('a =! ls', 'a = get_ipython().getoutput("ls")'), |
|
413 | [('a =! ls', 'a = get_ipython().getoutput("ls")'), | |
406 | ('b = !ls', 'b = get_ipython().getoutput("ls")'), |
|
414 | ('b = !ls', 'b = get_ipython().getoutput("ls")'), | |
407 | ('x=1', 'x=1'), # normal input is unmodified |
|
415 | ('x=1', 'x=1'), # normal input is unmodified | |
408 | (' ',' '), # blank lines are kept intact |
|
416 | (' ',' '), # blank lines are kept intact | |
409 | ], |
|
417 | ], | |
410 |
|
418 | |||
411 | assign_magic = |
|
419 | assign_magic = | |
412 | [('a =% who', 'a = get_ipython().magic("who")'), |
|
420 | [('a =% who', 'a = get_ipython().magic("who")'), | |
413 | ('b = %who', 'b = get_ipython().magic("who")'), |
|
421 | ('b = %who', 'b = get_ipython().magic("who")'), | |
414 | ('x=1', 'x=1'), # normal input is unmodified |
|
422 | ('x=1', 'x=1'), # normal input is unmodified | |
415 | (' ',' '), # blank lines are kept intact |
|
423 | (' ',' '), # blank lines are kept intact | |
416 | ], |
|
424 | ], | |
417 |
|
425 | |||
418 | classic_prompt = |
|
426 | classic_prompt = | |
419 | [('>>> x=1', 'x=1'), |
|
427 | [('>>> x=1', 'x=1'), | |
420 | ('x=1', 'x=1'), # normal input is unmodified |
|
428 | ('x=1', 'x=1'), # normal input is unmodified | |
421 | (' ', ' '), # blank lines are kept intact |
|
429 | (' ', ' '), # blank lines are kept intact | |
422 | ('... ', ''), # continuation prompts |
|
430 | ('... ', ''), # continuation prompts | |
423 | ], |
|
431 | ], | |
424 |
|
432 | |||
425 | ipy_prompt = |
|
433 | ipy_prompt = | |
426 | [('In [1]: x=1', 'x=1'), |
|
434 | [('In [1]: x=1', 'x=1'), | |
427 | ('x=1', 'x=1'), # normal input is unmodified |
|
435 | ('x=1', 'x=1'), # normal input is unmodified | |
428 | (' ',' '), # blank lines are kept intact |
|
436 | (' ',' '), # blank lines are kept intact | |
429 | (' ....: ', ''), # continuation prompts |
|
437 | (' ....: ', ''), # continuation prompts | |
430 | ], |
|
438 | ], | |
431 |
|
439 | |||
432 | # Tests for the escape transformer to leave normal code alone |
|
440 | # Tests for the escape transformer to leave normal code alone | |
433 | escaped_noesc = |
|
441 | escaped_noesc = | |
434 | [ (' ', ' '), |
|
442 | [ (' ', ' '), | |
435 | ('x=1', 'x=1'), |
|
443 | ('x=1', 'x=1'), | |
436 | ], |
|
444 | ], | |
437 |
|
445 | |||
438 | # System calls |
|
446 | # System calls | |
439 | escaped_shell = |
|
447 | escaped_shell = | |
440 | [ ('!ls', 'get_ipython().system("ls")'), |
|
448 | [ ('!ls', 'get_ipython().system("ls")'), | |
441 | # Double-escape shell, this means to capture the output of the |
|
449 | # Double-escape shell, this means to capture the output of the | |
442 | # subprocess and return it |
|
450 | # subprocess and return it | |
443 | ('!!ls', 'get_ipython().getoutput("ls")'), |
|
451 | ('!!ls', 'get_ipython().getoutput("ls")'), | |
444 | ], |
|
452 | ], | |
445 |
|
453 | |||
446 | # Help/object info |
|
454 | # Help/object info | |
447 | escaped_help = |
|
455 | escaped_help = | |
448 | [ ('?', 'get_ipython().show_usage()'), |
|
456 | [ ('?', 'get_ipython().show_usage()'), | |
449 | ('?x1', 'get_ipython().magic("pinfo x1")'), |
|
457 | ('?x1', 'get_ipython().magic("pinfo x1")'), | |
450 | ('??x2', 'get_ipython().magic("pinfo2 x2")'), |
|
458 | ('??x2', 'get_ipython().magic("pinfo2 x2")'), | |
451 | ('x3?', 'get_ipython().magic("pinfo x3")'), |
|
459 | ('x3?', 'get_ipython().magic("pinfo x3")'), | |
452 | ('x4??', 'get_ipython().magic("pinfo2 x4")'), |
|
460 | ('x4??', 'get_ipython().magic("pinfo2 x4")'), | |
453 | ('%hist?', 'get_ipython().magic("pinfo %hist")'), |
|
461 | ('%hist?', 'get_ipython().magic("pinfo %hist")'), | |
454 | ('f*?', 'get_ipython().magic("psearch f*")'), |
|
462 | ('f*?', 'get_ipython().magic("psearch f*")'), | |
455 | ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'), |
|
463 | ('ax.*aspe*?', 'get_ipython().magic("psearch ax.*aspe*")'), | |
456 | ], |
|
464 | ], | |
457 |
|
465 | |||
458 | # Explicit magic calls |
|
466 | # Explicit magic calls | |
459 | escaped_magic = |
|
467 | escaped_magic = | |
460 | [ ('%cd', 'get_ipython().magic("cd")'), |
|
468 | [ ('%cd', 'get_ipython().magic("cd")'), | |
461 | ('%cd /home', 'get_ipython().magic("cd /home")'), |
|
469 | ('%cd /home', 'get_ipython().magic("cd /home")'), | |
462 | (' %magic', ' get_ipython().magic("magic")'), |
|
470 | (' %magic', ' get_ipython().magic("magic")'), | |
463 | ], |
|
471 | ], | |
464 |
|
472 | |||
465 | # Quoting with separate arguments |
|
473 | # Quoting with separate arguments | |
466 | escaped_quote = |
|
474 | escaped_quote = | |
467 | [ (',f', 'f("")'), |
|
475 | [ (',f', 'f("")'), | |
468 | (',f x', 'f("x")'), |
|
476 | (',f x', 'f("x")'), | |
469 | (' ,f y', ' f("y")'), |
|
477 | (' ,f y', ' f("y")'), | |
470 | (',f a b', 'f("a", "b")'), |
|
478 | (',f a b', 'f("a", "b")'), | |
471 | ], |
|
479 | ], | |
472 |
|
480 | |||
473 | # Quoting with single argument |
|
481 | # Quoting with single argument | |
474 | escaped_quote2 = |
|
482 | escaped_quote2 = | |
475 | [ (';f', 'f("")'), |
|
483 | [ (';f', 'f("")'), | |
476 | (';f x', 'f("x")'), |
|
484 | (';f x', 'f("x")'), | |
477 | (' ;f y', ' f("y")'), |
|
485 | (' ;f y', ' f("y")'), | |
478 | (';f a b', 'f("a b")'), |
|
486 | (';f a b', 'f("a b")'), | |
479 | ], |
|
487 | ], | |
480 |
|
488 | |||
481 | # Simply apply parens |
|
489 | # Simply apply parens | |
482 | escaped_paren = |
|
490 | escaped_paren = | |
483 | [ ('/f', 'f()'), |
|
491 | [ ('/f', 'f()'), | |
484 | ('/f x', 'f(x)'), |
|
492 | ('/f x', 'f(x)'), | |
485 | (' /f y', ' f(y)'), |
|
493 | (' /f y', ' f(y)'), | |
486 | ('/f a b', 'f(a, b)'), |
|
494 | ('/f a b', 'f(a, b)'), | |
487 | ], |
|
495 | ], | |
488 |
|
496 | |||
489 | ) |
|
497 | ) | |
490 |
|
498 | |||
491 | # multiline syntax examples. Each of these should be a list of lists, with |
|
499 | # multiline syntax examples. Each of these should be a list of lists, with | |
492 | # each entry itself having pairs of raw/transformed input. The union (with |
|
500 | # each entry itself having pairs of raw/transformed input. The union (with | |
493 | # '\n'.join() of the transformed inputs is what the splitter should produce |
|
501 | # '\n'.join() of the transformed inputs is what the splitter should produce | |
494 | # when fed the raw lines one at a time via push. |
|
502 | # when fed the raw lines one at a time via push. | |
495 | syntax_ml = \ |
|
503 | syntax_ml = \ | |
496 | dict(classic_prompt = |
|
504 | dict(classic_prompt = | |
497 | [ [('>>> for i in range(10):','for i in range(10):'), |
|
505 | [ [('>>> for i in range(10):','for i in range(10):'), | |
498 | ('... print i',' print i'), |
|
506 | ('... print i',' print i'), | |
499 | ('... ', ''), |
|
507 | ('... ', ''), | |
500 | ], |
|
508 | ], | |
501 | ], |
|
509 | ], | |
502 |
|
510 | |||
503 | ipy_prompt = |
|
511 | ipy_prompt = | |
504 | [ [('In [24]: for i in range(10):','for i in range(10):'), |
|
512 | [ [('In [24]: for i in range(10):','for i in range(10):'), | |
505 | (' ....: print i',' print i'), |
|
513 | (' ....: print i',' print i'), | |
506 | (' ....: ', ''), |
|
514 | (' ....: ', ''), | |
507 | ], |
|
515 | ], | |
508 | ], |
|
516 | ], | |
509 | ) |
|
517 | ) | |
510 |
|
518 | |||
511 |
|
519 | |||
512 | def test_assign_system(): |
|
520 | def test_assign_system(): | |
513 | transform_checker(syntax['assign_system'], isp.transform_assign_system) |
|
521 | transform_checker(syntax['assign_system'], isp.transform_assign_system) | |
514 |
|
522 | |||
515 |
|
523 | |||
516 | def test_assign_magic(): |
|
524 | def test_assign_magic(): | |
517 | transform_checker(syntax['assign_magic'], isp.transform_assign_magic) |
|
525 | transform_checker(syntax['assign_magic'], isp.transform_assign_magic) | |
518 |
|
526 | |||
519 |
|
527 | |||
520 | def test_classic_prompt(): |
|
528 | def test_classic_prompt(): | |
521 | transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt) |
|
529 | transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt) | |
522 | for example in syntax_ml['classic_prompt']: |
|
530 | for example in syntax_ml['classic_prompt']: | |
523 | transform_checker(example, isp.transform_classic_prompt) |
|
531 | transform_checker(example, isp.transform_classic_prompt) | |
524 |
|
532 | |||
525 |
|
533 | |||
526 | def test_ipy_prompt(): |
|
534 | def test_ipy_prompt(): | |
527 | transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt) |
|
535 | transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt) | |
528 | for example in syntax_ml['ipy_prompt']: |
|
536 | for example in syntax_ml['ipy_prompt']: | |
529 | transform_checker(example, isp.transform_ipy_prompt) |
|
537 | transform_checker(example, isp.transform_ipy_prompt) | |
530 |
|
538 | |||
531 |
|
539 | |||
532 | def test_escaped_noesc(): |
|
540 | def test_escaped_noesc(): | |
533 | transform_checker(syntax['escaped_noesc'], isp.transform_escaped) |
|
541 | transform_checker(syntax['escaped_noesc'], isp.transform_escaped) | |
534 |
|
542 | |||
535 |
|
543 | |||
536 | def test_escaped_shell(): |
|
544 | def test_escaped_shell(): | |
537 | transform_checker(syntax['escaped_shell'], isp.transform_escaped) |
|
545 | transform_checker(syntax['escaped_shell'], isp.transform_escaped) | |
538 |
|
546 | |||
539 |
|
547 | |||
540 | def test_escaped_help(): |
|
548 | def test_escaped_help(): | |
541 | transform_checker(syntax['escaped_help'], isp.transform_escaped) |
|
549 | transform_checker(syntax['escaped_help'], isp.transform_escaped) | |
542 |
|
550 | |||
543 |
|
551 | |||
544 | def test_escaped_magic(): |
|
552 | def test_escaped_magic(): | |
545 | transform_checker(syntax['escaped_magic'], isp.transform_escaped) |
|
553 | transform_checker(syntax['escaped_magic'], isp.transform_escaped) | |
546 |
|
554 | |||
547 |
|
555 | |||
548 | def test_escaped_quote(): |
|
556 | def test_escaped_quote(): | |
549 | transform_checker(syntax['escaped_quote'], isp.transform_escaped) |
|
557 | transform_checker(syntax['escaped_quote'], isp.transform_escaped) | |
550 |
|
558 | |||
551 |
|
559 | |||
552 | def test_escaped_quote2(): |
|
560 | def test_escaped_quote2(): | |
553 | transform_checker(syntax['escaped_quote2'], isp.transform_escaped) |
|
561 | transform_checker(syntax['escaped_quote2'], isp.transform_escaped) | |
554 |
|
562 | |||
555 |
|
563 | |||
556 | def test_escaped_paren(): |
|
564 | def test_escaped_paren(): | |
557 | transform_checker(syntax['escaped_paren'], isp.transform_escaped) |
|
565 | transform_checker(syntax['escaped_paren'], isp.transform_escaped) | |
558 |
|
566 | |||
559 |
|
567 | |||
560 | class IPythonInputTestCase(InputSplitterTestCase): |
|
568 | class IPythonInputTestCase(InputSplitterTestCase): | |
561 | """By just creating a new class whose .isp is a different instance, we |
|
569 | """By just creating a new class whose .isp is a different instance, we | |
562 | re-run the same test battery on the new input splitter. |
|
570 | re-run the same test battery on the new input splitter. | |
563 |
|
571 | |||
564 | In addition, this runs the tests over the syntax and syntax_ml dicts that |
|
572 | In addition, this runs the tests over the syntax and syntax_ml dicts that | |
565 | were tested by individual functions, as part of the OO interface. |
|
573 | were tested by individual functions, as part of the OO interface. | |
|
574 | ||||
|
575 | It also makes some checks on the raw buffer storage. | |||
566 | """ |
|
576 | """ | |
567 |
|
577 | |||
568 | def setUp(self): |
|
578 | def setUp(self): | |
569 | self.isp = isp.IPythonInputSplitter(input_mode='line') |
|
579 | self.isp = isp.IPythonInputSplitter(input_mode='line') | |
570 |
|
580 | |||
571 | def test_syntax(self): |
|
581 | def test_syntax(self): | |
572 | """Call all single-line syntax tests from the main object""" |
|
582 | """Call all single-line syntax tests from the main object""" | |
573 | isp = self.isp |
|
583 | isp = self.isp | |
574 | for example in syntax.itervalues(): |
|
584 | for example in syntax.itervalues(): | |
575 | for raw, out_t in example: |
|
585 | for raw, out_t in example: | |
576 | if raw.startswith(' '): |
|
586 | if raw.startswith(' '): | |
577 | continue |
|
587 | continue | |
578 |
|
588 | |||
579 | isp.push(raw) |
|
589 | isp.push(raw) | |
580 |
out = isp.source_reset |
|
590 | out, out_raw = isp.source_raw_reset() | |
581 | self.assertEqual(out, out_t) |
|
591 | self.assertEqual(out.rstrip(), out_t) | |
|
592 | self.assertEqual(out_raw.rstrip(), raw.rstrip()) | |||
582 |
|
593 | |||
583 | def test_syntax_multiline(self): |
|
594 | def test_syntax_multiline(self): | |
584 | isp = self.isp |
|
595 | isp = self.isp | |
585 | for example in syntax_ml.itervalues(): |
|
596 | for example in syntax_ml.itervalues(): | |
586 | out_t_parts = [] |
|
597 | out_t_parts = [] | |
|
598 | raw_parts = [] | |||
587 | for line_pairs in example: |
|
599 | for line_pairs in example: | |
588 | for raw, out_t_part in line_pairs: |
|
600 | for lraw, out_t_part in line_pairs: | |
589 | isp.push(raw) |
|
601 | isp.push(lraw) | |
590 | out_t_parts.append(out_t_part) |
|
602 | out_t_parts.append(out_t_part) | |
|
603 | raw_parts.append(lraw) | |||
591 |
|
604 | |||
592 |
out = isp.source_reset |
|
605 | out, out_raw = isp.source_raw_reset() | |
593 | out_t = '\n'.join(out_t_parts).rstrip() |
|
606 | out_t = '\n'.join(out_t_parts).rstrip() | |
594 | self.assertEqual(out, out_t) |
|
607 | raw = '\n'.join(raw_parts).rstrip() | |
|
608 | self.assertEqual(out.rstrip(), out_t) | |||
|
609 | self.assertEqual(out_raw.rstrip(), raw) | |||
595 |
|
610 | |||
596 |
|
611 | |||
597 | class BlockIPythonInputTestCase(IPythonInputTestCase): |
|
612 | class BlockIPythonInputTestCase(IPythonInputTestCase): | |
598 |
|
613 | |||
599 | # Deactivate tests that don't make sense for the block mode |
|
614 | # Deactivate tests that don't make sense for the block mode | |
600 | test_push3 = test_split = lambda s: None |
|
615 | test_push3 = test_split = lambda s: None | |
601 |
|
616 | |||
602 | def setUp(self): |
|
617 | def setUp(self): | |
603 | self.isp = isp.IPythonInputSplitter(input_mode='cell') |
|
618 | self.isp = isp.IPythonInputSplitter(input_mode='cell') | |
604 |
|
619 | |||
605 | def test_syntax_multiline(self): |
|
620 | def test_syntax_multiline(self): | |
606 | isp = self.isp |
|
621 | isp = self.isp | |
607 | for example in syntax_ml.itervalues(): |
|
622 | for example in syntax_ml.itervalues(): | |
608 | raw_parts = [] |
|
623 | raw_parts = [] | |
609 | out_t_parts = [] |
|
624 | out_t_parts = [] | |
610 | for line_pairs in example: |
|
625 | for line_pairs in example: | |
611 | for raw, out_t_part in line_pairs: |
|
626 | for raw, out_t_part in line_pairs: | |
612 | raw_parts.append(raw) |
|
627 | raw_parts.append(raw) | |
613 | out_t_parts.append(out_t_part) |
|
628 | out_t_parts.append(out_t_part) | |
614 |
|
629 | |||
615 | raw = '\n'.join(raw_parts) |
|
630 | raw = '\n'.join(raw_parts) | |
616 | out_t = '\n'.join(out_t_parts) |
|
631 | out_t = '\n'.join(out_t_parts) | |
617 |
|
632 | |||
618 | isp.push(raw) |
|
633 | isp.push(raw) | |
619 | out = isp.source_reset() |
|
634 | out, out_raw = isp.source_raw_reset() | |
620 | # Match ignoring trailing whitespace |
|
635 | # Match ignoring trailing whitespace | |
621 | self.assertEqual(out.rstrip(), out_t.rstrip()) |
|
636 | self.assertEqual(out.rstrip(), out_t.rstrip()) | |
|
637 | self.assertEqual(out_raw.rstrip(), raw.rstrip()) | |||
622 |
|
638 | |||
623 |
|
639 | |||
624 | #----------------------------------------------------------------------------- |
|
640 | #----------------------------------------------------------------------------- | |
625 | # Main - use as a script, mostly for developer experiments |
|
641 | # Main - use as a script, mostly for developer experiments | |
626 | #----------------------------------------------------------------------------- |
|
642 | #----------------------------------------------------------------------------- | |
627 |
|
643 | |||
628 | if __name__ == '__main__': |
|
644 | if __name__ == '__main__': | |
629 | # A simple demo for interactive experimentation. This code will not get |
|
645 | # A simple demo for interactive experimentation. This code will not get | |
630 | # picked up by any test suite. |
|
646 | # picked up by any test suite. | |
631 | from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter |
|
647 | from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter | |
632 |
|
648 | |||
633 | # configure here the syntax to use, prompt and whether to autoindent |
|
649 | # configure here the syntax to use, prompt and whether to autoindent | |
634 | #isp, start_prompt = InputSplitter(), '>>> ' |
|
650 | #isp, start_prompt = InputSplitter(), '>>> ' | |
635 | isp, start_prompt = IPythonInputSplitter(), 'In> ' |
|
651 | isp, start_prompt = IPythonInputSplitter(), 'In> ' | |
636 |
|
652 | |||
637 | autoindent = True |
|
653 | autoindent = True | |
638 | #autoindent = False |
|
654 | #autoindent = False | |
639 |
|
655 | |||
640 | try: |
|
656 | try: | |
641 | while True: |
|
657 | while True: | |
642 | prompt = start_prompt |
|
658 | prompt = start_prompt | |
643 | while isp.push_accepts_more(): |
|
659 | while isp.push_accepts_more(): | |
644 | indent = ' '*isp.indent_spaces |
|
660 | indent = ' '*isp.indent_spaces | |
645 | if autoindent: |
|
661 | if autoindent: | |
646 | line = indent + raw_input(prompt+indent) |
|
662 | line = indent + raw_input(prompt+indent) | |
647 | else: |
|
663 | else: | |
648 | line = raw_input(prompt) |
|
664 | line = raw_input(prompt) | |
649 | isp.push(line) |
|
665 | isp.push(line) | |
650 | prompt = '... ' |
|
666 | prompt = '... ' | |
651 |
|
667 | |||
652 | # Here we just return input so we can use it in a test suite, but a |
|
668 | # Here we just return input so we can use it in a test suite, but a | |
653 | # real interpreter would instead send it for execution somewhere. |
|
669 | # real interpreter would instead send it for execution somewhere. | |
654 | #src = isp.source; raise EOFError # dbg |
|
670 | #src = isp.source; raise EOFError # dbg | |
655 | src = isp.source_reset() |
|
671 | src, raw = isp.source_raw_reset() | |
656 | print 'Input source was:\n', src |
|
672 | print 'Input source was:\n', src | |
|
673 | print 'Raw source was:\n', raw | |||
657 | except EOFError: |
|
674 | except EOFError: | |
658 | print 'Bye' |
|
675 | print 'Bye' |
@@ -1,201 +1,202 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | """Magic command interface for interactive parallel work.""" |
|
4 | """Magic command interface for interactive parallel work.""" | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 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 new |
|
17 | import new | |
18 |
|
18 | |||
19 | from IPython.core.plugin import Plugin |
|
19 | from IPython.core.plugin import Plugin | |
20 | from IPython.utils.traitlets import Bool, Any, Instance |
|
20 | from IPython.utils.traitlets import Bool, Any, Instance | |
21 | from IPython.utils.autoattr import auto_attr |
|
21 | from IPython.utils.autoattr import auto_attr | |
22 | from IPython.testing import decorators as testdec |
|
22 | from IPython.testing import decorators as testdec | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Definitions of magic functions for use with IPython |
|
25 | # Definitions of magic functions for use with IPython | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 |
|
28 | |||
29 | NO_ACTIVE_MULTIENGINE_CLIENT = """ |
|
29 | NO_ACTIVE_MULTIENGINE_CLIENT = """ | |
30 | Use activate() on a MultiEngineClient object to activate it for magics. |
|
30 | Use activate() on a MultiEngineClient object to activate it for magics. | |
31 | """ |
|
31 | """ | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | class ParalleMagic(Plugin): |
|
34 | class ParalleMagic(Plugin): | |
35 | """A component to manage the %result, %px and %autopx magics.""" |
|
35 | """A component to manage the %result, %px and %autopx magics.""" | |
36 |
|
36 | |||
37 | active_multiengine_client = Any() |
|
37 | active_multiengine_client = Any() | |
38 | verbose = Bool(False, config=True) |
|
38 | verbose = Bool(False, config=True) | |
39 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
39 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
40 |
|
40 | |||
41 | def __init__(self, shell=None, config=None): |
|
41 | def __init__(self, shell=None, config=None): | |
42 | super(ParalleMagic, self).__init__(shell=shell, config=config) |
|
42 | super(ParalleMagic, self).__init__(shell=shell, config=config) | |
43 | self._define_magics() |
|
43 | self._define_magics() | |
44 | # A flag showing if autopx is activated or not |
|
44 | # A flag showing if autopx is activated or not | |
45 | self.autopx = False |
|
45 | self.autopx = False | |
46 |
|
46 | |||
47 | def _define_magics(self): |
|
47 | def _define_magics(self): | |
48 | """Define the magic functions.""" |
|
48 | """Define the magic functions.""" | |
49 | self.shell.define_magic('result', self.magic_result) |
|
49 | self.shell.define_magic('result', self.magic_result) | |
50 | self.shell.define_magic('px', self.magic_px) |
|
50 | self.shell.define_magic('px', self.magic_px) | |
51 | self.shell.define_magic('autopx', self.magic_autopx) |
|
51 | self.shell.define_magic('autopx', self.magic_autopx) | |
52 |
|
52 | |||
53 | @testdec.skip_doctest |
|
53 | @testdec.skip_doctest | |
54 | def magic_result(self, ipself, parameter_s=''): |
|
54 | def magic_result(self, ipself, parameter_s=''): | |
55 | """Print the result of command i on all engines.. |
|
55 | """Print the result of command i on all engines.. | |
56 |
|
56 | |||
57 | To use this a :class:`MultiEngineClient` instance must be created |
|
57 | To use this a :class:`MultiEngineClient` instance must be created | |
58 | and then activated by calling its :meth:`activate` method. |
|
58 | and then activated by calling its :meth:`activate` method. | |
59 |
|
59 | |||
60 | Then you can do the following:: |
|
60 | Then you can do the following:: | |
61 |
|
61 | |||
62 | In [23]: %result |
|
62 | In [23]: %result | |
63 | Out[23]: |
|
63 | Out[23]: | |
64 | <Results List> |
|
64 | <Results List> | |
65 | [0] In [6]: a = 10 |
|
65 | [0] In [6]: a = 10 | |
66 | [1] In [6]: a = 10 |
|
66 | [1] In [6]: a = 10 | |
67 |
|
67 | |||
68 | In [22]: %result 6 |
|
68 | In [22]: %result 6 | |
69 | Out[22]: |
|
69 | Out[22]: | |
70 | <Results List> |
|
70 | <Results List> | |
71 | [0] In [6]: a = 10 |
|
71 | [0] In [6]: a = 10 | |
72 | [1] In [6]: a = 10 |
|
72 | [1] In [6]: a = 10 | |
73 | """ |
|
73 | """ | |
74 | if self.active_multiengine_client is None: |
|
74 | if self.active_multiengine_client is None: | |
75 | print NO_ACTIVE_MULTIENGINE_CLIENT |
|
75 | print NO_ACTIVE_MULTIENGINE_CLIENT | |
76 | return |
|
76 | return | |
77 |
|
77 | |||
78 | try: |
|
78 | try: | |
79 | index = int(parameter_s) |
|
79 | index = int(parameter_s) | |
80 | except: |
|
80 | except: | |
81 | index = None |
|
81 | index = None | |
82 | result = self.active_multiengine_client.get_result(index) |
|
82 | result = self.active_multiengine_client.get_result(index) | |
83 | return result |
|
83 | return result | |
84 |
|
84 | |||
85 | @testdec.skip_doctest |
|
85 | @testdec.skip_doctest | |
86 | def magic_px(self, ipself, parameter_s=''): |
|
86 | def magic_px(self, ipself, parameter_s=''): | |
87 | """Executes the given python command in parallel. |
|
87 | """Executes the given python command in parallel. | |
88 |
|
88 | |||
89 | To use this a :class:`MultiEngineClient` instance must be created |
|
89 | To use this a :class:`MultiEngineClient` instance must be created | |
90 | and then activated by calling its :meth:`activate` method. |
|
90 | and then activated by calling its :meth:`activate` method. | |
91 |
|
91 | |||
92 | Then you can do the following:: |
|
92 | Then you can do the following:: | |
93 |
|
93 | |||
94 | In [24]: %px a = 5 |
|
94 | In [24]: %px a = 5 | |
95 | Parallel execution on engines: all |
|
95 | Parallel execution on engines: all | |
96 | Out[24]: |
|
96 | Out[24]: | |
97 | <Results List> |
|
97 | <Results List> | |
98 | [0] In [7]: a = 5 |
|
98 | [0] In [7]: a = 5 | |
99 | [1] In [7]: a = 5 |
|
99 | [1] In [7]: a = 5 | |
100 | """ |
|
100 | """ | |
101 |
|
101 | |||
102 | if self.active_multiengine_client is None: |
|
102 | if self.active_multiengine_client is None: | |
103 | print NO_ACTIVE_MULTIENGINE_CLIENT |
|
103 | print NO_ACTIVE_MULTIENGINE_CLIENT | |
104 | return |
|
104 | return | |
105 | print "Parallel execution on engines: %s" % self.active_multiengine_client.targets |
|
105 | print "Parallel execution on engines: %s" % self.active_multiengine_client.targets | |
106 | result = self.active_multiengine_client.execute(parameter_s) |
|
106 | result = self.active_multiengine_client.execute(parameter_s) | |
107 | return result |
|
107 | return result | |
108 |
|
108 | |||
109 | @testdec.skip_doctest |
|
109 | @testdec.skip_doctest | |
110 | def magic_autopx(self, ipself, parameter_s=''): |
|
110 | def magic_autopx(self, ipself, parameter_s=''): | |
111 | """Toggles auto parallel mode. |
|
111 | """Toggles auto parallel mode. | |
112 |
|
112 | |||
113 | To use this a :class:`MultiEngineClient` instance must be created |
|
113 | To use this a :class:`MultiEngineClient` instance must be created | |
114 | and then activated by calling its :meth:`activate` method. Once this |
|
114 | and then activated by calling its :meth:`activate` method. Once this | |
115 | is called, all commands typed at the command line are send to |
|
115 | is called, all commands typed at the command line are send to | |
116 | the engines to be executed in parallel. To control which engine |
|
116 | the engines to be executed in parallel. To control which engine | |
117 | are used, set the ``targets`` attributed of the multiengine client |
|
117 | are used, set the ``targets`` attributed of the multiengine client | |
118 | before entering ``%autopx`` mode. |
|
118 | before entering ``%autopx`` mode. | |
119 |
|
119 | |||
120 | Then you can do the following:: |
|
120 | Then you can do the following:: | |
121 |
|
121 | |||
122 | In [25]: %autopx |
|
122 | In [25]: %autopx | |
123 | %autopx to enabled |
|
123 | %autopx to enabled | |
124 |
|
124 | |||
125 | In [26]: a = 10 |
|
125 | In [26]: a = 10 | |
126 | <Results List> |
|
126 | <Results List> | |
127 | [0] In [8]: a = 10 |
|
127 | [0] In [8]: a = 10 | |
128 | [1] In [8]: a = 10 |
|
128 | [1] In [8]: a = 10 | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | In [27]: %autopx |
|
131 | In [27]: %autopx | |
132 | %autopx disabled |
|
132 | %autopx disabled | |
133 | """ |
|
133 | """ | |
134 | if self.autopx: |
|
134 | if self.autopx: | |
135 | self._disable_autopx() |
|
135 | self._disable_autopx() | |
136 | else: |
|
136 | else: | |
137 | self._enable_autopx() |
|
137 | self._enable_autopx() | |
138 |
|
138 | |||
139 | def _enable_autopx(self): |
|
139 | def _enable_autopx(self): | |
140 | """Enable %autopx mode by saving the original runsource and installing |
|
140 | """Enable %autopx mode by saving the original run_source and installing | |
141 | pxrunsource. |
|
141 | pxrun_source. | |
142 | """ |
|
142 | """ | |
143 | if self.active_multiengine_client is None: |
|
143 | if self.active_multiengine_client is None: | |
144 | print NO_ACTIVE_MULTIENGINE_CLIENT |
|
144 | print NO_ACTIVE_MULTIENGINE_CLIENT | |
145 | return |
|
145 | return | |
146 |
|
146 | |||
147 | self._original_runsource = self.shell.runsource |
|
147 | self._original_run_source = self.shell.run_source | |
148 | self.shell.runsource = new.instancemethod( |
|
148 | self.shell.run_source = new.instancemethod( | |
149 | self.pxrunsource, self.shell, self.shell.__class__ |
|
149 | self.pxrun_source, self.shell, self.shell.__class__ | |
150 | ) |
|
150 | ) | |
151 | self.autopx = True |
|
151 | self.autopx = True | |
152 | print "%autopx enabled" |
|
152 | print "%autopx enabled" | |
153 |
|
153 | |||
154 | def _disable_autopx(self): |
|
154 | def _disable_autopx(self): | |
155 |
"""Disable %autopx by restoring the original InteractiveShell.runsource. |
|
155 | """Disable %autopx by restoring the original InteractiveShell.run_source. | |
|
156 | """ | |||
156 | if self.autopx: |
|
157 | if self.autopx: | |
157 | self.shell.runsource = self._original_runsource |
|
158 | self.shell.run_source = self._original_run_source | |
158 | self.autopx = False |
|
159 | self.autopx = False | |
159 | print "%autopx disabled" |
|
160 | print "%autopx disabled" | |
160 |
|
161 | |||
161 | def pxrunsource(self, ipself, source, filename="<input>", symbol="single"): |
|
162 | def pxrun_source(self, ipself, source, filename="<input>", symbol="single"): | |
162 | """A parallel replacement for InteractiveShell.runsource.""" |
|
163 | """A parallel replacement for InteractiveShell.run_source.""" | |
163 |
|
164 | |||
164 | try: |
|
165 | try: | |
165 | code = ipself.compile(source, filename, symbol) |
|
166 | code = ipself.compile(source, filename, symbol) | |
166 | except (OverflowError, SyntaxError, ValueError): |
|
167 | except (OverflowError, SyntaxError, ValueError): | |
167 | # Case 1 |
|
168 | # Case 1 | |
168 | ipself.showsyntaxerror(filename) |
|
169 | ipself.showsyntaxerror(filename) | |
169 | return None |
|
170 | return None | |
170 |
|
171 | |||
171 | if code is None: |
|
172 | if code is None: | |
172 | # Case 2 |
|
173 | # Case 2 | |
173 | return True |
|
174 | return True | |
174 |
|
175 | |||
175 | # Case 3 |
|
176 | # Case 3 | |
176 | # Because autopx is enabled, we now call executeAll or disable autopx if |
|
177 | # Because autopx is enabled, we now call executeAll or disable autopx if | |
177 | # %autopx or autopx has been called |
|
178 | # %autopx or autopx has been called | |
178 | if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source: |
|
179 | if 'get_ipython().magic("%autopx' in source or 'get_ipython().magic("autopx' in source: | |
179 | self._disable_autopx() |
|
180 | self._disable_autopx() | |
180 | return False |
|
181 | return False | |
181 | else: |
|
182 | else: | |
182 | try: |
|
183 | try: | |
183 | result = self.active_multiengine_client.execute(source) |
|
184 | result = self.active_multiengine_client.execute(source) | |
184 | except: |
|
185 | except: | |
185 | ipself.showtraceback() |
|
186 | ipself.showtraceback() | |
186 | else: |
|
187 | else: | |
187 | print result.__repr__() |
|
188 | print result.__repr__() | |
188 | return False |
|
189 | return False | |
189 |
|
190 | |||
190 |
|
191 | |||
191 | _loaded = False |
|
192 | _loaded = False | |
192 |
|
193 | |||
193 |
|
194 | |||
194 | def load_ipython_extension(ip): |
|
195 | def load_ipython_extension(ip): | |
195 | """Load the extension in IPython.""" |
|
196 | """Load the extension in IPython.""" | |
196 | global _loaded |
|
197 | global _loaded | |
197 | if not _loaded: |
|
198 | if not _loaded: | |
198 | plugin = ParalleMagic(shell=ip, config=ip.config) |
|
199 | plugin = ParalleMagic(shell=ip, config=ip.config) | |
199 | ip.plugin_manager.register_plugin('parallel_magic', plugin) |
|
200 | ip.plugin_manager.register_plugin('parallel_magic', plugin) | |
200 | _loaded = True |
|
201 | _loaded = True | |
201 |
|
202 |
@@ -1,652 +1,615 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
2 | """Subclass of InteractiveShell for terminal based frontends.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | from contextlib import nested |
|
19 | from contextlib import nested | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 |
|
23 | |||
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.usage import interactive_usage, default_banner |
|
25 | from IPython.core.usage import interactive_usage, default_banner | |
26 | from IPython.core.inputlist import InputList |
|
26 | from IPython.core.inputlist import InputList | |
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | |
28 | from IPython.lib.inputhook import enable_gui |
|
28 | from IPython.lib.inputhook import enable_gui | |
29 | from IPython.lib.pylabtools import pylab_activate |
|
29 | from IPython.lib.pylabtools import pylab_activate | |
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title | |
31 | from IPython.utils.process import abbrev_cwd |
|
31 | from IPython.utils.process import abbrev_cwd | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 | from IPython.utils.text import num_ini_spaces |
|
33 | from IPython.utils.text import num_ini_spaces | |
34 | from IPython.utils.traitlets import Int, Str, CBool |
|
34 | from IPython.utils.traitlets import Int, Str, CBool | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | # Utilities |
|
38 | # Utilities | |
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | def get_default_editor(): |
|
42 | def get_default_editor(): | |
43 | try: |
|
43 | try: | |
44 | ed = os.environ['EDITOR'] |
|
44 | ed = os.environ['EDITOR'] | |
45 | except KeyError: |
|
45 | except KeyError: | |
46 | if os.name == 'posix': |
|
46 | if os.name == 'posix': | |
47 | ed = 'vi' # the only one guaranteed to be there! |
|
47 | ed = 'vi' # the only one guaranteed to be there! | |
48 | else: |
|
48 | else: | |
49 | ed = 'notepad' # same in Windows! |
|
49 | ed = 'notepad' # same in Windows! | |
50 | return ed |
|
50 | return ed | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | # store the builtin raw_input globally, and use this always, in case user code |
|
53 | # store the builtin raw_input globally, and use this always, in case user code | |
54 | # overwrites it (like wx.py.PyShell does) |
|
54 | # overwrites it (like wx.py.PyShell does) | |
55 | raw_input_original = raw_input |
|
55 | raw_input_original = raw_input | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | #----------------------------------------------------------------------------- |
|
58 | #----------------------------------------------------------------------------- | |
59 | # Main class |
|
59 | # Main class | |
60 | #----------------------------------------------------------------------------- |
|
60 | #----------------------------------------------------------------------------- | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | class TerminalInteractiveShell(InteractiveShell): |
|
63 | class TerminalInteractiveShell(InteractiveShell): | |
64 |
|
64 | |||
65 | autoedit_syntax = CBool(False, config=True) |
|
65 | autoedit_syntax = CBool(False, config=True) | |
66 | banner = Str('') |
|
66 | banner = Str('') | |
67 | banner1 = Str(default_banner, config=True) |
|
67 | banner1 = Str(default_banner, config=True) | |
68 | banner2 = Str('', config=True) |
|
68 | banner2 = Str('', config=True) | |
69 | confirm_exit = CBool(True, config=True) |
|
69 | confirm_exit = CBool(True, config=True) | |
70 | # This display_banner only controls whether or not self.show_banner() |
|
70 | # This display_banner only controls whether or not self.show_banner() | |
71 | # is called when mainloop/interact are called. The default is False |
|
71 | # is called when mainloop/interact are called. The default is False | |
72 | # because for the terminal based application, the banner behavior |
|
72 | # because for the terminal based application, the banner behavior | |
73 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
73 | # is controlled by Global.display_banner, which IPythonApp looks at | |
74 | # to determine if *it* should call show_banner() by hand or not. |
|
74 | # to determine if *it* should call show_banner() by hand or not. | |
75 | display_banner = CBool(False) # This isn't configurable! |
|
75 | display_banner = CBool(False) # This isn't configurable! | |
76 | embedded = CBool(False) |
|
76 | embedded = CBool(False) | |
77 | embedded_active = CBool(False) |
|
77 | embedded_active = CBool(False) | |
78 | editor = Str(get_default_editor(), config=True) |
|
78 | editor = Str(get_default_editor(), config=True) | |
79 | pager = Str('less', config=True) |
|
79 | pager = Str('less', config=True) | |
80 |
|
80 | |||
81 | screen_length = Int(0, config=True) |
|
81 | screen_length = Int(0, config=True) | |
82 | term_title = CBool(False, config=True) |
|
82 | term_title = CBool(False, config=True) | |
83 |
|
83 | |||
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, |
|
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, | |
85 | user_global_ns=None, custom_exceptions=((),None), |
|
85 | user_global_ns=None, custom_exceptions=((),None), | |
86 | usage=None, banner1=None, banner2=None, |
|
86 | usage=None, banner1=None, banner2=None, | |
87 | display_banner=None): |
|
87 | display_banner=None): | |
88 |
|
88 | |||
89 | super(TerminalInteractiveShell, self).__init__( |
|
89 | super(TerminalInteractiveShell, self).__init__( | |
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, |
|
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, | |
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions |
|
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions | |
92 | ) |
|
92 | ) | |
93 | self.init_term_title() |
|
93 | self.init_term_title() | |
94 | self.init_usage(usage) |
|
94 | self.init_usage(usage) | |
95 | self.init_banner(banner1, banner2, display_banner) |
|
95 | self.init_banner(banner1, banner2, display_banner) | |
96 |
|
96 | |||
97 | #------------------------------------------------------------------------- |
|
97 | #------------------------------------------------------------------------- | |
98 | # Things related to the terminal |
|
98 | # Things related to the terminal | |
99 | #------------------------------------------------------------------------- |
|
99 | #------------------------------------------------------------------------- | |
100 |
|
100 | |||
101 | @property |
|
101 | @property | |
102 | def usable_screen_length(self): |
|
102 | def usable_screen_length(self): | |
103 | if self.screen_length == 0: |
|
103 | if self.screen_length == 0: | |
104 | return 0 |
|
104 | return 0 | |
105 | else: |
|
105 | else: | |
106 | num_lines_bot = self.separate_in.count('\n')+1 |
|
106 | num_lines_bot = self.separate_in.count('\n')+1 | |
107 | return self.screen_length - num_lines_bot |
|
107 | return self.screen_length - num_lines_bot | |
108 |
|
108 | |||
109 | def init_term_title(self): |
|
109 | def init_term_title(self): | |
110 | # Enable or disable the terminal title. |
|
110 | # Enable or disable the terminal title. | |
111 | if self.term_title: |
|
111 | if self.term_title: | |
112 | toggle_set_term_title(True) |
|
112 | toggle_set_term_title(True) | |
113 | set_term_title('IPython: ' + abbrev_cwd()) |
|
113 | set_term_title('IPython: ' + abbrev_cwd()) | |
114 | else: |
|
114 | else: | |
115 | toggle_set_term_title(False) |
|
115 | toggle_set_term_title(False) | |
116 |
|
116 | |||
117 | #------------------------------------------------------------------------- |
|
117 | #------------------------------------------------------------------------- | |
118 | # Things related to aliases |
|
118 | # Things related to aliases | |
119 | #------------------------------------------------------------------------- |
|
119 | #------------------------------------------------------------------------- | |
120 |
|
120 | |||
121 | def init_alias(self): |
|
121 | def init_alias(self): | |
122 | # The parent class defines aliases that can be safely used with any |
|
122 | # The parent class defines aliases that can be safely used with any | |
123 | # frontend. |
|
123 | # frontend. | |
124 | super(TerminalInteractiveShell, self).init_alias() |
|
124 | super(TerminalInteractiveShell, self).init_alias() | |
125 |
|
125 | |||
126 | # Now define aliases that only make sense on the terminal, because they |
|
126 | # Now define aliases that only make sense on the terminal, because they | |
127 | # need direct access to the console in a way that we can't emulate in |
|
127 | # need direct access to the console in a way that we can't emulate in | |
128 | # GUI or web frontend |
|
128 | # GUI or web frontend | |
129 | if os.name == 'posix': |
|
129 | if os.name == 'posix': | |
130 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
130 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), | |
131 | ('man', 'man')] |
|
131 | ('man', 'man')] | |
132 | elif os.name == 'nt': |
|
132 | elif os.name == 'nt': | |
133 | aliases = [('cls', 'cls')] |
|
133 | aliases = [('cls', 'cls')] | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | for name, cmd in aliases: |
|
136 | for name, cmd in aliases: | |
137 | self.alias_manager.define_alias(name, cmd) |
|
137 | self.alias_manager.define_alias(name, cmd) | |
138 |
|
138 | |||
139 | #------------------------------------------------------------------------- |
|
139 | #------------------------------------------------------------------------- | |
140 | # Things related to the banner and usage |
|
140 | # Things related to the banner and usage | |
141 | #------------------------------------------------------------------------- |
|
141 | #------------------------------------------------------------------------- | |
142 |
|
142 | |||
143 | def _banner1_changed(self): |
|
143 | def _banner1_changed(self): | |
144 | self.compute_banner() |
|
144 | self.compute_banner() | |
145 |
|
145 | |||
146 | def _banner2_changed(self): |
|
146 | def _banner2_changed(self): | |
147 | self.compute_banner() |
|
147 | self.compute_banner() | |
148 |
|
148 | |||
149 | def _term_title_changed(self, name, new_value): |
|
149 | def _term_title_changed(self, name, new_value): | |
150 | self.init_term_title() |
|
150 | self.init_term_title() | |
151 |
|
151 | |||
152 | def init_banner(self, banner1, banner2, display_banner): |
|
152 | def init_banner(self, banner1, banner2, display_banner): | |
153 | if banner1 is not None: |
|
153 | if banner1 is not None: | |
154 | self.banner1 = banner1 |
|
154 | self.banner1 = banner1 | |
155 | if banner2 is not None: |
|
155 | if banner2 is not None: | |
156 | self.banner2 = banner2 |
|
156 | self.banner2 = banner2 | |
157 | if display_banner is not None: |
|
157 | if display_banner is not None: | |
158 | self.display_banner = display_banner |
|
158 | self.display_banner = display_banner | |
159 | self.compute_banner() |
|
159 | self.compute_banner() | |
160 |
|
160 | |||
161 | def show_banner(self, banner=None): |
|
161 | def show_banner(self, banner=None): | |
162 | if banner is None: |
|
162 | if banner is None: | |
163 | banner = self.banner |
|
163 | banner = self.banner | |
164 | self.write(banner) |
|
164 | self.write(banner) | |
165 |
|
165 | |||
166 | def compute_banner(self): |
|
166 | def compute_banner(self): | |
167 | self.banner = self.banner1 |
|
167 | self.banner = self.banner1 | |
168 | if self.profile: |
|
168 | if self.profile: | |
169 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
169 | self.banner += '\nIPython profile: %s\n' % self.profile | |
170 | if self.banner2: |
|
170 | if self.banner2: | |
171 | self.banner += '\n' + self.banner2 |
|
171 | self.banner += '\n' + self.banner2 | |
172 |
|
172 | |||
173 | def init_usage(self, usage=None): |
|
173 | def init_usage(self, usage=None): | |
174 | if usage is None: |
|
174 | if usage is None: | |
175 | self.usage = interactive_usage |
|
175 | self.usage = interactive_usage | |
176 | else: |
|
176 | else: | |
177 | self.usage = usage |
|
177 | self.usage = usage | |
178 |
|
178 | |||
179 | #------------------------------------------------------------------------- |
|
179 | #------------------------------------------------------------------------- | |
180 | # Mainloop and code execution logic |
|
180 | # Mainloop and code execution logic | |
181 | #------------------------------------------------------------------------- |
|
181 | #------------------------------------------------------------------------- | |
182 |
|
182 | |||
183 | def mainloop(self, display_banner=None): |
|
183 | def mainloop(self, display_banner=None): | |
184 | """Start the mainloop. |
|
184 | """Start the mainloop. | |
185 |
|
185 | |||
186 | If an optional banner argument is given, it will override the |
|
186 | If an optional banner argument is given, it will override the | |
187 | internally created default banner. |
|
187 | internally created default banner. | |
188 | """ |
|
188 | """ | |
189 |
|
189 | |||
190 | with nested(self.builtin_trap, self.display_trap): |
|
190 | with nested(self.builtin_trap, self.display_trap): | |
191 |
|
191 | |||
192 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
192 | # if you run stuff with -c <cmd>, raw hist is not updated | |
193 | # ensure that it's in sync |
|
193 | # ensure that it's in sync | |
194 | if len(self.input_hist) != len (self.input_hist_raw): |
|
194 | self.history_manager.sync_inputs() | |
195 | self.input_hist_raw = InputList(self.input_hist) |
|
|||
196 |
|
195 | |||
197 | while 1: |
|
196 | while 1: | |
198 | try: |
|
197 | try: | |
199 | self.interact(display_banner=display_banner) |
|
198 | self.interact(display_banner=display_banner) | |
200 | #self.interact_with_readline() |
|
199 | #self.interact_with_readline() | |
201 | # XXX for testing of a readline-decoupled repl loop, call |
|
200 | # XXX for testing of a readline-decoupled repl loop, call | |
202 | # interact_with_readline above |
|
201 | # interact_with_readline above | |
203 | break |
|
202 | break | |
204 | except KeyboardInterrupt: |
|
203 | except KeyboardInterrupt: | |
205 | # this should not be necessary, but KeyboardInterrupt |
|
204 | # this should not be necessary, but KeyboardInterrupt | |
206 | # handling seems rather unpredictable... |
|
205 | # handling seems rather unpredictable... | |
207 | self.write("\nKeyboardInterrupt in interact()\n") |
|
206 | self.write("\nKeyboardInterrupt in interact()\n") | |
208 |
|
207 | |||
209 | def interact(self, display_banner=None): |
|
208 | def interact(self, display_banner=None): | |
210 | """Closely emulate the interactive Python console.""" |
|
209 | """Closely emulate the interactive Python console.""" | |
211 |
|
210 | |||
212 | # batch run -> do not interact |
|
211 | # batch run -> do not interact | |
213 | if self.exit_now: |
|
212 | if self.exit_now: | |
214 | return |
|
213 | return | |
215 |
|
214 | |||
216 | if display_banner is None: |
|
215 | if display_banner is None: | |
217 | display_banner = self.display_banner |
|
216 | display_banner = self.display_banner | |
218 | if display_banner: |
|
217 | if display_banner: | |
219 | self.show_banner() |
|
218 | self.show_banner() | |
220 |
|
219 | |||
221 |
more = |
|
220 | more = False | |
222 |
|
221 | |||
223 | # Mark activity in the builtins |
|
222 | # Mark activity in the builtins | |
224 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
223 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
225 |
|
224 | |||
226 | if self.has_readline: |
|
225 | if self.has_readline: | |
227 | self.readline_startup_hook(self.pre_readline) |
|
226 | self.readline_startup_hook(self.pre_readline) | |
228 | # exit_now is set by a call to %Exit or %Quit, through the |
|
227 | # exit_now is set by a call to %Exit or %Quit, through the | |
229 | # ask_exit callback. |
|
228 | # ask_exit callback. | |
230 |
|
229 | |||
231 | while not self.exit_now: |
|
230 | while not self.exit_now: | |
232 | self.hooks.pre_prompt_hook() |
|
231 | self.hooks.pre_prompt_hook() | |
233 | if more: |
|
232 | if more: | |
234 | try: |
|
233 | try: | |
235 | prompt = self.hooks.generate_prompt(True) |
|
234 | prompt = self.hooks.generate_prompt(True) | |
236 | except: |
|
235 | except: | |
237 | self.showtraceback() |
|
236 | self.showtraceback() | |
238 | if self.autoindent: |
|
237 | if self.autoindent: | |
239 | self.rl_do_indent = True |
|
238 | self.rl_do_indent = True | |
240 |
|
239 | |||
241 | else: |
|
240 | else: | |
242 | try: |
|
241 | try: | |
243 | prompt = self.hooks.generate_prompt(False) |
|
242 | prompt = self.hooks.generate_prompt(False) | |
244 | except: |
|
243 | except: | |
245 | self.showtraceback() |
|
244 | self.showtraceback() | |
246 | try: |
|
245 | try: | |
247 |
line = self.raw_input(prompt |
|
246 | line = self.raw_input(prompt) | |
248 | if self.exit_now: |
|
247 | if self.exit_now: | |
249 | # quick exit on sys.std[in|out] close |
|
248 | # quick exit on sys.std[in|out] close | |
250 | break |
|
249 | break | |
251 | if self.autoindent: |
|
250 | if self.autoindent: | |
252 | self.rl_do_indent = False |
|
251 | self.rl_do_indent = False | |
253 |
|
252 | |||
254 | except KeyboardInterrupt: |
|
253 | except KeyboardInterrupt: | |
255 | #double-guard against keyboardinterrupts during kbdint handling |
|
254 | #double-guard against keyboardinterrupts during kbdint handling | |
256 | try: |
|
255 | try: | |
257 | self.write('\nKeyboardInterrupt\n') |
|
256 | self.write('\nKeyboardInterrupt\n') | |
258 | self.resetbuffer() |
|
257 | self.resetbuffer() | |
259 | # keep cache in sync with the prompt counter: |
|
258 | more = False | |
260 | self.displayhook.prompt_count -= 1 |
|
|||
261 |
|
||||
262 | if self.autoindent: |
|
|||
263 | self.indent_current_nsp = 0 |
|
|||
264 | more = 0 |
|
|||
265 | except KeyboardInterrupt: |
|
259 | except KeyboardInterrupt: | |
266 | pass |
|
260 | pass | |
267 | except EOFError: |
|
261 | except EOFError: | |
268 | if self.autoindent: |
|
262 | if self.autoindent: | |
269 | self.rl_do_indent = False |
|
263 | self.rl_do_indent = False | |
270 | if self.has_readline: |
|
264 | if self.has_readline: | |
271 | self.readline_startup_hook(None) |
|
265 | self.readline_startup_hook(None) | |
272 | self.write('\n') |
|
266 | self.write('\n') | |
273 | self.exit() |
|
267 | self.exit() | |
274 | except bdb.BdbQuit: |
|
268 | except bdb.BdbQuit: | |
275 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
269 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
276 | 'Because of how pdb handles the stack, it is impossible\n' |
|
270 | 'Because of how pdb handles the stack, it is impossible\n' | |
277 | 'for IPython to properly format this particular exception.\n' |
|
271 | 'for IPython to properly format this particular exception.\n' | |
278 | 'IPython will resume normal operation.') |
|
272 | 'IPython will resume normal operation.') | |
279 | except: |
|
273 | except: | |
280 | # exceptions here are VERY RARE, but they can be triggered |
|
274 | # exceptions here are VERY RARE, but they can be triggered | |
281 | # asynchronously by signal handlers, for example. |
|
275 | # asynchronously by signal handlers, for example. | |
282 | self.showtraceback() |
|
276 | self.showtraceback() | |
283 | else: |
|
277 | else: | |
284 |
|
|
278 | self.input_splitter.push(line) | |
|
279 | more = self.input_splitter.push_accepts_more() | |||
285 | if (self.SyntaxTB.last_syntax_error and |
|
280 | if (self.SyntaxTB.last_syntax_error and | |
286 | self.autoedit_syntax): |
|
281 | self.autoedit_syntax): | |
287 | self.edit_syntax_error() |
|
282 | self.edit_syntax_error() | |
288 |
|
283 | if not more: | ||
|
284 | source_raw = self.input_splitter.source_raw_reset()[1] | |||
|
285 | self.run_cell(source_raw) | |||
|
286 | ||||
289 | # We are off again... |
|
287 | # We are off again... | |
290 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
288 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
291 |
|
289 | |||
292 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
290 | # Turn off the exit flag, so the mainloop can be restarted if desired | |
293 | self.exit_now = False |
|
291 | self.exit_now = False | |
294 |
|
292 | |||
295 | def raw_input(self,prompt='',continue_prompt=False): |
|
293 | def raw_input(self, prompt='', continue_prompt=False): | |
296 | """Write a prompt and read a line. |
|
294 | """Write a prompt and read a line. | |
297 |
|
295 | |||
298 | The returned line does not include the trailing newline. |
|
296 | The returned line does not include the trailing newline. | |
299 | When the user enters the EOF key sequence, EOFError is raised. |
|
297 | When the user enters the EOF key sequence, EOFError is raised. | |
300 |
|
298 | |||
301 | Optional inputs: |
|
299 | Optional inputs: | |
302 |
|
300 | |||
303 | - prompt(''): a string to be printed to prompt the user. |
|
301 | - prompt(''): a string to be printed to prompt the user. | |
304 |
|
302 | |||
305 | - continue_prompt(False): whether this line is the first one or a |
|
303 | - continue_prompt(False): whether this line is the first one or a | |
306 | continuation in a sequence of inputs. |
|
304 | continuation in a sequence of inputs. | |
307 | """ |
|
305 | """ | |
308 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
|||
309 |
|
||||
310 | # Code run by the user may have modified the readline completer state. |
|
306 | # Code run by the user may have modified the readline completer state. | |
311 | # We must ensure that our completer is back in place. |
|
307 | # We must ensure that our completer is back in place. | |
312 |
|
308 | |||
313 | if self.has_readline: |
|
309 | if self.has_readline: | |
314 | self.set_readline_completer() |
|
310 | self.set_readline_completer() | |
315 |
|
311 | |||
316 | try: |
|
312 | try: | |
317 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
313 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
318 | except ValueError: |
|
314 | except ValueError: | |
319 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
315 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
320 | " or sys.stdout.close()!\nExiting IPython!") |
|
316 | " or sys.stdout.close()!\nExiting IPython!") | |
321 | self.ask_exit() |
|
317 | self.ask_exit() | |
322 | return "" |
|
318 | return "" | |
323 |
|
319 | |||
324 | # Try to be reasonably smart about not re-indenting pasted input more |
|
320 | # Try to be reasonably smart about not re-indenting pasted input more | |
325 | # than necessary. We do this by trimming out the auto-indent initial |
|
321 | # than necessary. We do this by trimming out the auto-indent initial | |
326 | # spaces, if the user's actual input started itself with whitespace. |
|
322 | # spaces, if the user's actual input started itself with whitespace. | |
327 | #debugx('self.buffer[-1]') |
|
|||
328 |
|
||||
329 | if self.autoindent: |
|
323 | if self.autoindent: | |
330 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
324 | if num_ini_spaces(line) > self.indent_current_nsp: | |
331 | line = line[self.indent_current_nsp:] |
|
325 | line = line[self.indent_current_nsp:] | |
332 | self.indent_current_nsp = 0 |
|
326 | self.indent_current_nsp = 0 | |
333 |
|
327 | |||
334 | # store the unfiltered input before the user has any chance to modify |
|
328 | # store the unfiltered input before the user has any chance to modify | |
335 | # it. |
|
329 | # it. | |
336 | if line.strip(): |
|
330 | if line.strip(): | |
337 | if continue_prompt: |
|
331 | if continue_prompt: | |
338 | self.input_hist_raw[-1] += '%s\n' % line |
|
|||
339 | if self.has_readline and self.readline_use: |
|
332 | if self.has_readline and self.readline_use: | |
340 | try: |
|
333 | histlen = self.readline.get_current_history_length() | |
341 | histlen = self.readline.get_current_history_length() |
|
334 | if histlen > 1: | |
342 | if histlen > 1: |
|
335 | newhist = self.input_hist_raw[-1].rstrip() | |
343 | newhist = self.input_hist_raw[-1].rstrip() |
|
336 | self.readline.remove_history_item(histlen-1) | |
344 |
|
|
337 | self.readline.replace_history_item(histlen-2, | |
345 | self.readline.replace_history_item(histlen-2, |
|
338 | newhist.encode(self.stdin_encoding)) | |
346 | newhist.encode(self.stdin_encoding)) |
|
|||
347 | except AttributeError: |
|
|||
348 | pass # re{move,place}_history_item are new in 2.4. |
|
|||
349 | else: |
|
339 | else: | |
350 | self.input_hist_raw.append('%s\n' % line) |
|
340 | self.input_hist_raw.append('%s\n' % line) | |
351 | # only entries starting at first column go to shadow history |
|
|||
352 | if line.lstrip() == line: |
|
|||
353 | self.shadowhist.add(line.strip()) |
|
|||
354 | elif not continue_prompt: |
|
341 | elif not continue_prompt: | |
355 | self.input_hist_raw.append('\n') |
|
342 | self.input_hist_raw.append('\n') | |
356 | try: |
|
343 | try: | |
357 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
344 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
358 | except: |
|
345 | except: | |
359 | # blanket except, in case a user-defined prefilter crashes, so it |
|
346 | # blanket except, in case a user-defined prefilter crashes, so it | |
360 | # can't take all of ipython with it. |
|
347 | # can't take all of ipython with it. | |
361 | self.showtraceback() |
|
348 | self.showtraceback() | |
362 | return '' |
|
349 | return '' | |
363 | else: |
|
350 | else: | |
364 | return lineout |
|
351 | return lineout | |
365 |
|
352 | |||
366 | # TODO: The following three methods are an early attempt to refactor |
|
353 | ||
367 | # the main code execution logic. We don't use them, but they may be |
|
354 | def raw_input(self, prompt=''): | |
368 | # helpful when we refactor the code execution logic further. |
|
355 | """Write a prompt and read a line. | |
369 | # def interact_prompt(self): |
|
356 | ||
370 | # """ Print the prompt (in read-eval-print loop) |
|
357 | The returned line does not include the trailing newline. | |
371 | # |
|
358 | When the user enters the EOF key sequence, EOFError is raised. | |
372 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
359 | ||
373 | # used in standard IPython flow. |
|
360 | Optional inputs: | |
374 | # """ |
|
361 | ||
375 | # if self.more: |
|
362 | - prompt(''): a string to be printed to prompt the user. | |
376 | # try: |
|
363 | ||
377 | # prompt = self.hooks.generate_prompt(True) |
|
364 | - continue_prompt(False): whether this line is the first one or a | |
378 | # except: |
|
365 | continuation in a sequence of inputs. | |
379 | # self.showtraceback() |
|
366 | """ | |
380 | # if self.autoindent: |
|
367 | # Code run by the user may have modified the readline completer state. | |
381 | # self.rl_do_indent = True |
|
368 | # We must ensure that our completer is back in place. | |
382 | # |
|
369 | ||
383 | # else: |
|
370 | if self.has_readline: | |
384 | # try: |
|
371 | self.set_readline_completer() | |
385 | # prompt = self.hooks.generate_prompt(False) |
|
372 | ||
386 |
|
|
373 | try: | |
387 | # self.showtraceback() |
|
374 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
388 | # self.write(prompt) |
|
375 | except ValueError: | |
389 | # |
|
376 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
390 | # def interact_handle_input(self,line): |
|
377 | " or sys.stdout.close()!\nExiting IPython!") | |
391 | # """ Handle the input line (in read-eval-print loop) |
|
378 | self.ask_exit() | |
392 | # |
|
379 | return "" | |
393 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
380 | ||
394 | # used in standard IPython flow. |
|
381 | # Try to be reasonably smart about not re-indenting pasted input more | |
395 | # """ |
|
382 | # than necessary. We do this by trimming out the auto-indent initial | |
396 | # if line.lstrip() == line: |
|
383 | # spaces, if the user's actual input started itself with whitespace. | |
397 | # self.shadowhist.add(line.strip()) |
|
384 | if self.autoindent: | |
398 | # lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
385 | if num_ini_spaces(line) > self.indent_current_nsp: | |
399 | # |
|
386 | line = line[self.indent_current_nsp:] | |
400 | # if line.strip(): |
|
387 | self.indent_current_nsp = 0 | |
401 | # if self.more: |
|
388 | ||
402 | # self.input_hist_raw[-1] += '%s\n' % line |
|
389 | return line | |
403 | # else: |
|
|||
404 | # self.input_hist_raw.append('%s\n' % line) |
|
|||
405 | # |
|
|||
406 | # |
|
|||
407 | # self.more = self.push_line(lineout) |
|
|||
408 | # if (self.SyntaxTB.last_syntax_error and |
|
|||
409 | # self.autoedit_syntax): |
|
|||
410 | # self.edit_syntax_error() |
|
|||
411 | # |
|
|||
412 | # def interact_with_readline(self): |
|
|||
413 | # """ Demo of using interact_handle_input, interact_prompt |
|
|||
414 | # |
|
|||
415 | # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
|||
416 | # it should work like this. |
|
|||
417 | # """ |
|
|||
418 | # self.readline_startup_hook(self.pre_readline) |
|
|||
419 | # while not self.exit_now: |
|
|||
420 | # self.interact_prompt() |
|
|||
421 | # if self.more: |
|
|||
422 | # self.rl_do_indent = True |
|
|||
423 | # else: |
|
|||
424 | # self.rl_do_indent = False |
|
|||
425 | # line = raw_input_original().decode(self.stdin_encoding) |
|
|||
426 | # self.interact_handle_input(line) |
|
|||
427 |
|
390 | |||
428 | #------------------------------------------------------------------------- |
|
391 | #------------------------------------------------------------------------- | |
429 | # Methods to support auto-editing of SyntaxErrors. |
|
392 | # Methods to support auto-editing of SyntaxErrors. | |
430 | #------------------------------------------------------------------------- |
|
393 | #------------------------------------------------------------------------- | |
431 |
|
394 | |||
432 | def edit_syntax_error(self): |
|
395 | def edit_syntax_error(self): | |
433 | """The bottom half of the syntax error handler called in the main loop. |
|
396 | """The bottom half of the syntax error handler called in the main loop. | |
434 |
|
397 | |||
435 | Loop until syntax error is fixed or user cancels. |
|
398 | Loop until syntax error is fixed or user cancels. | |
436 | """ |
|
399 | """ | |
437 |
|
400 | |||
438 | while self.SyntaxTB.last_syntax_error: |
|
401 | while self.SyntaxTB.last_syntax_error: | |
439 | # copy and clear last_syntax_error |
|
402 | # copy and clear last_syntax_error | |
440 | err = self.SyntaxTB.clear_err_state() |
|
403 | err = self.SyntaxTB.clear_err_state() | |
441 | if not self._should_recompile(err): |
|
404 | if not self._should_recompile(err): | |
442 | return |
|
405 | return | |
443 | try: |
|
406 | try: | |
444 | # may set last_syntax_error again if a SyntaxError is raised |
|
407 | # may set last_syntax_error again if a SyntaxError is raised | |
445 | self.safe_execfile(err.filename,self.user_ns) |
|
408 | self.safe_execfile(err.filename,self.user_ns) | |
446 | except: |
|
409 | except: | |
447 | self.showtraceback() |
|
410 | self.showtraceback() | |
448 | else: |
|
411 | else: | |
449 | try: |
|
412 | try: | |
450 | f = file(err.filename) |
|
413 | f = file(err.filename) | |
451 | try: |
|
414 | try: | |
452 | # This should be inside a display_trap block and I |
|
415 | # This should be inside a display_trap block and I | |
453 | # think it is. |
|
416 | # think it is. | |
454 | sys.displayhook(f.read()) |
|
417 | sys.displayhook(f.read()) | |
455 | finally: |
|
418 | finally: | |
456 | f.close() |
|
419 | f.close() | |
457 | except: |
|
420 | except: | |
458 | self.showtraceback() |
|
421 | self.showtraceback() | |
459 |
|
422 | |||
460 | def _should_recompile(self,e): |
|
423 | def _should_recompile(self,e): | |
461 | """Utility routine for edit_syntax_error""" |
|
424 | """Utility routine for edit_syntax_error""" | |
462 |
|
425 | |||
463 | if e.filename in ('<ipython console>','<input>','<string>', |
|
426 | if e.filename in ('<ipython console>','<input>','<string>', | |
464 | '<console>','<BackgroundJob compilation>', |
|
427 | '<console>','<BackgroundJob compilation>', | |
465 | None): |
|
428 | None): | |
466 |
|
429 | |||
467 | return False |
|
430 | return False | |
468 | try: |
|
431 | try: | |
469 | if (self.autoedit_syntax and |
|
432 | if (self.autoedit_syntax and | |
470 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
433 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
471 | '[Y/n] ','y')): |
|
434 | '[Y/n] ','y')): | |
472 | return False |
|
435 | return False | |
473 | except EOFError: |
|
436 | except EOFError: | |
474 | return False |
|
437 | return False | |
475 |
|
438 | |||
476 | def int0(x): |
|
439 | def int0(x): | |
477 | try: |
|
440 | try: | |
478 | return int(x) |
|
441 | return int(x) | |
479 | except TypeError: |
|
442 | except TypeError: | |
480 | return 0 |
|
443 | return 0 | |
481 | # always pass integer line and offset values to editor hook |
|
444 | # always pass integer line and offset values to editor hook | |
482 | try: |
|
445 | try: | |
483 | self.hooks.fix_error_editor(e.filename, |
|
446 | self.hooks.fix_error_editor(e.filename, | |
484 | int0(e.lineno),int0(e.offset),e.msg) |
|
447 | int0(e.lineno),int0(e.offset),e.msg) | |
485 | except TryNext: |
|
448 | except TryNext: | |
486 | warn('Could not open editor') |
|
449 | warn('Could not open editor') | |
487 | return False |
|
450 | return False | |
488 | return True |
|
451 | return True | |
489 |
|
452 | |||
490 | #------------------------------------------------------------------------- |
|
453 | #------------------------------------------------------------------------- | |
491 | # Things related to GUI support and pylab |
|
454 | # Things related to GUI support and pylab | |
492 | #------------------------------------------------------------------------- |
|
455 | #------------------------------------------------------------------------- | |
493 |
|
456 | |||
494 | def enable_pylab(self, gui=None): |
|
457 | def enable_pylab(self, gui=None): | |
495 | """Activate pylab support at runtime. |
|
458 | """Activate pylab support at runtime. | |
496 |
|
459 | |||
497 | This turns on support for matplotlib, preloads into the interactive |
|
460 | This turns on support for matplotlib, preloads into the interactive | |
498 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
461 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
499 | interact with the GUI event loop. The GUI backend to be used can be |
|
462 | interact with the GUI event loop. The GUI backend to be used can be | |
500 | optionally selected with the optional :param:`gui` argument. |
|
463 | optionally selected with the optional :param:`gui` argument. | |
501 |
|
464 | |||
502 | Parameters |
|
465 | Parameters | |
503 | ---------- |
|
466 | ---------- | |
504 | gui : optional, string |
|
467 | gui : optional, string | |
505 |
|
468 | |||
506 | If given, dictates the choice of matplotlib GUI backend to use |
|
469 | If given, dictates the choice of matplotlib GUI backend to use | |
507 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
470 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
508 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
471 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
509 | dictated by the matplotlib build-time options plus the user's |
|
472 | dictated by the matplotlib build-time options plus the user's | |
510 | matplotlibrc configuration file). |
|
473 | matplotlibrc configuration file). | |
511 | """ |
|
474 | """ | |
512 | # We want to prevent the loading of pylab to pollute the user's |
|
475 | # We want to prevent the loading of pylab to pollute the user's | |
513 | # namespace as shown by the %who* magics, so we execute the activation |
|
476 | # namespace as shown by the %who* magics, so we execute the activation | |
514 | # code in an empty namespace, and we update *both* user_ns and |
|
477 | # code in an empty namespace, and we update *both* user_ns and | |
515 | # user_ns_hidden with this information. |
|
478 | # user_ns_hidden with this information. | |
516 | ns = {} |
|
479 | ns = {} | |
517 | gui = pylab_activate(ns, gui) |
|
480 | gui = pylab_activate(ns, gui) | |
518 | self.user_ns.update(ns) |
|
481 | self.user_ns.update(ns) | |
519 | self.user_ns_hidden.update(ns) |
|
482 | self.user_ns_hidden.update(ns) | |
520 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
483 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
521 | # plot updates into account |
|
484 | # plot updates into account | |
522 | enable_gui(gui) |
|
485 | enable_gui(gui) | |
523 | self.magic_run = self._pylab_magic_run |
|
486 | self.magic_run = self._pylab_magic_run | |
524 |
|
487 | |||
525 | #------------------------------------------------------------------------- |
|
488 | #------------------------------------------------------------------------- | |
526 | # Things related to exiting |
|
489 | # Things related to exiting | |
527 | #------------------------------------------------------------------------- |
|
490 | #------------------------------------------------------------------------- | |
528 |
|
491 | |||
529 | def ask_exit(self): |
|
492 | def ask_exit(self): | |
530 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
493 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
531 | self.exit_now = True |
|
494 | self.exit_now = True | |
532 |
|
495 | |||
533 | def exit(self): |
|
496 | def exit(self): | |
534 | """Handle interactive exit. |
|
497 | """Handle interactive exit. | |
535 |
|
498 | |||
536 | This method calls the ask_exit callback.""" |
|
499 | This method calls the ask_exit callback.""" | |
537 | if self.confirm_exit: |
|
500 | if self.confirm_exit: | |
538 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
501 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
539 | self.ask_exit() |
|
502 | self.ask_exit() | |
540 | else: |
|
503 | else: | |
541 | self.ask_exit() |
|
504 | self.ask_exit() | |
542 |
|
505 | |||
543 | #------------------------------------------------------------------------ |
|
506 | #------------------------------------------------------------------------ | |
544 | # Magic overrides |
|
507 | # Magic overrides | |
545 | #------------------------------------------------------------------------ |
|
508 | #------------------------------------------------------------------------ | |
546 | # Once the base class stops inheriting from magic, this code needs to be |
|
509 | # Once the base class stops inheriting from magic, this code needs to be | |
547 | # moved into a separate machinery as well. For now, at least isolate here |
|
510 | # moved into a separate machinery as well. For now, at least isolate here | |
548 | # the magics which this class needs to implement differently from the base |
|
511 | # the magics which this class needs to implement differently from the base | |
549 | # class, or that are unique to it. |
|
512 | # class, or that are unique to it. | |
550 |
|
513 | |||
551 | def magic_autoindent(self, parameter_s = ''): |
|
514 | def magic_autoindent(self, parameter_s = ''): | |
552 | """Toggle autoindent on/off (if available).""" |
|
515 | """Toggle autoindent on/off (if available).""" | |
553 |
|
516 | |||
554 | self.shell.set_autoindent() |
|
517 | self.shell.set_autoindent() | |
555 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
518 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
556 |
|
519 | |||
557 | def magic_cpaste(self, parameter_s=''): |
|
520 | def magic_cpaste(self, parameter_s=''): | |
558 | """Paste & execute a pre-formatted code block from clipboard. |
|
521 | """Paste & execute a pre-formatted code block from clipboard. | |
559 |
|
522 | |||
560 | You must terminate the block with '--' (two minus-signs) alone on the |
|
523 | You must terminate the block with '--' (two minus-signs) alone on the | |
561 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
524 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
562 | is the new sentinel for this operation) |
|
525 | is the new sentinel for this operation) | |
563 |
|
526 | |||
564 | The block is dedented prior to execution to enable execution of method |
|
527 | The block is dedented prior to execution to enable execution of method | |
565 | definitions. '>' and '+' characters at the beginning of a line are |
|
528 | definitions. '>' and '+' characters at the beginning of a line are | |
566 | ignored, to allow pasting directly from e-mails, diff files and |
|
529 | ignored, to allow pasting directly from e-mails, diff files and | |
567 | doctests (the '...' continuation prompt is also stripped). The |
|
530 | doctests (the '...' continuation prompt is also stripped). The | |
568 | executed block is also assigned to variable named 'pasted_block' for |
|
531 | executed block is also assigned to variable named 'pasted_block' for | |
569 | later editing with '%edit pasted_block'. |
|
532 | later editing with '%edit pasted_block'. | |
570 |
|
533 | |||
571 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
534 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
572 | This assigns the pasted block to variable 'foo' as string, without |
|
535 | This assigns the pasted block to variable 'foo' as string, without | |
573 | dedenting or executing it (preceding >>> and + is still stripped) |
|
536 | dedenting or executing it (preceding >>> and + is still stripped) | |
574 |
|
537 | |||
575 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
538 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
576 |
|
539 | |||
577 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
540 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
578 | Just press enter and type -- (and press enter again) and the block |
|
541 | Just press enter and type -- (and press enter again) and the block | |
579 | will be what was just pasted. |
|
542 | will be what was just pasted. | |
580 |
|
543 | |||
581 | IPython statements (magics, shell escapes) are not supported (yet). |
|
544 | IPython statements (magics, shell escapes) are not supported (yet). | |
582 |
|
545 | |||
583 | See also |
|
546 | See also | |
584 | -------- |
|
547 | -------- | |
585 | paste: automatically pull code from clipboard. |
|
548 | paste: automatically pull code from clipboard. | |
586 | """ |
|
549 | """ | |
587 |
|
550 | |||
588 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
551 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
589 | par = args.strip() |
|
552 | par = args.strip() | |
590 | if opts.has_key('r'): |
|
553 | if opts.has_key('r'): | |
591 | self._rerun_pasted() |
|
554 | self._rerun_pasted() | |
592 | return |
|
555 | return | |
593 |
|
556 | |||
594 | sentinel = opts.get('s','--') |
|
557 | sentinel = opts.get('s','--') | |
595 |
|
558 | |||
596 | block = self._strip_pasted_lines_for_code( |
|
559 | block = self._strip_pasted_lines_for_code( | |
597 | self._get_pasted_lines(sentinel)) |
|
560 | self._get_pasted_lines(sentinel)) | |
598 |
|
561 | |||
599 | self._execute_block(block, par) |
|
562 | self._execute_block(block, par) | |
600 |
|
563 | |||
601 | def magic_paste(self, parameter_s=''): |
|
564 | def magic_paste(self, parameter_s=''): | |
602 | """Paste & execute a pre-formatted code block from clipboard. |
|
565 | """Paste & execute a pre-formatted code block from clipboard. | |
603 |
|
566 | |||
604 | The text is pulled directly from the clipboard without user |
|
567 | The text is pulled directly from the clipboard without user | |
605 | intervention and printed back on the screen before execution (unless |
|
568 | intervention and printed back on the screen before execution (unless | |
606 | the -q flag is given to force quiet mode). |
|
569 | the -q flag is given to force quiet mode). | |
607 |
|
570 | |||
608 | The block is dedented prior to execution to enable execution of method |
|
571 | The block is dedented prior to execution to enable execution of method | |
609 | definitions. '>' and '+' characters at the beginning of a line are |
|
572 | definitions. '>' and '+' characters at the beginning of a line are | |
610 | ignored, to allow pasting directly from e-mails, diff files and |
|
573 | ignored, to allow pasting directly from e-mails, diff files and | |
611 | doctests (the '...' continuation prompt is also stripped). The |
|
574 | doctests (the '...' continuation prompt is also stripped). The | |
612 | executed block is also assigned to variable named 'pasted_block' for |
|
575 | executed block is also assigned to variable named 'pasted_block' for | |
613 | later editing with '%edit pasted_block'. |
|
576 | later editing with '%edit pasted_block'. | |
614 |
|
577 | |||
615 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
578 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
616 | This assigns the pasted block to variable 'foo' as string, without |
|
579 | This assigns the pasted block to variable 'foo' as string, without | |
617 | dedenting or executing it (preceding >>> and + is still stripped) |
|
580 | dedenting or executing it (preceding >>> and + is still stripped) | |
618 |
|
581 | |||
619 | Options |
|
582 | Options | |
620 | ------- |
|
583 | ------- | |
621 |
|
584 | |||
622 | -r: re-executes the block previously entered by cpaste. |
|
585 | -r: re-executes the block previously entered by cpaste. | |
623 |
|
586 | |||
624 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
587 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
625 |
|
588 | |||
626 | IPython statements (magics, shell escapes) are not supported (yet). |
|
589 | IPython statements (magics, shell escapes) are not supported (yet). | |
627 |
|
590 | |||
628 | See also |
|
591 | See also | |
629 | -------- |
|
592 | -------- | |
630 | cpaste: manually paste code into terminal until you mark its end. |
|
593 | cpaste: manually paste code into terminal until you mark its end. | |
631 | """ |
|
594 | """ | |
632 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
595 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
633 | par = args.strip() |
|
596 | par = args.strip() | |
634 | if opts.has_key('r'): |
|
597 | if opts.has_key('r'): | |
635 | self._rerun_pasted() |
|
598 | self._rerun_pasted() | |
636 | return |
|
599 | return | |
637 |
|
600 | |||
638 | text = self.shell.hooks.clipboard_get() |
|
601 | text = self.shell.hooks.clipboard_get() | |
639 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
602 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
640 |
|
603 | |||
641 | # By default, echo back to terminal unless quiet mode is requested |
|
604 | # By default, echo back to terminal unless quiet mode is requested | |
642 | if not opts.has_key('q'): |
|
605 | if not opts.has_key('q'): | |
643 | write = self.shell.write |
|
606 | write = self.shell.write | |
644 | write(self.shell.pycolorize(block)) |
|
607 | write(self.shell.pycolorize(block)) | |
645 | if not block.endswith('\n'): |
|
608 | if not block.endswith('\n'): | |
646 | write('\n') |
|
609 | write('\n') | |
647 | write("## -- End pasted text --\n") |
|
610 | write("## -- End pasted text --\n") | |
648 |
|
611 | |||
649 | self._execute_block(block, par) |
|
612 | self._execute_block(block, par) | |
650 |
|
613 | |||
651 |
|
614 | |||
652 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
615 | InteractiveShellABC.register(TerminalInteractiveShell) |
@@ -1,665 +1,665 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The :class:`~IPython.core.application.Application` object for the command |
|
4 | The :class:`~IPython.core.application.Application` object for the command | |
5 | line :command:`ipython` program. |
|
5 | line :command:`ipython` program. | |
6 |
|
6 | |||
7 | Authors |
|
7 | Authors | |
8 | ------- |
|
8 | ------- | |
9 |
|
9 | |||
10 | * Brian Granger |
|
10 | * Brian Granger | |
11 | * Fernando Perez |
|
11 | * Fernando Perez | |
12 | """ |
|
12 | """ | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Copyright (C) 2008-2010 The IPython Development Team |
|
15 | # Copyright (C) 2008-2010 The IPython Development Team | |
16 | # |
|
16 | # | |
17 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Imports |
|
22 | # Imports | |
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 |
|
24 | |||
25 | from __future__ import absolute_import |
|
25 | from __future__ import absolute_import | |
26 |
|
26 | |||
27 | import logging |
|
27 | import logging | |
28 | import os |
|
28 | import os | |
29 | import sys |
|
29 | import sys | |
30 |
|
30 | |||
31 | from IPython.core import release |
|
31 | from IPython.core import release | |
32 | from IPython.core.crashhandler import CrashHandler |
|
32 | from IPython.core.crashhandler import CrashHandler | |
33 | from IPython.core.application import Application, BaseAppConfigLoader |
|
33 | from IPython.core.application import Application, BaseAppConfigLoader | |
34 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell |
|
34 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell | |
35 | from IPython.config.loader import ( |
|
35 | from IPython.config.loader import ( | |
36 | Config, |
|
36 | Config, | |
37 | PyFileConfigLoader |
|
37 | PyFileConfigLoader | |
38 | ) |
|
38 | ) | |
39 | from IPython.lib import inputhook |
|
39 | from IPython.lib import inputhook | |
40 | from IPython.utils.path import filefind, get_ipython_dir |
|
40 | from IPython.utils.path import filefind, get_ipython_dir | |
41 | from IPython.core import usage |
|
41 | from IPython.core import usage | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Globals, utilities and helpers |
|
44 | # Globals, utilities and helpers | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | #: The default config file name for this application. |
|
47 | #: The default config file name for this application. | |
48 | default_config_file_name = u'ipython_config.py' |
|
48 | default_config_file_name = u'ipython_config.py' | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | class IPAppConfigLoader(BaseAppConfigLoader): |
|
51 | class IPAppConfigLoader(BaseAppConfigLoader): | |
52 |
|
52 | |||
53 | def _add_arguments(self): |
|
53 | def _add_arguments(self): | |
54 | super(IPAppConfigLoader, self)._add_arguments() |
|
54 | super(IPAppConfigLoader, self)._add_arguments() | |
55 | paa = self.parser.add_argument |
|
55 | paa = self.parser.add_argument | |
56 | paa('-p', |
|
56 | paa('-p', | |
57 | '--profile', dest='Global.profile', type=unicode, |
|
57 | '--profile', dest='Global.profile', type=unicode, | |
58 | help= |
|
58 | help= | |
59 | """The string name of the ipython profile to be used. Assume that your |
|
59 | """The string name of the ipython profile to be used. Assume that your | |
60 | config file is ipython_config-<name>.py (looks in current dir first, |
|
60 | config file is ipython_config-<name>.py (looks in current dir first, | |
61 | then in IPYTHON_DIR). This is a quick way to keep and load multiple |
|
61 | then in IPYTHON_DIR). This is a quick way to keep and load multiple | |
62 | config files for different tasks, especially if include your basic one |
|
62 | config files for different tasks, especially if include your basic one | |
63 | in your more specialized ones. You can keep a basic |
|
63 | in your more specialized ones. You can keep a basic | |
64 | IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which |
|
64 | IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which | |
65 | include this one and load extra things for particular tasks.""", |
|
65 | include this one and load extra things for particular tasks.""", | |
66 | metavar='Global.profile') |
|
66 | metavar='Global.profile') | |
67 | paa('--config-file', |
|
67 | paa('--config-file', | |
68 | dest='Global.config_file', type=unicode, |
|
68 | dest='Global.config_file', type=unicode, | |
69 | help= |
|
69 | help= | |
70 | """Set the config file name to override default. Normally IPython |
|
70 | """Set the config file name to override default. Normally IPython | |
71 | loads ipython_config.py (from current directory) or |
|
71 | loads ipython_config.py (from current directory) or | |
72 | IPYTHON_DIR/ipython_config.py. If the loading of your config file |
|
72 | IPYTHON_DIR/ipython_config.py. If the loading of your config file | |
73 | fails, IPython starts with a bare bones configuration (no modules |
|
73 | fails, IPython starts with a bare bones configuration (no modules | |
74 | loaded at all).""", |
|
74 | loaded at all).""", | |
75 | metavar='Global.config_file') |
|
75 | metavar='Global.config_file') | |
76 | paa('--autocall', |
|
76 | paa('--autocall', | |
77 | dest='InteractiveShell.autocall', type=int, |
|
77 | dest='InteractiveShell.autocall', type=int, | |
78 | help= |
|
78 | help= | |
79 | """Make IPython automatically call any callable object even if you |
|
79 | """Make IPython automatically call any callable object even if you | |
80 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
80 | didn't type explicit parentheses. For example, 'str 43' becomes | |
81 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
81 | 'str(43)' automatically. The value can be '0' to disable the feature, | |
82 | '1' for 'smart' autocall, where it is not applied if there are no more |
|
82 | '1' for 'smart' autocall, where it is not applied if there are no more | |
83 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
83 | arguments on the line, and '2' for 'full' autocall, where all callable | |
84 | objects are automatically called (even if no arguments are present). |
|
84 | objects are automatically called (even if no arguments are present). | |
85 | The default is '1'.""", |
|
85 | The default is '1'.""", | |
86 | metavar='InteractiveShell.autocall') |
|
86 | metavar='InteractiveShell.autocall') | |
87 | paa('--autoindent', |
|
87 | paa('--autoindent', | |
88 | action='store_true', dest='InteractiveShell.autoindent', |
|
88 | action='store_true', dest='InteractiveShell.autoindent', | |
89 | help='Turn on autoindenting.') |
|
89 | help='Turn on autoindenting.') | |
90 | paa('--no-autoindent', |
|
90 | paa('--no-autoindent', | |
91 | action='store_false', dest='InteractiveShell.autoindent', |
|
91 | action='store_false', dest='InteractiveShell.autoindent', | |
92 | help='Turn off autoindenting.') |
|
92 | help='Turn off autoindenting.') | |
93 | paa('--automagic', |
|
93 | paa('--automagic', | |
94 | action='store_true', dest='InteractiveShell.automagic', |
|
94 | action='store_true', dest='InteractiveShell.automagic', | |
95 | help= |
|
95 | help= | |
96 | """Turn on the auto calling of magic commands. Type %%magic at the |
|
96 | """Turn on the auto calling of magic commands. Type %%magic at the | |
97 | IPython prompt for more information.""") |
|
97 | IPython prompt for more information.""") | |
98 | paa('--no-automagic', |
|
98 | paa('--no-automagic', | |
99 | action='store_false', dest='InteractiveShell.automagic', |
|
99 | action='store_false', dest='InteractiveShell.automagic', | |
100 | help='Turn off the auto calling of magic commands.') |
|
100 | help='Turn off the auto calling of magic commands.') | |
101 | paa('--autoedit-syntax', |
|
101 | paa('--autoedit-syntax', | |
102 | action='store_true', dest='TerminalInteractiveShell.autoedit_syntax', |
|
102 | action='store_true', dest='TerminalInteractiveShell.autoedit_syntax', | |
103 | help='Turn on auto editing of files with syntax errors.') |
|
103 | help='Turn on auto editing of files with syntax errors.') | |
104 | paa('--no-autoedit-syntax', |
|
104 | paa('--no-autoedit-syntax', | |
105 | action='store_false', dest='TerminalInteractiveShell.autoedit_syntax', |
|
105 | action='store_false', dest='TerminalInteractiveShell.autoedit_syntax', | |
106 | help='Turn off auto editing of files with syntax errors.') |
|
106 | help='Turn off auto editing of files with syntax errors.') | |
107 | paa('--banner', |
|
107 | paa('--banner', | |
108 | action='store_true', dest='Global.display_banner', |
|
108 | action='store_true', dest='Global.display_banner', | |
109 | help='Display a banner upon starting IPython.') |
|
109 | help='Display a banner upon starting IPython.') | |
110 | paa('--no-banner', |
|
110 | paa('--no-banner', | |
111 | action='store_false', dest='Global.display_banner', |
|
111 | action='store_false', dest='Global.display_banner', | |
112 | help="Don't display a banner upon starting IPython.") |
|
112 | help="Don't display a banner upon starting IPython.") | |
113 | paa('--cache-size', |
|
113 | paa('--cache-size', | |
114 | type=int, dest='InteractiveShell.cache_size', |
|
114 | type=int, dest='InteractiveShell.cache_size', | |
115 | help= |
|
115 | help= | |
116 | """Set the size of the output cache. The default is 1000, you can |
|
116 | """Set the size of the output cache. The default is 1000, you can | |
117 | change it permanently in your config file. Setting it to 0 completely |
|
117 | change it permanently in your config file. Setting it to 0 completely | |
118 | disables the caching system, and the minimum value accepted is 20 (if |
|
118 | disables the caching system, and the minimum value accepted is 20 (if | |
119 | you provide a value less than 20, it is reset to 0 and a warning is |
|
119 | you provide a value less than 20, it is reset to 0 and a warning is | |
120 | issued). This limit is defined because otherwise you'll spend more |
|
120 | issued). This limit is defined because otherwise you'll spend more | |
121 | time re-flushing a too small cache than working""", |
|
121 | time re-flushing a too small cache than working""", | |
122 | metavar='InteractiveShell.cache_size') |
|
122 | metavar='InteractiveShell.cache_size') | |
123 | paa('--classic', |
|
123 | paa('--classic', | |
124 | action='store_true', dest='Global.classic', |
|
124 | action='store_true', dest='Global.classic', | |
125 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
125 | help="Gives IPython a similar feel to the classic Python prompt.") | |
126 | paa('--colors', |
|
126 | paa('--colors', | |
127 | type=str, dest='InteractiveShell.colors', |
|
127 | type=str, dest='InteractiveShell.colors', | |
128 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
128 | help="Set the color scheme (NoColor, Linux, and LightBG).", | |
129 | metavar='InteractiveShell.colors') |
|
129 | metavar='InteractiveShell.colors') | |
130 | paa('--color-info', |
|
130 | paa('--color-info', | |
131 | action='store_true', dest='InteractiveShell.color_info', |
|
131 | action='store_true', dest='InteractiveShell.color_info', | |
132 | help= |
|
132 | help= | |
133 | """IPython can display information about objects via a set of func- |
|
133 | """IPython can display information about objects via a set of func- | |
134 | tions, and optionally can use colors for this, syntax highlighting |
|
134 | tions, and optionally can use colors for this, syntax highlighting | |
135 | source code and various other elements. However, because this |
|
135 | source code and various other elements. However, because this | |
136 | information is passed through a pager (like 'less') and many pagers get |
|
136 | information is passed through a pager (like 'less') and many pagers get | |
137 | confused with color codes, this option is off by default. You can test |
|
137 | confused with color codes, this option is off by default. You can test | |
138 | it and turn it on permanently in your ipython_config.py file if it |
|
138 | it and turn it on permanently in your ipython_config.py file if it | |
139 | works for you. Test it and turn it on permanently if it works with |
|
139 | works for you. Test it and turn it on permanently if it works with | |
140 | your system. The magic function %%color_info allows you to toggle this |
|
140 | your system. The magic function %%color_info allows you to toggle this | |
141 | inter- actively for testing.""") |
|
141 | inter- actively for testing.""") | |
142 | paa('--no-color-info', |
|
142 | paa('--no-color-info', | |
143 | action='store_false', dest='InteractiveShell.color_info', |
|
143 | action='store_false', dest='InteractiveShell.color_info', | |
144 | help="Disable using colors for info related things.") |
|
144 | help="Disable using colors for info related things.") | |
145 | paa('--confirm-exit', |
|
145 | paa('--confirm-exit', | |
146 | action='store_true', dest='TerminalInteractiveShell.confirm_exit', |
|
146 | action='store_true', dest='TerminalInteractiveShell.confirm_exit', | |
147 | help= |
|
147 | help= | |
148 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
148 | """Set to confirm when you try to exit IPython with an EOF (Control-D | |
149 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or |
|
149 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or | |
150 | '%%Exit', you can force a direct exit without any confirmation.""") |
|
150 | '%%Exit', you can force a direct exit without any confirmation.""") | |
151 | paa('--no-confirm-exit', |
|
151 | paa('--no-confirm-exit', | |
152 | action='store_false', dest='TerminalInteractiveShell.confirm_exit', |
|
152 | action='store_false', dest='TerminalInteractiveShell.confirm_exit', | |
153 | help="Don't prompt the user when exiting.") |
|
153 | help="Don't prompt the user when exiting.") | |
154 | paa('--deep-reload', |
|
154 | paa('--deep-reload', | |
155 | action='store_true', dest='InteractiveShell.deep_reload', |
|
155 | action='store_true', dest='InteractiveShell.deep_reload', | |
156 | help= |
|
156 | help= | |
157 | """Enable deep (recursive) reloading by default. IPython can use the |
|
157 | """Enable deep (recursive) reloading by default. IPython can use the | |
158 | deep_reload module which reloads changes in modules recursively (it |
|
158 | deep_reload module which reloads changes in modules recursively (it | |
159 | replaces the reload() function, so you don't need to change anything to |
|
159 | replaces the reload() function, so you don't need to change anything to | |
160 | use it). deep_reload() forces a full reload of modules whose code may |
|
160 | use it). deep_reload() forces a full reload of modules whose code may | |
161 | have changed, which the default reload() function does not. When |
|
161 | have changed, which the default reload() function does not. When | |
162 | deep_reload is off, IPython will use the normal reload(), but |
|
162 | deep_reload is off, IPython will use the normal reload(), but | |
163 | deep_reload will still be available as dreload(). This fea- ture is off |
|
163 | deep_reload will still be available as dreload(). This fea- ture is off | |
164 | by default [which means that you have both normal reload() and |
|
164 | by default [which means that you have both normal reload() and | |
165 | dreload()].""") |
|
165 | dreload()].""") | |
166 | paa('--no-deep-reload', |
|
166 | paa('--no-deep-reload', | |
167 | action='store_false', dest='InteractiveShell.deep_reload', |
|
167 | action='store_false', dest='InteractiveShell.deep_reload', | |
168 | help="Disable deep (recursive) reloading by default.") |
|
168 | help="Disable deep (recursive) reloading by default.") | |
169 | paa('--editor', |
|
169 | paa('--editor', | |
170 | type=str, dest='TerminalInteractiveShell.editor', |
|
170 | type=str, dest='TerminalInteractiveShell.editor', | |
171 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
171 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", | |
172 | metavar='TerminalInteractiveShell.editor') |
|
172 | metavar='TerminalInteractiveShell.editor') | |
173 | paa('--log','-l', |
|
173 | paa('--log','-l', | |
174 | action='store_true', dest='InteractiveShell.logstart', |
|
174 | action='store_true', dest='InteractiveShell.logstart', | |
175 | help="Start logging to the default log file (./ipython_log.py).") |
|
175 | help="Start logging to the default log file (./ipython_log.py).") | |
176 | paa('--logfile','-lf', |
|
176 | paa('--logfile','-lf', | |
177 | type=unicode, dest='InteractiveShell.logfile', |
|
177 | type=unicode, dest='InteractiveShell.logfile', | |
178 | help="Start logging to logfile with this name.", |
|
178 | help="Start logging to logfile with this name.", | |
179 | metavar='InteractiveShell.logfile') |
|
179 | metavar='InteractiveShell.logfile') | |
180 | paa('--log-append','-la', |
|
180 | paa('--log-append','-la', | |
181 | type=unicode, dest='InteractiveShell.logappend', |
|
181 | type=unicode, dest='InteractiveShell.logappend', | |
182 | help="Start logging to the given file in append mode.", |
|
182 | help="Start logging to the given file in append mode.", | |
183 | metavar='InteractiveShell.logfile') |
|
183 | metavar='InteractiveShell.logfile') | |
184 | paa('--pdb', |
|
184 | paa('--pdb', | |
185 | action='store_true', dest='InteractiveShell.pdb', |
|
185 | action='store_true', dest='InteractiveShell.pdb', | |
186 | help="Enable auto calling the pdb debugger after every exception.") |
|
186 | help="Enable auto calling the pdb debugger after every exception.") | |
187 | paa('--no-pdb', |
|
187 | paa('--no-pdb', | |
188 | action='store_false', dest='InteractiveShell.pdb', |
|
188 | action='store_false', dest='InteractiveShell.pdb', | |
189 | help="Disable auto calling the pdb debugger after every exception.") |
|
189 | help="Disable auto calling the pdb debugger after every exception.") | |
190 | paa('--pprint', |
|
190 | paa('--pprint', | |
191 | action='store_true', dest='InteractiveShell.pprint', |
|
191 | action='store_true', dest='InteractiveShell.pprint', | |
192 | help="Enable auto pretty printing of results.") |
|
192 | help="Enable auto pretty printing of results.") | |
193 | paa('--no-pprint', |
|
193 | paa('--no-pprint', | |
194 | action='store_false', dest='InteractiveShell.pprint', |
|
194 | action='store_false', dest='InteractiveShell.pprint', | |
195 | help="Disable auto auto pretty printing of results.") |
|
195 | help="Disable auto auto pretty printing of results.") | |
196 | paa('--prompt-in1','-pi1', |
|
196 | paa('--prompt-in1','-pi1', | |
197 | type=str, dest='InteractiveShell.prompt_in1', |
|
197 | type=str, dest='InteractiveShell.prompt_in1', | |
198 | help= |
|
198 | help= | |
199 | """Set the main input prompt ('In [\#]: '). Note that if you are using |
|
199 | """Set the main input prompt ('In [\#]: '). Note that if you are using | |
200 | numbered prompts, the number is represented with a '\#' in the string. |
|
200 | numbered prompts, the number is represented with a '\#' in the string. | |
201 | Don't forget to quote strings with spaces embedded in them. Most |
|
201 | Don't forget to quote strings with spaces embedded in them. Most | |
202 | bash-like escapes can be used to customize IPython's prompts, as well |
|
202 | bash-like escapes can be used to customize IPython's prompts, as well | |
203 | as a few additional ones which are IPython-spe- cific. All valid |
|
203 | as a few additional ones which are IPython-spe- cific. All valid | |
204 | prompt escapes are described in detail in the Customization section of |
|
204 | prompt escapes are described in detail in the Customization section of | |
205 | the IPython manual.""", |
|
205 | the IPython manual.""", | |
206 | metavar='InteractiveShell.prompt_in1') |
|
206 | metavar='InteractiveShell.prompt_in1') | |
207 | paa('--prompt-in2','-pi2', |
|
207 | paa('--prompt-in2','-pi2', | |
208 | type=str, dest='InteractiveShell.prompt_in2', |
|
208 | type=str, dest='InteractiveShell.prompt_in2', | |
209 | help= |
|
209 | help= | |
210 | """Set the secondary input prompt (' .\D.: '). Similar to the previous |
|
210 | """Set the secondary input prompt (' .\D.: '). Similar to the previous | |
211 | option, but used for the continuation prompts. The special sequence |
|
211 | option, but used for the continuation prompts. The special sequence | |
212 | '\D' is similar to '\#', but with all digits replaced by dots (so you |
|
212 | '\D' is similar to '\#', but with all digits replaced by dots (so you | |
213 | can have your continuation prompt aligned with your input prompt). |
|
213 | can have your continuation prompt aligned with your input prompt). | |
214 | Default: ' .\D.: ' (note three spaces at the start for alignment with |
|
214 | Default: ' .\D.: ' (note three spaces at the start for alignment with | |
215 | 'In [\#]')""", |
|
215 | 'In [\#]')""", | |
216 | metavar='InteractiveShell.prompt_in2') |
|
216 | metavar='InteractiveShell.prompt_in2') | |
217 | paa('--prompt-out','-po', |
|
217 | paa('--prompt-out','-po', | |
218 | type=str, dest='InteractiveShell.prompt_out', |
|
218 | type=str, dest='InteractiveShell.prompt_out', | |
219 | help="Set the output prompt ('Out[\#]:')", |
|
219 | help="Set the output prompt ('Out[\#]:')", | |
220 | metavar='InteractiveShell.prompt_out') |
|
220 | metavar='InteractiveShell.prompt_out') | |
221 | paa('--quick', |
|
221 | paa('--quick', | |
222 | action='store_true', dest='Global.quick', |
|
222 | action='store_true', dest='Global.quick', | |
223 | help="Enable quick startup with no config files.") |
|
223 | help="Enable quick startup with no config files.") | |
224 | paa('--readline', |
|
224 | paa('--readline', | |
225 | action='store_true', dest='InteractiveShell.readline_use', |
|
225 | action='store_true', dest='InteractiveShell.readline_use', | |
226 | help="Enable readline for command line usage.") |
|
226 | help="Enable readline for command line usage.") | |
227 | paa('--no-readline', |
|
227 | paa('--no-readline', | |
228 | action='store_false', dest='InteractiveShell.readline_use', |
|
228 | action='store_false', dest='InteractiveShell.readline_use', | |
229 | help="Disable readline for command line usage.") |
|
229 | help="Disable readline for command line usage.") | |
230 | paa('--screen-length','-sl', |
|
230 | paa('--screen-length','-sl', | |
231 | type=int, dest='TerminalInteractiveShell.screen_length', |
|
231 | type=int, dest='TerminalInteractiveShell.screen_length', | |
232 | help= |
|
232 | help= | |
233 | """Number of lines of your screen, used to control printing of very |
|
233 | """Number of lines of your screen, used to control printing of very | |
234 | long strings. Strings longer than this number of lines will be sent |
|
234 | long strings. Strings longer than this number of lines will be sent | |
235 | through a pager instead of directly printed. The default value for |
|
235 | through a pager instead of directly printed. The default value for | |
236 | this is 0, which means IPython will auto-detect your screen size every |
|
236 | this is 0, which means IPython will auto-detect your screen size every | |
237 | time it needs to print certain potentially long strings (this doesn't |
|
237 | time it needs to print certain potentially long strings (this doesn't | |
238 | change the behavior of the 'print' keyword, it's only triggered |
|
238 | change the behavior of the 'print' keyword, it's only triggered | |
239 | internally). If for some reason this isn't working well (it needs |
|
239 | internally). If for some reason this isn't working well (it needs | |
240 | curses support), specify it yourself. Otherwise don't change the |
|
240 | curses support), specify it yourself. Otherwise don't change the | |
241 | default.""", |
|
241 | default.""", | |
242 | metavar='TerminalInteractiveShell.screen_length') |
|
242 | metavar='TerminalInteractiveShell.screen_length') | |
243 | paa('--separate-in','-si', |
|
243 | paa('--separate-in','-si', | |
244 | type=str, dest='InteractiveShell.separate_in', |
|
244 | type=str, dest='InteractiveShell.separate_in', | |
245 | help="Separator before input prompts. Default '\\n'.", |
|
245 | help="Separator before input prompts. Default '\\n'.", | |
246 | metavar='InteractiveShell.separate_in') |
|
246 | metavar='InteractiveShell.separate_in') | |
247 | paa('--separate-out','-so', |
|
247 | paa('--separate-out','-so', | |
248 | type=str, dest='InteractiveShell.separate_out', |
|
248 | type=str, dest='InteractiveShell.separate_out', | |
249 | help="Separator before output prompts. Default 0 (nothing).", |
|
249 | help="Separator before output prompts. Default 0 (nothing).", | |
250 | metavar='InteractiveShell.separate_out') |
|
250 | metavar='InteractiveShell.separate_out') | |
251 | paa('--separate-out2','-so2', |
|
251 | paa('--separate-out2','-so2', | |
252 | type=str, dest='InteractiveShell.separate_out2', |
|
252 | type=str, dest='InteractiveShell.separate_out2', | |
253 | help="Separator after output prompts. Default 0 (nonight).", |
|
253 | help="Separator after output prompts. Default 0 (nonight).", | |
254 | metavar='InteractiveShell.separate_out2') |
|
254 | metavar='InteractiveShell.separate_out2') | |
255 | paa('--no-sep', |
|
255 | paa('--no-sep', | |
256 | action='store_true', dest='Global.nosep', |
|
256 | action='store_true', dest='Global.nosep', | |
257 | help="Eliminate all spacing between prompts.") |
|
257 | help="Eliminate all spacing between prompts.") | |
258 | paa('--term-title', |
|
258 | paa('--term-title', | |
259 | action='store_true', dest='TerminalInteractiveShell.term_title', |
|
259 | action='store_true', dest='TerminalInteractiveShell.term_title', | |
260 | help="Enable auto setting the terminal title.") |
|
260 | help="Enable auto setting the terminal title.") | |
261 | paa('--no-term-title', |
|
261 | paa('--no-term-title', | |
262 | action='store_false', dest='TerminalInteractiveShell.term_title', |
|
262 | action='store_false', dest='TerminalInteractiveShell.term_title', | |
263 | help="Disable auto setting the terminal title.") |
|
263 | help="Disable auto setting the terminal title.") | |
264 | paa('--xmode', |
|
264 | paa('--xmode', | |
265 | type=str, dest='InteractiveShell.xmode', |
|
265 | type=str, dest='InteractiveShell.xmode', | |
266 | help= |
|
266 | help= | |
267 | """Exception reporting mode ('Plain','Context','Verbose'). Plain: |
|
267 | """Exception reporting mode ('Plain','Context','Verbose'). Plain: | |
268 | similar to python's normal traceback printing. Context: prints 5 lines |
|
268 | similar to python's normal traceback printing. Context: prints 5 lines | |
269 | of context source code around each line in the traceback. Verbose: |
|
269 | of context source code around each line in the traceback. Verbose: | |
270 | similar to Context, but additionally prints the variables currently |
|
270 | similar to Context, but additionally prints the variables currently | |
271 | visible where the exception happened (shortening their strings if too |
|
271 | visible where the exception happened (shortening their strings if too | |
272 | long). This can potentially be very slow, if you happen to have a huge |
|
272 | long). This can potentially be very slow, if you happen to have a huge | |
273 | data structure whose string representation is complex to compute. |
|
273 | data structure whose string representation is complex to compute. | |
274 | Your computer may appear to freeze for a while with cpu usage at 100%%. |
|
274 | Your computer may appear to freeze for a while with cpu usage at 100%%. | |
275 | If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting |
|
275 | If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting | |
276 | it more than once). |
|
276 | it more than once). | |
277 | """, |
|
277 | """, | |
278 | metavar='InteractiveShell.xmode') |
|
278 | metavar='InteractiveShell.xmode') | |
279 | paa('--ext', |
|
279 | paa('--ext', | |
280 | type=str, dest='Global.extra_extension', |
|
280 | type=str, dest='Global.extra_extension', | |
281 | help="The dotted module name of an IPython extension to load.", |
|
281 | help="The dotted module name of an IPython extension to load.", | |
282 | metavar='Global.extra_extension') |
|
282 | metavar='Global.extra_extension') | |
283 | paa('-c', |
|
283 | paa('-c', | |
284 | type=str, dest='Global.code_to_run', |
|
284 | type=str, dest='Global.code_to_run', | |
285 | help="Execute the given command string.", |
|
285 | help="Execute the given command string.", | |
286 | metavar='Global.code_to_run') |
|
286 | metavar='Global.code_to_run') | |
287 | paa('-i', |
|
287 | paa('-i', | |
288 | action='store_true', dest='Global.force_interact', |
|
288 | action='store_true', dest='Global.force_interact', | |
289 | help= |
|
289 | help= | |
290 | "If running code from the command line, become interactive afterwards.") |
|
290 | "If running code from the command line, become interactive afterwards.") | |
291 |
|
291 | |||
292 | # Options to start with GUI control enabled from the beginning |
|
292 | # Options to start with GUI control enabled from the beginning | |
293 | paa('--gui', |
|
293 | paa('--gui', | |
294 | type=str, dest='Global.gui', |
|
294 | type=str, dest='Global.gui', | |
295 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk').", |
|
295 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk').", | |
296 | metavar='gui-mode') |
|
296 | metavar='gui-mode') | |
297 | paa('--pylab','-pylab', |
|
297 | paa('--pylab','-pylab', | |
298 | type=str, dest='Global.pylab', |
|
298 | type=str, dest='Global.pylab', | |
299 | nargs='?', const='auto', metavar='gui-mode', |
|
299 | nargs='?', const='auto', metavar='gui-mode', | |
300 | help="Pre-load matplotlib and numpy for interactive use. "+ |
|
300 | help="Pre-load matplotlib and numpy for interactive use. "+ | |
301 | "If no value is given, the gui backend is matplotlib's, else use "+ |
|
301 | "If no value is given, the gui backend is matplotlib's, else use "+ | |
302 | "one of: ['tk', 'qt', 'wx', 'gtk'].") |
|
302 | "one of: ['tk', 'qt', 'wx', 'gtk'].") | |
303 |
|
303 | |||
304 | # Legacy GUI options. Leave them in for backwards compatibility, but the |
|
304 | # Legacy GUI options. Leave them in for backwards compatibility, but the | |
305 | # 'thread' names are really a misnomer now. |
|
305 | # 'thread' names are really a misnomer now. | |
306 | paa('--wthread', '-wthread', |
|
306 | paa('--wthread', '-wthread', | |
307 | action='store_true', dest='Global.wthread', |
|
307 | action='store_true', dest='Global.wthread', | |
308 | help= |
|
308 | help= | |
309 | """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""") |
|
309 | """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""") | |
310 | paa('--q4thread', '--qthread', '-q4thread', '-qthread', |
|
310 | paa('--q4thread', '--qthread', '-q4thread', '-qthread', | |
311 | action='store_true', dest='Global.q4thread', |
|
311 | action='store_true', dest='Global.q4thread', | |
312 | help= |
|
312 | help= | |
313 | """Enable Qt4 event loop integration. Qt3 is no longer supported. |
|
313 | """Enable Qt4 event loop integration. Qt3 is no longer supported. | |
314 | (DEPRECATED, use --gui qt)""") |
|
314 | (DEPRECATED, use --gui qt)""") | |
315 | paa('--gthread', '-gthread', |
|
315 | paa('--gthread', '-gthread', | |
316 | action='store_true', dest='Global.gthread', |
|
316 | action='store_true', dest='Global.gthread', | |
317 | help= |
|
317 | help= | |
318 | """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""") |
|
318 | """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""") | |
319 |
|
319 | |||
320 |
|
320 | |||
321 | #----------------------------------------------------------------------------- |
|
321 | #----------------------------------------------------------------------------- | |
322 | # Crash handler for this application |
|
322 | # Crash handler for this application | |
323 | #----------------------------------------------------------------------------- |
|
323 | #----------------------------------------------------------------------------- | |
324 |
|
324 | |||
325 |
|
325 | |||
326 | _message_template = """\ |
|
326 | _message_template = """\ | |
327 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
327 | Oops, $self.app_name crashed. We do our best to make it stable, but... | |
328 |
|
328 | |||
329 | A crash report was automatically generated with the following information: |
|
329 | A crash report was automatically generated with the following information: | |
330 | - A verbatim copy of the crash traceback. |
|
330 | - A verbatim copy of the crash traceback. | |
331 | - A copy of your input history during this session. |
|
331 | - A copy of your input history during this session. | |
332 | - Data on your current $self.app_name configuration. |
|
332 | - Data on your current $self.app_name configuration. | |
333 |
|
333 | |||
334 | It was left in the file named: |
|
334 | It was left in the file named: | |
335 | \t'$self.crash_report_fname' |
|
335 | \t'$self.crash_report_fname' | |
336 | If you can email this file to the developers, the information in it will help |
|
336 | If you can email this file to the developers, the information in it will help | |
337 | them in understanding and correcting the problem. |
|
337 | them in understanding and correcting the problem. | |
338 |
|
338 | |||
339 | You can mail it to: $self.contact_name at $self.contact_email |
|
339 | You can mail it to: $self.contact_name at $self.contact_email | |
340 | with the subject '$self.app_name Crash Report'. |
|
340 | with the subject '$self.app_name Crash Report'. | |
341 |
|
341 | |||
342 | If you want to do it now, the following command will work (under Unix): |
|
342 | If you want to do it now, the following command will work (under Unix): | |
343 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
343 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname | |
344 |
|
344 | |||
345 | To ensure accurate tracking of this issue, please file a report about it at: |
|
345 | To ensure accurate tracking of this issue, please file a report about it at: | |
346 | $self.bug_tracker |
|
346 | $self.bug_tracker | |
347 | """ |
|
347 | """ | |
348 |
|
348 | |||
349 | class IPAppCrashHandler(CrashHandler): |
|
349 | class IPAppCrashHandler(CrashHandler): | |
350 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
350 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" | |
351 |
|
351 | |||
352 | message_template = _message_template |
|
352 | message_template = _message_template | |
353 |
|
353 | |||
354 | def __init__(self, app): |
|
354 | def __init__(self, app): | |
355 | contact_name = release.authors['Fernando'][0] |
|
355 | contact_name = release.authors['Fernando'][0] | |
356 | contact_email = release.authors['Fernando'][1] |
|
356 | contact_email = release.authors['Fernando'][1] | |
357 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
357 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' | |
358 | super(IPAppCrashHandler,self).__init__( |
|
358 | super(IPAppCrashHandler,self).__init__( | |
359 | app, contact_name, contact_email, bug_tracker |
|
359 | app, contact_name, contact_email, bug_tracker | |
360 | ) |
|
360 | ) | |
361 |
|
361 | |||
362 | def make_report(self,traceback): |
|
362 | def make_report(self,traceback): | |
363 | """Return a string containing a crash report.""" |
|
363 | """Return a string containing a crash report.""" | |
364 |
|
364 | |||
365 | sec_sep = self.section_sep |
|
365 | sec_sep = self.section_sep | |
366 | # Start with parent report |
|
366 | # Start with parent report | |
367 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
367 | report = [super(IPAppCrashHandler, self).make_report(traceback)] | |
368 | # Add interactive-specific info we may have |
|
368 | # Add interactive-specific info we may have | |
369 | rpt_add = report.append |
|
369 | rpt_add = report.append | |
370 | try: |
|
370 | try: | |
371 | rpt_add(sec_sep+"History of session input:") |
|
371 | rpt_add(sec_sep+"History of session input:") | |
372 | for line in self.app.shell.user_ns['_ih']: |
|
372 | for line in self.app.shell.user_ns['_ih']: | |
373 | rpt_add(line) |
|
373 | rpt_add(line) | |
374 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
374 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
375 | rpt_add(self.app.shell._last_input_line+'\n') |
|
375 | rpt_add(self.app.shell._last_input_line+'\n') | |
376 | except: |
|
376 | except: | |
377 | pass |
|
377 | pass | |
378 |
|
378 | |||
379 | return ''.join(report) |
|
379 | return ''.join(report) | |
380 |
|
380 | |||
381 |
|
381 | |||
382 | #----------------------------------------------------------------------------- |
|
382 | #----------------------------------------------------------------------------- | |
383 | # Main classes and functions |
|
383 | # Main classes and functions | |
384 | #----------------------------------------------------------------------------- |
|
384 | #----------------------------------------------------------------------------- | |
385 |
|
385 | |||
386 | class IPythonApp(Application): |
|
386 | class IPythonApp(Application): | |
387 | name = u'ipython' |
|
387 | name = u'ipython' | |
388 | #: argparse formats better the 'usage' than the 'description' field |
|
388 | #: argparse formats better the 'usage' than the 'description' field | |
389 | description = None |
|
389 | description = None | |
390 | usage = usage.cl_usage |
|
390 | usage = usage.cl_usage | |
391 | command_line_loader = IPAppConfigLoader |
|
391 | command_line_loader = IPAppConfigLoader | |
392 | default_config_file_name = default_config_file_name |
|
392 | default_config_file_name = default_config_file_name | |
393 | crash_handler_class = IPAppCrashHandler |
|
393 | crash_handler_class = IPAppCrashHandler | |
394 |
|
394 | |||
395 | def create_default_config(self): |
|
395 | def create_default_config(self): | |
396 | super(IPythonApp, self).create_default_config() |
|
396 | super(IPythonApp, self).create_default_config() | |
397 | # Eliminate multiple lookups |
|
397 | # Eliminate multiple lookups | |
398 | Global = self.default_config.Global |
|
398 | Global = self.default_config.Global | |
399 |
|
399 | |||
400 | # Set all default values |
|
400 | # Set all default values | |
401 | Global.display_banner = True |
|
401 | Global.display_banner = True | |
402 |
|
402 | |||
403 | # If the -c flag is given or a file is given to run at the cmd line |
|
403 | # If the -c flag is given or a file is given to run at the cmd line | |
404 | # like "ipython foo.py", normally we exit without starting the main |
|
404 | # like "ipython foo.py", normally we exit without starting the main | |
405 | # loop. The force_interact config variable allows a user to override |
|
405 | # loop. The force_interact config variable allows a user to override | |
406 | # this and interact. It is also set by the -i cmd line flag, just |
|
406 | # this and interact. It is also set by the -i cmd line flag, just | |
407 | # like Python. |
|
407 | # like Python. | |
408 | Global.force_interact = False |
|
408 | Global.force_interact = False | |
409 |
|
409 | |||
410 | # By default always interact by starting the IPython mainloop. |
|
410 | # By default always interact by starting the IPython mainloop. | |
411 | Global.interact = True |
|
411 | Global.interact = True | |
412 |
|
412 | |||
413 | # No GUI integration by default |
|
413 | # No GUI integration by default | |
414 | Global.gui = False |
|
414 | Global.gui = False | |
415 | # Pylab off by default |
|
415 | # Pylab off by default | |
416 | Global.pylab = False |
|
416 | Global.pylab = False | |
417 |
|
417 | |||
418 | # Deprecated versions of gui support that used threading, we support |
|
418 | # Deprecated versions of gui support that used threading, we support | |
419 | # them just for bacwards compatibility as an alternate spelling for |
|
419 | # them just for bacwards compatibility as an alternate spelling for | |
420 | # '--gui X' |
|
420 | # '--gui X' | |
421 | Global.qthread = False |
|
421 | Global.qthread = False | |
422 | Global.q4thread = False |
|
422 | Global.q4thread = False | |
423 | Global.wthread = False |
|
423 | Global.wthread = False | |
424 | Global.gthread = False |
|
424 | Global.gthread = False | |
425 |
|
425 | |||
426 | def load_file_config(self): |
|
426 | def load_file_config(self): | |
427 | if hasattr(self.command_line_config.Global, 'quick'): |
|
427 | if hasattr(self.command_line_config.Global, 'quick'): | |
428 | if self.command_line_config.Global.quick: |
|
428 | if self.command_line_config.Global.quick: | |
429 | self.file_config = Config() |
|
429 | self.file_config = Config() | |
430 | return |
|
430 | return | |
431 | super(IPythonApp, self).load_file_config() |
|
431 | super(IPythonApp, self).load_file_config() | |
432 |
|
432 | |||
433 | def post_load_file_config(self): |
|
433 | def post_load_file_config(self): | |
434 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
434 | if hasattr(self.command_line_config.Global, 'extra_extension'): | |
435 | if not hasattr(self.file_config.Global, 'extensions'): |
|
435 | if not hasattr(self.file_config.Global, 'extensions'): | |
436 | self.file_config.Global.extensions = [] |
|
436 | self.file_config.Global.extensions = [] | |
437 | self.file_config.Global.extensions.append( |
|
437 | self.file_config.Global.extensions.append( | |
438 | self.command_line_config.Global.extra_extension) |
|
438 | self.command_line_config.Global.extra_extension) | |
439 | del self.command_line_config.Global.extra_extension |
|
439 | del self.command_line_config.Global.extra_extension | |
440 |
|
440 | |||
441 | def pre_construct(self): |
|
441 | def pre_construct(self): | |
442 | config = self.master_config |
|
442 | config = self.master_config | |
443 |
|
443 | |||
444 | if hasattr(config.Global, 'classic'): |
|
444 | if hasattr(config.Global, 'classic'): | |
445 | if config.Global.classic: |
|
445 | if config.Global.classic: | |
446 | config.InteractiveShell.cache_size = 0 |
|
446 | config.InteractiveShell.cache_size = 0 | |
447 | config.InteractiveShell.pprint = 0 |
|
447 | config.InteractiveShell.pprint = 0 | |
448 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
448 | config.InteractiveShell.prompt_in1 = '>>> ' | |
449 | config.InteractiveShell.prompt_in2 = '... ' |
|
449 | config.InteractiveShell.prompt_in2 = '... ' | |
450 | config.InteractiveShell.prompt_out = '' |
|
450 | config.InteractiveShell.prompt_out = '' | |
451 | config.InteractiveShell.separate_in = \ |
|
451 | config.InteractiveShell.separate_in = \ | |
452 | config.InteractiveShell.separate_out = \ |
|
452 | config.InteractiveShell.separate_out = \ | |
453 | config.InteractiveShell.separate_out2 = '' |
|
453 | config.InteractiveShell.separate_out2 = '' | |
454 | config.InteractiveShell.colors = 'NoColor' |
|
454 | config.InteractiveShell.colors = 'NoColor' | |
455 | config.InteractiveShell.xmode = 'Plain' |
|
455 | config.InteractiveShell.xmode = 'Plain' | |
456 |
|
456 | |||
457 | if hasattr(config.Global, 'nosep'): |
|
457 | if hasattr(config.Global, 'nosep'): | |
458 | if config.Global.nosep: |
|
458 | if config.Global.nosep: | |
459 | config.InteractiveShell.separate_in = \ |
|
459 | config.InteractiveShell.separate_in = \ | |
460 | config.InteractiveShell.separate_out = \ |
|
460 | config.InteractiveShell.separate_out = \ | |
461 | config.InteractiveShell.separate_out2 = '' |
|
461 | config.InteractiveShell.separate_out2 = '' | |
462 |
|
462 | |||
463 | # if there is code of files to run from the cmd line, don't interact |
|
463 | # if there is code of files to run from the cmd line, don't interact | |
464 | # unless the -i flag (Global.force_interact) is true. |
|
464 | # unless the -i flag (Global.force_interact) is true. | |
465 | code_to_run = config.Global.get('code_to_run','') |
|
465 | code_to_run = config.Global.get('code_to_run','') | |
466 | file_to_run = False |
|
466 | file_to_run = False | |
467 | if self.extra_args and self.extra_args[0]: |
|
467 | if self.extra_args and self.extra_args[0]: | |
468 | file_to_run = True |
|
468 | file_to_run = True | |
469 | if file_to_run or code_to_run: |
|
469 | if file_to_run or code_to_run: | |
470 | if not config.Global.force_interact: |
|
470 | if not config.Global.force_interact: | |
471 | config.Global.interact = False |
|
471 | config.Global.interact = False | |
472 |
|
472 | |||
473 | def construct(self): |
|
473 | def construct(self): | |
474 | # I am a little hesitant to put these into InteractiveShell itself. |
|
474 | # I am a little hesitant to put these into InteractiveShell itself. | |
475 | # But that might be the place for them |
|
475 | # But that might be the place for them | |
476 | sys.path.insert(0, '') |
|
476 | sys.path.insert(0, '') | |
477 |
|
477 | |||
478 | # Create an InteractiveShell instance. |
|
478 | # Create an InteractiveShell instance. | |
479 | self.shell = TerminalInteractiveShell.instance(config=self.master_config) |
|
479 | self.shell = TerminalInteractiveShell.instance(config=self.master_config) | |
480 |
|
480 | |||
481 | def post_construct(self): |
|
481 | def post_construct(self): | |
482 | """Do actions after construct, but before starting the app.""" |
|
482 | """Do actions after construct, but before starting the app.""" | |
483 | config = self.master_config |
|
483 | config = self.master_config | |
484 |
|
484 | |||
485 | # shell.display_banner should always be False for the terminal |
|
485 | # shell.display_banner should always be False for the terminal | |
486 | # based app, because we call shell.show_banner() by hand below |
|
486 | # based app, because we call shell.show_banner() by hand below | |
487 | # so the banner shows *before* all extension loading stuff. |
|
487 | # so the banner shows *before* all extension loading stuff. | |
488 | self.shell.display_banner = False |
|
488 | self.shell.display_banner = False | |
489 | if config.Global.display_banner and \ |
|
489 | if config.Global.display_banner and \ | |
490 | config.Global.interact: |
|
490 | config.Global.interact: | |
491 | self.shell.show_banner() |
|
491 | self.shell.show_banner() | |
492 |
|
492 | |||
493 | # Make sure there is a space below the banner. |
|
493 | # Make sure there is a space below the banner. | |
494 | if self.log_level <= logging.INFO: print |
|
494 | if self.log_level <= logging.INFO: print | |
495 |
|
495 | |||
496 | # Now a variety of things that happen after the banner is printed. |
|
496 | # Now a variety of things that happen after the banner is printed. | |
497 | self._enable_gui_pylab() |
|
497 | self._enable_gui_pylab() | |
498 | self._load_extensions() |
|
498 | self._load_extensions() | |
499 | self._run_exec_lines() |
|
499 | self._run_exec_lines() | |
500 | self._run_exec_files() |
|
500 | self._run_exec_files() | |
501 | self._run_cmd_line_code() |
|
501 | self._run_cmd_line_code() | |
502 |
|
502 | |||
503 | def _enable_gui_pylab(self): |
|
503 | def _enable_gui_pylab(self): | |
504 | """Enable GUI event loop integration, taking pylab into account.""" |
|
504 | """Enable GUI event loop integration, taking pylab into account.""" | |
505 | Global = self.master_config.Global |
|
505 | Global = self.master_config.Global | |
506 |
|
506 | |||
507 | # Select which gui to use |
|
507 | # Select which gui to use | |
508 | if Global.gui: |
|
508 | if Global.gui: | |
509 | gui = Global.gui |
|
509 | gui = Global.gui | |
510 | # The following are deprecated, but there's likely to be a lot of use |
|
510 | # The following are deprecated, but there's likely to be a lot of use | |
511 | # of this form out there, so we might as well support it for now. But |
|
511 | # of this form out there, so we might as well support it for now. But | |
512 | # the --gui option above takes precedence. |
|
512 | # the --gui option above takes precedence. | |
513 | elif Global.wthread: |
|
513 | elif Global.wthread: | |
514 | gui = inputhook.GUI_WX |
|
514 | gui = inputhook.GUI_WX | |
515 | elif Global.qthread: |
|
515 | elif Global.qthread: | |
516 | gui = inputhook.GUI_QT |
|
516 | gui = inputhook.GUI_QT | |
517 | elif Global.gthread: |
|
517 | elif Global.gthread: | |
518 | gui = inputhook.GUI_GTK |
|
518 | gui = inputhook.GUI_GTK | |
519 | else: |
|
519 | else: | |
520 | gui = None |
|
520 | gui = None | |
521 |
|
521 | |||
522 | # Using --pylab will also require gui activation, though which toolkit |
|
522 | # Using --pylab will also require gui activation, though which toolkit | |
523 | # to use may be chosen automatically based on mpl configuration. |
|
523 | # to use may be chosen automatically based on mpl configuration. | |
524 | if Global.pylab: |
|
524 | if Global.pylab: | |
525 | activate = self.shell.enable_pylab |
|
525 | activate = self.shell.enable_pylab | |
526 | if Global.pylab == 'auto': |
|
526 | if Global.pylab == 'auto': | |
527 | gui = None |
|
527 | gui = None | |
528 | else: |
|
528 | else: | |
529 | gui = Global.pylab |
|
529 | gui = Global.pylab | |
530 | else: |
|
530 | else: | |
531 | # Enable only GUI integration, no pylab |
|
531 | # Enable only GUI integration, no pylab | |
532 | activate = inputhook.enable_gui |
|
532 | activate = inputhook.enable_gui | |
533 |
|
533 | |||
534 | if gui or Global.pylab: |
|
534 | if gui or Global.pylab: | |
535 | try: |
|
535 | try: | |
536 | self.log.info("Enabling GUI event loop integration, " |
|
536 | self.log.info("Enabling GUI event loop integration, " | |
537 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) |
|
537 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) | |
538 | activate(gui) |
|
538 | activate(gui) | |
539 | except: |
|
539 | except: | |
540 | self.log.warn("Error in enabling GUI event loop integration:") |
|
540 | self.log.warn("Error in enabling GUI event loop integration:") | |
541 | self.shell.showtraceback() |
|
541 | self.shell.showtraceback() | |
542 |
|
542 | |||
543 | def _load_extensions(self): |
|
543 | def _load_extensions(self): | |
544 | """Load all IPython extensions in Global.extensions. |
|
544 | """Load all IPython extensions in Global.extensions. | |
545 |
|
545 | |||
546 | This uses the :meth:`ExtensionManager.load_extensions` to load all |
|
546 | This uses the :meth:`ExtensionManager.load_extensions` to load all | |
547 | the extensions listed in ``self.master_config.Global.extensions``. |
|
547 | the extensions listed in ``self.master_config.Global.extensions``. | |
548 | """ |
|
548 | """ | |
549 | try: |
|
549 | try: | |
550 | if hasattr(self.master_config.Global, 'extensions'): |
|
550 | if hasattr(self.master_config.Global, 'extensions'): | |
551 | self.log.debug("Loading IPython extensions...") |
|
551 | self.log.debug("Loading IPython extensions...") | |
552 | extensions = self.master_config.Global.extensions |
|
552 | extensions = self.master_config.Global.extensions | |
553 | for ext in extensions: |
|
553 | for ext in extensions: | |
554 | try: |
|
554 | try: | |
555 | self.log.info("Loading IPython extension: %s" % ext) |
|
555 | self.log.info("Loading IPython extension: %s" % ext) | |
556 | self.shell.extension_manager.load_extension(ext) |
|
556 | self.shell.extension_manager.load_extension(ext) | |
557 | except: |
|
557 | except: | |
558 | self.log.warn("Error in loading extension: %s" % ext) |
|
558 | self.log.warn("Error in loading extension: %s" % ext) | |
559 | self.shell.showtraceback() |
|
559 | self.shell.showtraceback() | |
560 | except: |
|
560 | except: | |
561 | self.log.warn("Unknown error in loading extensions:") |
|
561 | self.log.warn("Unknown error in loading extensions:") | |
562 | self.shell.showtraceback() |
|
562 | self.shell.showtraceback() | |
563 |
|
563 | |||
564 | def _run_exec_lines(self): |
|
564 | def _run_exec_lines(self): | |
565 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
565 | """Run lines of code in Global.exec_lines in the user's namespace.""" | |
566 | try: |
|
566 | try: | |
567 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
567 | if hasattr(self.master_config.Global, 'exec_lines'): | |
568 | self.log.debug("Running code from Global.exec_lines...") |
|
568 | self.log.debug("Running code from Global.exec_lines...") | |
569 | exec_lines = self.master_config.Global.exec_lines |
|
569 | exec_lines = self.master_config.Global.exec_lines | |
570 | for line in exec_lines: |
|
570 | for line in exec_lines: | |
571 | try: |
|
571 | try: | |
572 | self.log.info("Running code in user namespace: %s" % |
|
572 | self.log.info("Running code in user namespace: %s" % | |
573 | line) |
|
573 | line) | |
574 |
self.shell.run |
|
574 | self.shell.run_cell(line) | |
575 | except: |
|
575 | except: | |
576 | self.log.warn("Error in executing line in user " |
|
576 | self.log.warn("Error in executing line in user " | |
577 | "namespace: %s" % line) |
|
577 | "namespace: %s" % line) | |
578 | self.shell.showtraceback() |
|
578 | self.shell.showtraceback() | |
579 | except: |
|
579 | except: | |
580 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
580 | self.log.warn("Unknown error in handling Global.exec_lines:") | |
581 | self.shell.showtraceback() |
|
581 | self.shell.showtraceback() | |
582 |
|
582 | |||
583 | def _exec_file(self, fname): |
|
583 | def _exec_file(self, fname): | |
584 | full_filename = filefind(fname, [u'.', self.ipython_dir]) |
|
584 | full_filename = filefind(fname, [u'.', self.ipython_dir]) | |
585 | if os.path.isfile(full_filename): |
|
585 | if os.path.isfile(full_filename): | |
586 | if full_filename.endswith(u'.py'): |
|
586 | if full_filename.endswith(u'.py'): | |
587 | self.log.info("Running file in user namespace: %s" % |
|
587 | self.log.info("Running file in user namespace: %s" % | |
588 | full_filename) |
|
588 | full_filename) | |
589 | # Ensure that __file__ is always defined to match Python behavior |
|
589 | # Ensure that __file__ is always defined to match Python behavior | |
590 | self.shell.user_ns['__file__'] = fname |
|
590 | self.shell.user_ns['__file__'] = fname | |
591 | try: |
|
591 | try: | |
592 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
592 | self.shell.safe_execfile(full_filename, self.shell.user_ns) | |
593 | finally: |
|
593 | finally: | |
594 | del self.shell.user_ns['__file__'] |
|
594 | del self.shell.user_ns['__file__'] | |
595 | elif full_filename.endswith('.ipy'): |
|
595 | elif full_filename.endswith('.ipy'): | |
596 | self.log.info("Running file in user namespace: %s" % |
|
596 | self.log.info("Running file in user namespace: %s" % | |
597 | full_filename) |
|
597 | full_filename) | |
598 | self.shell.safe_execfile_ipy(full_filename) |
|
598 | self.shell.safe_execfile_ipy(full_filename) | |
599 | else: |
|
599 | else: | |
600 | self.log.warn("File does not have a .py or .ipy extension: <%s>" |
|
600 | self.log.warn("File does not have a .py or .ipy extension: <%s>" | |
601 | % full_filename) |
|
601 | % full_filename) | |
602 | def _run_exec_files(self): |
|
602 | def _run_exec_files(self): | |
603 | try: |
|
603 | try: | |
604 | if hasattr(self.master_config.Global, 'exec_files'): |
|
604 | if hasattr(self.master_config.Global, 'exec_files'): | |
605 | self.log.debug("Running files in Global.exec_files...") |
|
605 | self.log.debug("Running files in Global.exec_files...") | |
606 | exec_files = self.master_config.Global.exec_files |
|
606 | exec_files = self.master_config.Global.exec_files | |
607 | for fname in exec_files: |
|
607 | for fname in exec_files: | |
608 | self._exec_file(fname) |
|
608 | self._exec_file(fname) | |
609 | except: |
|
609 | except: | |
610 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
610 | self.log.warn("Unknown error in handling Global.exec_files:") | |
611 | self.shell.showtraceback() |
|
611 | self.shell.showtraceback() | |
612 |
|
612 | |||
613 | def _run_cmd_line_code(self): |
|
613 | def _run_cmd_line_code(self): | |
614 | if hasattr(self.master_config.Global, 'code_to_run'): |
|
614 | if hasattr(self.master_config.Global, 'code_to_run'): | |
615 | line = self.master_config.Global.code_to_run |
|
615 | line = self.master_config.Global.code_to_run | |
616 | try: |
|
616 | try: | |
617 | self.log.info("Running code given at command line (-c): %s" % |
|
617 | self.log.info("Running code given at command line (-c): %s" % | |
618 | line) |
|
618 | line) | |
619 |
self.shell.run |
|
619 | self.shell.run_cell(line) | |
620 | except: |
|
620 | except: | |
621 | self.log.warn("Error in executing line in user namespace: %s" % |
|
621 | self.log.warn("Error in executing line in user namespace: %s" % | |
622 | line) |
|
622 | line) | |
623 | self.shell.showtraceback() |
|
623 | self.shell.showtraceback() | |
624 | return |
|
624 | return | |
625 | # Like Python itself, ignore the second if the first of these is present |
|
625 | # Like Python itself, ignore the second if the first of these is present | |
626 | try: |
|
626 | try: | |
627 | fname = self.extra_args[0] |
|
627 | fname = self.extra_args[0] | |
628 | except: |
|
628 | except: | |
629 | pass |
|
629 | pass | |
630 | else: |
|
630 | else: | |
631 | try: |
|
631 | try: | |
632 | self._exec_file(fname) |
|
632 | self._exec_file(fname) | |
633 | except: |
|
633 | except: | |
634 | self.log.warn("Error in executing file in user namespace: %s" % |
|
634 | self.log.warn("Error in executing file in user namespace: %s" % | |
635 | fname) |
|
635 | fname) | |
636 | self.shell.showtraceback() |
|
636 | self.shell.showtraceback() | |
637 |
|
637 | |||
638 | def start_app(self): |
|
638 | def start_app(self): | |
639 | if self.master_config.Global.interact: |
|
639 | if self.master_config.Global.interact: | |
640 | self.log.debug("Starting IPython's mainloop...") |
|
640 | self.log.debug("Starting IPython's mainloop...") | |
641 | self.shell.mainloop() |
|
641 | self.shell.mainloop() | |
642 | else: |
|
642 | else: | |
643 | self.log.debug("IPython not interactive, start_app is no-op...") |
|
643 | self.log.debug("IPython not interactive, start_app is no-op...") | |
644 |
|
644 | |||
645 |
|
645 | |||
646 | def load_default_config(ipython_dir=None): |
|
646 | def load_default_config(ipython_dir=None): | |
647 | """Load the default config file from the default ipython_dir. |
|
647 | """Load the default config file from the default ipython_dir. | |
648 |
|
648 | |||
649 | This is useful for embedded shells. |
|
649 | This is useful for embedded shells. | |
650 | """ |
|
650 | """ | |
651 | if ipython_dir is None: |
|
651 | if ipython_dir is None: | |
652 | ipython_dir = get_ipython_dir() |
|
652 | ipython_dir = get_ipython_dir() | |
653 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) |
|
653 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) | |
654 | config = cl.load_config() |
|
654 | config = cl.load_config() | |
655 | return config |
|
655 | return config | |
656 |
|
656 | |||
657 |
|
657 | |||
658 | def launch_new_instance(): |
|
658 | def launch_new_instance(): | |
659 | """Create and run a full blown IPython instance""" |
|
659 | """Create and run a full blown IPython instance""" | |
660 | app = IPythonApp() |
|
660 | app = IPythonApp() | |
661 | app.start() |
|
661 | app.start() | |
662 |
|
662 | |||
663 |
|
663 | |||
664 | if __name__ == '__main__': |
|
664 | if __name__ == '__main__': | |
665 | launch_new_instance() |
|
665 | launch_new_instance() |
@@ -1,575 +1,575 b'' | |||||
1 | """Module for interactive demos using IPython. |
|
1 | """Module for interactive demos using IPython. | |
2 |
|
2 | |||
3 | This module implements a few classes for running Python scripts interactively |
|
3 | This module implements a few classes for running Python scripts interactively | |
4 | in IPython for demonstrations. With very simple markup (a few tags in |
|
4 | in IPython for demonstrations. With very simple markup (a few tags in | |
5 | comments), you can control points where the script stops executing and returns |
|
5 | comments), you can control points where the script stops executing and returns | |
6 | control to IPython. |
|
6 | control to IPython. | |
7 |
|
7 | |||
8 |
|
8 | |||
9 | Provided classes |
|
9 | Provided classes | |
10 | ================ |
|
10 | ================ | |
11 |
|
11 | |||
12 | The classes are (see their docstrings for further details): |
|
12 | The classes are (see their docstrings for further details): | |
13 |
|
13 | |||
14 | - Demo: pure python demos |
|
14 | - Demo: pure python demos | |
15 |
|
15 | |||
16 | - IPythonDemo: demos with input to be processed by IPython as if it had been |
|
16 | - IPythonDemo: demos with input to be processed by IPython as if it had been | |
17 | typed interactively (so magics work, as well as any other special syntax you |
|
17 | typed interactively (so magics work, as well as any other special syntax you | |
18 | may have added via input prefilters). |
|
18 | may have added via input prefilters). | |
19 |
|
19 | |||
20 | - LineDemo: single-line version of the Demo class. These demos are executed |
|
20 | - LineDemo: single-line version of the Demo class. These demos are executed | |
21 | one line at a time, and require no markup. |
|
21 | one line at a time, and require no markup. | |
22 |
|
22 | |||
23 | - IPythonLineDemo: IPython version of the LineDemo class (the demo is |
|
23 | - IPythonLineDemo: IPython version of the LineDemo class (the demo is | |
24 | executed a line at a time, but processed via IPython). |
|
24 | executed a line at a time, but processed via IPython). | |
25 |
|
25 | |||
26 | - ClearMixin: mixin to make Demo classes with less visual clutter. It |
|
26 | - ClearMixin: mixin to make Demo classes with less visual clutter. It | |
27 | declares an empty marquee and a pre_cmd that clears the screen before each |
|
27 | declares an empty marquee and a pre_cmd that clears the screen before each | |
28 | block (see Subclassing below). |
|
28 | block (see Subclassing below). | |
29 |
|
29 | |||
30 | - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo |
|
30 | - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo | |
31 | classes. |
|
31 | classes. | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | Subclassing |
|
34 | Subclassing | |
35 | =========== |
|
35 | =========== | |
36 |
|
36 | |||
37 | The classes here all include a few methods meant to make customization by |
|
37 | The classes here all include a few methods meant to make customization by | |
38 | subclassing more convenient. Their docstrings below have some more details: |
|
38 | subclassing more convenient. Their docstrings below have some more details: | |
39 |
|
39 | |||
40 | - marquee(): generates a marquee to provide visible on-screen markers at each |
|
40 | - marquee(): generates a marquee to provide visible on-screen markers at each | |
41 | block start and end. |
|
41 | block start and end. | |
42 |
|
42 | |||
43 | - pre_cmd(): run right before the execution of each block. |
|
43 | - pre_cmd(): run right before the execution of each block. | |
44 |
|
44 | |||
45 | - post_cmd(): run right after the execution of each block. If the block |
|
45 | - post_cmd(): run right after the execution of each block. If the block | |
46 | raises an exception, this is NOT called. |
|
46 | raises an exception, this is NOT called. | |
47 |
|
47 | |||
48 |
|
48 | |||
49 | Operation |
|
49 | Operation | |
50 | ========= |
|
50 | ========= | |
51 |
|
51 | |||
52 | The file is run in its own empty namespace (though you can pass it a string of |
|
52 | The file is run in its own empty namespace (though you can pass it a string of | |
53 | arguments as if in a command line environment, and it will see those as |
|
53 | arguments as if in a command line environment, and it will see those as | |
54 | sys.argv). But at each stop, the global IPython namespace is updated with the |
|
54 | sys.argv). But at each stop, the global IPython namespace is updated with the | |
55 | current internal demo namespace, so you can work interactively with the data |
|
55 | current internal demo namespace, so you can work interactively with the data | |
56 | accumulated so far. |
|
56 | accumulated so far. | |
57 |
|
57 | |||
58 | By default, each block of code is printed (with syntax highlighting) before |
|
58 | By default, each block of code is printed (with syntax highlighting) before | |
59 | executing it and you have to confirm execution. This is intended to show the |
|
59 | executing it and you have to confirm execution. This is intended to show the | |
60 | code to an audience first so you can discuss it, and only proceed with |
|
60 | code to an audience first so you can discuss it, and only proceed with | |
61 | execution once you agree. There are a few tags which allow you to modify this |
|
61 | execution once you agree. There are a few tags which allow you to modify this | |
62 | behavior. |
|
62 | behavior. | |
63 |
|
63 | |||
64 | The supported tags are: |
|
64 | The supported tags are: | |
65 |
|
65 | |||
66 | # <demo> stop |
|
66 | # <demo> stop | |
67 |
|
67 | |||
68 | Defines block boundaries, the points where IPython stops execution of the |
|
68 | Defines block boundaries, the points where IPython stops execution of the | |
69 | file and returns to the interactive prompt. |
|
69 | file and returns to the interactive prompt. | |
70 |
|
70 | |||
71 | You can optionally mark the stop tag with extra dashes before and after the |
|
71 | You can optionally mark the stop tag with extra dashes before and after the | |
72 | word 'stop', to help visually distinguish the blocks in a text editor: |
|
72 | word 'stop', to help visually distinguish the blocks in a text editor: | |
73 |
|
73 | |||
74 | # <demo> --- stop --- |
|
74 | # <demo> --- stop --- | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | # <demo> silent |
|
77 | # <demo> silent | |
78 |
|
78 | |||
79 | Make a block execute silently (and hence automatically). Typically used in |
|
79 | Make a block execute silently (and hence automatically). Typically used in | |
80 | cases where you have some boilerplate or initialization code which you need |
|
80 | cases where you have some boilerplate or initialization code which you need | |
81 | executed but do not want to be seen in the demo. |
|
81 | executed but do not want to be seen in the demo. | |
82 |
|
82 | |||
83 | # <demo> auto |
|
83 | # <demo> auto | |
84 |
|
84 | |||
85 | Make a block execute automatically, but still being printed. Useful for |
|
85 | Make a block execute automatically, but still being printed. Useful for | |
86 | simple code which does not warrant discussion, since it avoids the extra |
|
86 | simple code which does not warrant discussion, since it avoids the extra | |
87 | manual confirmation. |
|
87 | manual confirmation. | |
88 |
|
88 | |||
89 | # <demo> auto_all |
|
89 | # <demo> auto_all | |
90 |
|
90 | |||
91 | This tag can _only_ be in the first block, and if given it overrides the |
|
91 | This tag can _only_ be in the first block, and if given it overrides the | |
92 | individual auto tags to make the whole demo fully automatic (no block asks |
|
92 | individual auto tags to make the whole demo fully automatic (no block asks | |
93 | for confirmation). It can also be given at creation time (or the attribute |
|
93 | for confirmation). It can also be given at creation time (or the attribute | |
94 | set later) to override what's in the file. |
|
94 | set later) to override what's in the file. | |
95 |
|
95 | |||
96 | While _any_ python file can be run as a Demo instance, if there are no stop |
|
96 | While _any_ python file can be run as a Demo instance, if there are no stop | |
97 | tags the whole file will run in a single block (no different that calling |
|
97 | tags the whole file will run in a single block (no different that calling | |
98 | first %pycat and then %run). The minimal markup to make this useful is to |
|
98 | first %pycat and then %run). The minimal markup to make this useful is to | |
99 | place a set of stop tags; the other tags are only there to let you fine-tune |
|
99 | place a set of stop tags; the other tags are only there to let you fine-tune | |
100 | the execution. |
|
100 | the execution. | |
101 |
|
101 | |||
102 | This is probably best explained with the simple example file below. You can |
|
102 | This is probably best explained with the simple example file below. You can | |
103 | copy this into a file named ex_demo.py, and try running it via: |
|
103 | copy this into a file named ex_demo.py, and try running it via: | |
104 |
|
104 | |||
105 | from IPython.demo import Demo |
|
105 | from IPython.demo import Demo | |
106 | d = Demo('ex_demo.py') |
|
106 | d = Demo('ex_demo.py') | |
107 | d() <--- Call the d object (omit the parens if you have autocall set to 2). |
|
107 | d() <--- Call the d object (omit the parens if you have autocall set to 2). | |
108 |
|
108 | |||
109 | Each time you call the demo object, it runs the next block. The demo object |
|
109 | Each time you call the demo object, it runs the next block. The demo object | |
110 | has a few useful methods for navigation, like again(), edit(), jump(), seek() |
|
110 | has a few useful methods for navigation, like again(), edit(), jump(), seek() | |
111 | and back(). It can be reset for a new run via reset() or reloaded from disk |
|
111 | and back(). It can be reset for a new run via reset() or reloaded from disk | |
112 | (in case you've edited the source) via reload(). See their docstrings below. |
|
112 | (in case you've edited the source) via reload(). See their docstrings below. | |
113 |
|
113 | |||
114 | Note: To make this simpler to explore, a file called "demo-exercizer.py" has |
|
114 | Note: To make this simpler to explore, a file called "demo-exercizer.py" has | |
115 | been added to the "docs/examples/core" directory. Just cd to this directory in |
|
115 | been added to the "docs/examples/core" directory. Just cd to this directory in | |
116 | an IPython session, and type:: |
|
116 | an IPython session, and type:: | |
117 |
|
117 | |||
118 | %run demo-exercizer.py |
|
118 | %run demo-exercizer.py | |
119 |
|
119 | |||
120 | and then follow the directions. |
|
120 | and then follow the directions. | |
121 |
|
121 | |||
122 | Example |
|
122 | Example | |
123 | ======= |
|
123 | ======= | |
124 |
|
124 | |||
125 | The following is a very simple example of a valid demo file. |
|
125 | The following is a very simple example of a valid demo file. | |
126 |
|
126 | |||
127 | #################### EXAMPLE DEMO <ex_demo.py> ############################### |
|
127 | #################### EXAMPLE DEMO <ex_demo.py> ############################### | |
128 | '''A simple interactive demo to illustrate the use of IPython's Demo class.''' |
|
128 | '''A simple interactive demo to illustrate the use of IPython's Demo class.''' | |
129 |
|
129 | |||
130 | print 'Hello, welcome to an interactive IPython demo.' |
|
130 | print 'Hello, welcome to an interactive IPython demo.' | |
131 |
|
131 | |||
132 | # The mark below defines a block boundary, which is a point where IPython will |
|
132 | # The mark below defines a block boundary, which is a point where IPython will | |
133 | # stop execution and return to the interactive prompt. The dashes are actually |
|
133 | # stop execution and return to the interactive prompt. The dashes are actually | |
134 | # optional and used only as a visual aid to clearly separate blocks while |
|
134 | # optional and used only as a visual aid to clearly separate blocks while | |
135 | # editing the demo code. |
|
135 | # editing the demo code. | |
136 | # <demo> stop |
|
136 | # <demo> stop | |
137 |
|
137 | |||
138 | x = 1 |
|
138 | x = 1 | |
139 | y = 2 |
|
139 | y = 2 | |
140 |
|
140 | |||
141 | # <demo> stop |
|
141 | # <demo> stop | |
142 |
|
142 | |||
143 | # the mark below makes this block as silent |
|
143 | # the mark below makes this block as silent | |
144 | # <demo> silent |
|
144 | # <demo> silent | |
145 |
|
145 | |||
146 | print 'This is a silent block, which gets executed but not printed.' |
|
146 | print 'This is a silent block, which gets executed but not printed.' | |
147 |
|
147 | |||
148 | # <demo> stop |
|
148 | # <demo> stop | |
149 | # <demo> auto |
|
149 | # <demo> auto | |
150 | print 'This is an automatic block.' |
|
150 | print 'This is an automatic block.' | |
151 | print 'It is executed without asking for confirmation, but printed.' |
|
151 | print 'It is executed without asking for confirmation, but printed.' | |
152 | z = x+y |
|
152 | z = x+y | |
153 |
|
153 | |||
154 | print 'z=',x |
|
154 | print 'z=',x | |
155 |
|
155 | |||
156 | # <demo> stop |
|
156 | # <demo> stop | |
157 | # This is just another normal block. |
|
157 | # This is just another normal block. | |
158 | print 'z is now:', z |
|
158 | print 'z is now:', z | |
159 |
|
159 | |||
160 | print 'bye!' |
|
160 | print 'bye!' | |
161 | ################### END EXAMPLE DEMO <ex_demo.py> ############################ |
|
161 | ################### END EXAMPLE DEMO <ex_demo.py> ############################ | |
162 | """ |
|
162 | """ | |
163 |
|
163 | |||
164 | #***************************************************************************** |
|
164 | #***************************************************************************** | |
165 | # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu> |
|
165 | # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu> | |
166 | # |
|
166 | # | |
167 | # Distributed under the terms of the BSD License. The full license is in |
|
167 | # Distributed under the terms of the BSD License. The full license is in | |
168 | # the file COPYING, distributed as part of this software. |
|
168 | # the file COPYING, distributed as part of this software. | |
169 | # |
|
169 | # | |
170 | #***************************************************************************** |
|
170 | #***************************************************************************** | |
171 |
|
171 | |||
172 | import exceptions |
|
172 | import exceptions | |
173 | import os |
|
173 | import os | |
174 | import re |
|
174 | import re | |
175 | import shlex |
|
175 | import shlex | |
176 | import sys |
|
176 | import sys | |
177 |
|
177 | |||
178 | from IPython.utils.PyColorize import Parser |
|
178 | from IPython.utils.PyColorize import Parser | |
179 | from IPython.utils.io import file_read, file_readlines |
|
179 | from IPython.utils.io import file_read, file_readlines | |
180 | import IPython.utils.io |
|
180 | import IPython.utils.io | |
181 | from IPython.utils.text import marquee |
|
181 | from IPython.utils.text import marquee | |
182 |
|
182 | |||
183 | __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] |
|
183 | __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] | |
184 |
|
184 | |||
185 | class DemoError(exceptions.Exception): pass |
|
185 | class DemoError(exceptions.Exception): pass | |
186 |
|
186 | |||
187 | def re_mark(mark): |
|
187 | def re_mark(mark): | |
188 | return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE) |
|
188 | return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE) | |
189 |
|
189 | |||
190 | class Demo(object): |
|
190 | class Demo(object): | |
191 |
|
191 | |||
192 | re_stop = re_mark('-*\s?stop\s?-*') |
|
192 | re_stop = re_mark('-*\s?stop\s?-*') | |
193 | re_silent = re_mark('silent') |
|
193 | re_silent = re_mark('silent') | |
194 | re_auto = re_mark('auto') |
|
194 | re_auto = re_mark('auto') | |
195 | re_auto_all = re_mark('auto_all') |
|
195 | re_auto_all = re_mark('auto_all') | |
196 |
|
196 | |||
197 | def __init__(self,src,title='',arg_str='',auto_all=None): |
|
197 | def __init__(self,src,title='',arg_str='',auto_all=None): | |
198 | """Make a new demo object. To run the demo, simply call the object. |
|
198 | """Make a new demo object. To run the demo, simply call the object. | |
199 |
|
199 | |||
200 | See the module docstring for full details and an example (you can use |
|
200 | See the module docstring for full details and an example (you can use | |
201 | IPython.Demo? in IPython to see it). |
|
201 | IPython.Demo? in IPython to see it). | |
202 |
|
202 | |||
203 | Inputs: |
|
203 | Inputs: | |
204 |
|
204 | |||
205 | - src is either a file, or file-like object, or a |
|
205 | - src is either a file, or file-like object, or a | |
206 | string that can be resolved to a filename. |
|
206 | string that can be resolved to a filename. | |
207 |
|
207 | |||
208 | Optional inputs: |
|
208 | Optional inputs: | |
209 |
|
209 | |||
210 | - title: a string to use as the demo name. Of most use when the demo |
|
210 | - title: a string to use as the demo name. Of most use when the demo | |
211 | you are making comes from an object that has no filename, or if you |
|
211 | you are making comes from an object that has no filename, or if you | |
212 | want an alternate denotation distinct from the filename. |
|
212 | want an alternate denotation distinct from the filename. | |
213 |
|
213 | |||
214 | - arg_str(''): a string of arguments, internally converted to a list |
|
214 | - arg_str(''): a string of arguments, internally converted to a list | |
215 | just like sys.argv, so the demo script can see a similar |
|
215 | just like sys.argv, so the demo script can see a similar | |
216 | environment. |
|
216 | environment. | |
217 |
|
217 | |||
218 | - auto_all(None): global flag to run all blocks automatically without |
|
218 | - auto_all(None): global flag to run all blocks automatically without | |
219 | confirmation. This attribute overrides the block-level tags and |
|
219 | confirmation. This attribute overrides the block-level tags and | |
220 | applies to the whole demo. It is an attribute of the object, and |
|
220 | applies to the whole demo. It is an attribute of the object, and | |
221 | can be changed at runtime simply by reassigning it to a boolean |
|
221 | can be changed at runtime simply by reassigning it to a boolean | |
222 | value. |
|
222 | value. | |
223 | """ |
|
223 | """ | |
224 | if hasattr(src, "read"): |
|
224 | if hasattr(src, "read"): | |
225 | # It seems to be a file or a file-like object |
|
225 | # It seems to be a file or a file-like object | |
226 | self.fname = "from a file-like object" |
|
226 | self.fname = "from a file-like object" | |
227 | if title == '': |
|
227 | if title == '': | |
228 | self.title = "from a file-like object" |
|
228 | self.title = "from a file-like object" | |
229 | else: |
|
229 | else: | |
230 | self.title = title |
|
230 | self.title = title | |
231 | else: |
|
231 | else: | |
232 | # Assume it's a string or something that can be converted to one |
|
232 | # Assume it's a string or something that can be converted to one | |
233 | self.fname = src |
|
233 | self.fname = src | |
234 | if title == '': |
|
234 | if title == '': | |
235 | (filepath, filename) = os.path.split(src) |
|
235 | (filepath, filename) = os.path.split(src) | |
236 | self.title = filename |
|
236 | self.title = filename | |
237 | else: |
|
237 | else: | |
238 | self.title = title |
|
238 | self.title = title | |
239 | self.sys_argv = [src] + shlex.split(arg_str) |
|
239 | self.sys_argv = [src] + shlex.split(arg_str) | |
240 | self.auto_all = auto_all |
|
240 | self.auto_all = auto_all | |
241 | self.src = src |
|
241 | self.src = src | |
242 |
|
242 | |||
243 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
243 | # get a few things from ipython. While it's a bit ugly design-wise, | |
244 | # it ensures that things like color scheme and the like are always in |
|
244 | # it ensures that things like color scheme and the like are always in | |
245 | # sync with the ipython mode being used. This class is only meant to |
|
245 | # sync with the ipython mode being used. This class is only meant to | |
246 | # be used inside ipython anyways, so it's OK. |
|
246 | # be used inside ipython anyways, so it's OK. | |
247 | ip = get_ipython() # this is in builtins whenever IPython is running |
|
247 | ip = get_ipython() # this is in builtins whenever IPython is running | |
248 | self.ip_ns = ip.user_ns |
|
248 | self.ip_ns = ip.user_ns | |
249 | self.ip_colorize = ip.pycolorize |
|
249 | self.ip_colorize = ip.pycolorize | |
250 | self.ip_showtb = ip.showtraceback |
|
250 | self.ip_showtb = ip.showtraceback | |
251 |
self.ip_run |
|
251 | self.ip_run_cell = ip.run_cell | |
252 | self.shell = ip |
|
252 | self.shell = ip | |
253 |
|
253 | |||
254 | # load user data and initialize data structures |
|
254 | # load user data and initialize data structures | |
255 | self.reload() |
|
255 | self.reload() | |
256 |
|
256 | |||
257 | def fload(self): |
|
257 | def fload(self): | |
258 | """Load file object.""" |
|
258 | """Load file object.""" | |
259 | # read data and parse into blocks |
|
259 | # read data and parse into blocks | |
260 | if hasattr(self, 'fobj') and self.fobj is not None: |
|
260 | if hasattr(self, 'fobj') and self.fobj is not None: | |
261 | self.fobj.close() |
|
261 | self.fobj.close() | |
262 | if hasattr(self.src, "read"): |
|
262 | if hasattr(self.src, "read"): | |
263 | # It seems to be a file or a file-like object |
|
263 | # It seems to be a file or a file-like object | |
264 | self.fobj = self.src |
|
264 | self.fobj = self.src | |
265 | else: |
|
265 | else: | |
266 | # Assume it's a string or something that can be converted to one |
|
266 | # Assume it's a string or something that can be converted to one | |
267 | self.fobj = open(self.fname) |
|
267 | self.fobj = open(self.fname) | |
268 |
|
268 | |||
269 | def reload(self): |
|
269 | def reload(self): | |
270 | """Reload source from disk and initialize state.""" |
|
270 | """Reload source from disk and initialize state.""" | |
271 | self.fload() |
|
271 | self.fload() | |
272 |
|
272 | |||
273 | self.src = self.fobj.read() |
|
273 | self.src = self.fobj.read() | |
274 | src_b = [b.strip() for b in self.re_stop.split(self.src) if b] |
|
274 | src_b = [b.strip() for b in self.re_stop.split(self.src) if b] | |
275 | self._silent = [bool(self.re_silent.findall(b)) for b in src_b] |
|
275 | self._silent = [bool(self.re_silent.findall(b)) for b in src_b] | |
276 | self._auto = [bool(self.re_auto.findall(b)) for b in src_b] |
|
276 | self._auto = [bool(self.re_auto.findall(b)) for b in src_b] | |
277 |
|
277 | |||
278 | # if auto_all is not given (def. None), we read it from the file |
|
278 | # if auto_all is not given (def. None), we read it from the file | |
279 | if self.auto_all is None: |
|
279 | if self.auto_all is None: | |
280 | self.auto_all = bool(self.re_auto_all.findall(src_b[0])) |
|
280 | self.auto_all = bool(self.re_auto_all.findall(src_b[0])) | |
281 | else: |
|
281 | else: | |
282 | self.auto_all = bool(self.auto_all) |
|
282 | self.auto_all = bool(self.auto_all) | |
283 |
|
283 | |||
284 | # Clean the sources from all markup so it doesn't get displayed when |
|
284 | # Clean the sources from all markup so it doesn't get displayed when | |
285 | # running the demo |
|
285 | # running the demo | |
286 | src_blocks = [] |
|
286 | src_blocks = [] | |
287 | auto_strip = lambda s: self.re_auto.sub('',s) |
|
287 | auto_strip = lambda s: self.re_auto.sub('',s) | |
288 | for i,b in enumerate(src_b): |
|
288 | for i,b in enumerate(src_b): | |
289 | if self._auto[i]: |
|
289 | if self._auto[i]: | |
290 | src_blocks.append(auto_strip(b)) |
|
290 | src_blocks.append(auto_strip(b)) | |
291 | else: |
|
291 | else: | |
292 | src_blocks.append(b) |
|
292 | src_blocks.append(b) | |
293 | # remove the auto_all marker |
|
293 | # remove the auto_all marker | |
294 | src_blocks[0] = self.re_auto_all.sub('',src_blocks[0]) |
|
294 | src_blocks[0] = self.re_auto_all.sub('',src_blocks[0]) | |
295 |
|
295 | |||
296 | self.nblocks = len(src_blocks) |
|
296 | self.nblocks = len(src_blocks) | |
297 | self.src_blocks = src_blocks |
|
297 | self.src_blocks = src_blocks | |
298 |
|
298 | |||
299 | # also build syntax-highlighted source |
|
299 | # also build syntax-highlighted source | |
300 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) |
|
300 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) | |
301 |
|
301 | |||
302 | # ensure clean namespace and seek offset |
|
302 | # ensure clean namespace and seek offset | |
303 | self.reset() |
|
303 | self.reset() | |
304 |
|
304 | |||
305 | def reset(self): |
|
305 | def reset(self): | |
306 | """Reset the namespace and seek pointer to restart the demo""" |
|
306 | """Reset the namespace and seek pointer to restart the demo""" | |
307 | self.user_ns = {} |
|
307 | self.user_ns = {} | |
308 | self.finished = False |
|
308 | self.finished = False | |
309 | self.block_index = 0 |
|
309 | self.block_index = 0 | |
310 |
|
310 | |||
311 | def _validate_index(self,index): |
|
311 | def _validate_index(self,index): | |
312 | if index<0 or index>=self.nblocks: |
|
312 | if index<0 or index>=self.nblocks: | |
313 | raise ValueError('invalid block index %s' % index) |
|
313 | raise ValueError('invalid block index %s' % index) | |
314 |
|
314 | |||
315 | def _get_index(self,index): |
|
315 | def _get_index(self,index): | |
316 | """Get the current block index, validating and checking status. |
|
316 | """Get the current block index, validating and checking status. | |
317 |
|
317 | |||
318 | Returns None if the demo is finished""" |
|
318 | Returns None if the demo is finished""" | |
319 |
|
319 | |||
320 | if index is None: |
|
320 | if index is None: | |
321 | if self.finished: |
|
321 | if self.finished: | |
322 | print >>IPython.utils.io.Term.cout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.' |
|
322 | print >>IPython.utils.io.Term.cout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.' | |
323 | return None |
|
323 | return None | |
324 | index = self.block_index |
|
324 | index = self.block_index | |
325 | else: |
|
325 | else: | |
326 | self._validate_index(index) |
|
326 | self._validate_index(index) | |
327 | return index |
|
327 | return index | |
328 |
|
328 | |||
329 | def seek(self,index): |
|
329 | def seek(self,index): | |
330 | """Move the current seek pointer to the given block. |
|
330 | """Move the current seek pointer to the given block. | |
331 |
|
331 | |||
332 | You can use negative indices to seek from the end, with identical |
|
332 | You can use negative indices to seek from the end, with identical | |
333 | semantics to those of Python lists.""" |
|
333 | semantics to those of Python lists.""" | |
334 | if index<0: |
|
334 | if index<0: | |
335 | index = self.nblocks + index |
|
335 | index = self.nblocks + index | |
336 | self._validate_index(index) |
|
336 | self._validate_index(index) | |
337 | self.block_index = index |
|
337 | self.block_index = index | |
338 | self.finished = False |
|
338 | self.finished = False | |
339 |
|
339 | |||
340 | def back(self,num=1): |
|
340 | def back(self,num=1): | |
341 | """Move the seek pointer back num blocks (default is 1).""" |
|
341 | """Move the seek pointer back num blocks (default is 1).""" | |
342 | self.seek(self.block_index-num) |
|
342 | self.seek(self.block_index-num) | |
343 |
|
343 | |||
344 | def jump(self,num=1): |
|
344 | def jump(self,num=1): | |
345 | """Jump a given number of blocks relative to the current one. |
|
345 | """Jump a given number of blocks relative to the current one. | |
346 |
|
346 | |||
347 | The offset can be positive or negative, defaults to 1.""" |
|
347 | The offset can be positive or negative, defaults to 1.""" | |
348 | self.seek(self.block_index+num) |
|
348 | self.seek(self.block_index+num) | |
349 |
|
349 | |||
350 | def again(self): |
|
350 | def again(self): | |
351 | """Move the seek pointer back one block and re-execute.""" |
|
351 | """Move the seek pointer back one block and re-execute.""" | |
352 | self.back(1) |
|
352 | self.back(1) | |
353 | self() |
|
353 | self() | |
354 |
|
354 | |||
355 | def edit(self,index=None): |
|
355 | def edit(self,index=None): | |
356 | """Edit a block. |
|
356 | """Edit a block. | |
357 |
|
357 | |||
358 | If no number is given, use the last block executed. |
|
358 | If no number is given, use the last block executed. | |
359 |
|
359 | |||
360 | This edits the in-memory copy of the demo, it does NOT modify the |
|
360 | This edits the in-memory copy of the demo, it does NOT modify the | |
361 | original source file. If you want to do that, simply open the file in |
|
361 | original source file. If you want to do that, simply open the file in | |
362 | an editor and use reload() when you make changes to the file. This |
|
362 | an editor and use reload() when you make changes to the file. This | |
363 | method is meant to let you change a block during a demonstration for |
|
363 | method is meant to let you change a block during a demonstration for | |
364 | explanatory purposes, without damaging your original script.""" |
|
364 | explanatory purposes, without damaging your original script.""" | |
365 |
|
365 | |||
366 | index = self._get_index(index) |
|
366 | index = self._get_index(index) | |
367 | if index is None: |
|
367 | if index is None: | |
368 | return |
|
368 | return | |
369 | # decrease the index by one (unless we're at the very beginning), so |
|
369 | # decrease the index by one (unless we're at the very beginning), so | |
370 | # that the default demo.edit() call opens up the sblock we've last run |
|
370 | # that the default demo.edit() call opens up the sblock we've last run | |
371 | if index>0: |
|
371 | if index>0: | |
372 | index -= 1 |
|
372 | index -= 1 | |
373 |
|
373 | |||
374 | filename = self.shell.mktempfile(self.src_blocks[index]) |
|
374 | filename = self.shell.mktempfile(self.src_blocks[index]) | |
375 | self.shell.hooks.editor(filename,1) |
|
375 | self.shell.hooks.editor(filename,1) | |
376 | new_block = file_read(filename) |
|
376 | new_block = file_read(filename) | |
377 | # update the source and colored block |
|
377 | # update the source and colored block | |
378 | self.src_blocks[index] = new_block |
|
378 | self.src_blocks[index] = new_block | |
379 | self.src_blocks_colored[index] = self.ip_colorize(new_block) |
|
379 | self.src_blocks_colored[index] = self.ip_colorize(new_block) | |
380 | self.block_index = index |
|
380 | self.block_index = index | |
381 | # call to run with the newly edited index |
|
381 | # call to run with the newly edited index | |
382 | self() |
|
382 | self() | |
383 |
|
383 | |||
384 | def show(self,index=None): |
|
384 | def show(self,index=None): | |
385 | """Show a single block on screen""" |
|
385 | """Show a single block on screen""" | |
386 |
|
386 | |||
387 | index = self._get_index(index) |
|
387 | index = self._get_index(index) | |
388 | if index is None: |
|
388 | if index is None: | |
389 | return |
|
389 | return | |
390 |
|
390 | |||
391 | print >>IPython.utils.io.Term.cout, self.marquee('<%s> block # %s (%s remaining)' % |
|
391 | print >>IPython.utils.io.Term.cout, self.marquee('<%s> block # %s (%s remaining)' % | |
392 | (self.title,index,self.nblocks-index-1)) |
|
392 | (self.title,index,self.nblocks-index-1)) | |
393 | print >>IPython.utils.io.Term.cout,(self.src_blocks_colored[index]) |
|
393 | print >>IPython.utils.io.Term.cout,(self.src_blocks_colored[index]) | |
394 | sys.stdout.flush() |
|
394 | sys.stdout.flush() | |
395 |
|
395 | |||
396 | def show_all(self): |
|
396 | def show_all(self): | |
397 | """Show entire demo on screen, block by block""" |
|
397 | """Show entire demo on screen, block by block""" | |
398 |
|
398 | |||
399 | fname = self.title |
|
399 | fname = self.title | |
400 | title = self.title |
|
400 | title = self.title | |
401 | nblocks = self.nblocks |
|
401 | nblocks = self.nblocks | |
402 | silent = self._silent |
|
402 | silent = self._silent | |
403 | marquee = self.marquee |
|
403 | marquee = self.marquee | |
404 | for index,block in enumerate(self.src_blocks_colored): |
|
404 | for index,block in enumerate(self.src_blocks_colored): | |
405 | if silent[index]: |
|
405 | if silent[index]: | |
406 | print >>IPython.utils.io.Term.cout, marquee('<%s> SILENT block # %s (%s remaining)' % |
|
406 | print >>IPython.utils.io.Term.cout, marquee('<%s> SILENT block # %s (%s remaining)' % | |
407 | (title,index,nblocks-index-1)) |
|
407 | (title,index,nblocks-index-1)) | |
408 | else: |
|
408 | else: | |
409 | print >>IPython.utils.io.Term.cout, marquee('<%s> block # %s (%s remaining)' % |
|
409 | print >>IPython.utils.io.Term.cout, marquee('<%s> block # %s (%s remaining)' % | |
410 | (title,index,nblocks-index-1)) |
|
410 | (title,index,nblocks-index-1)) | |
411 | print >>IPython.utils.io.Term.cout, block, |
|
411 | print >>IPython.utils.io.Term.cout, block, | |
412 | sys.stdout.flush() |
|
412 | sys.stdout.flush() | |
413 |
|
413 | |||
414 |
def run |
|
414 | def run_cell(self,source): | |
415 | """Execute a string with one or more lines of code""" |
|
415 | """Execute a string with one or more lines of code""" | |
416 |
|
416 | |||
417 | exec source in self.user_ns |
|
417 | exec source in self.user_ns | |
418 |
|
418 | |||
419 | def __call__(self,index=None): |
|
419 | def __call__(self,index=None): | |
420 | """run a block of the demo. |
|
420 | """run a block of the demo. | |
421 |
|
421 | |||
422 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
422 | If index is given, it should be an integer >=1 and <= nblocks. This | |
423 | means that the calling convention is one off from typical Python |
|
423 | means that the calling convention is one off from typical Python | |
424 | lists. The reason for the inconsistency is that the demo always |
|
424 | lists. The reason for the inconsistency is that the demo always | |
425 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
425 | prints 'Block n/N, and N is the total, so it would be very odd to use | |
426 | zero-indexing here.""" |
|
426 | zero-indexing here.""" | |
427 |
|
427 | |||
428 | index = self._get_index(index) |
|
428 | index = self._get_index(index) | |
429 | if index is None: |
|
429 | if index is None: | |
430 | return |
|
430 | return | |
431 | try: |
|
431 | try: | |
432 | marquee = self.marquee |
|
432 | marquee = self.marquee | |
433 | next_block = self.src_blocks[index] |
|
433 | next_block = self.src_blocks[index] | |
434 | self.block_index += 1 |
|
434 | self.block_index += 1 | |
435 | if self._silent[index]: |
|
435 | if self._silent[index]: | |
436 | print >>IPython.utils.io.Term.cout, marquee('Executing silent block # %s (%s remaining)' % |
|
436 | print >>IPython.utils.io.Term.cout, marquee('Executing silent block # %s (%s remaining)' % | |
437 | (index,self.nblocks-index-1)) |
|
437 | (index,self.nblocks-index-1)) | |
438 | else: |
|
438 | else: | |
439 | self.pre_cmd() |
|
439 | self.pre_cmd() | |
440 | self.show(index) |
|
440 | self.show(index) | |
441 | if self.auto_all or self._auto[index]: |
|
441 | if self.auto_all or self._auto[index]: | |
442 | print >>IPython.utils.io.Term.cout, marquee('output:') |
|
442 | print >>IPython.utils.io.Term.cout, marquee('output:') | |
443 | else: |
|
443 | else: | |
444 | print >>IPython.utils.io.Term.cout, marquee('Press <q> to quit, <Enter> to execute...'), |
|
444 | print >>IPython.utils.io.Term.cout, marquee('Press <q> to quit, <Enter> to execute...'), | |
445 | ans = raw_input().strip() |
|
445 | ans = raw_input().strip() | |
446 | if ans: |
|
446 | if ans: | |
447 | print >>IPython.utils.io.Term.cout, marquee('Block NOT executed') |
|
447 | print >>IPython.utils.io.Term.cout, marquee('Block NOT executed') | |
448 | return |
|
448 | return | |
449 | try: |
|
449 | try: | |
450 | save_argv = sys.argv |
|
450 | save_argv = sys.argv | |
451 | sys.argv = self.sys_argv |
|
451 | sys.argv = self.sys_argv | |
452 |
self.run |
|
452 | self.run_cell(next_block) | |
453 | self.post_cmd() |
|
453 | self.post_cmd() | |
454 | finally: |
|
454 | finally: | |
455 | sys.argv = save_argv |
|
455 | sys.argv = save_argv | |
456 |
|
456 | |||
457 | except: |
|
457 | except: | |
458 | self.ip_showtb(filename=self.fname) |
|
458 | self.ip_showtb(filename=self.fname) | |
459 | else: |
|
459 | else: | |
460 | self.ip_ns.update(self.user_ns) |
|
460 | self.ip_ns.update(self.user_ns) | |
461 |
|
461 | |||
462 | if self.block_index == self.nblocks: |
|
462 | if self.block_index == self.nblocks: | |
463 | mq1 = self.marquee('END OF DEMO') |
|
463 | mq1 = self.marquee('END OF DEMO') | |
464 | if mq1: |
|
464 | if mq1: | |
465 | # avoid spurious print >>IPython.utils.io.Term.cout,s if empty marquees are used |
|
465 | # avoid spurious print >>IPython.utils.io.Term.cout,s if empty marquees are used | |
466 | print >>IPython.utils.io.Term.cout |
|
466 | print >>IPython.utils.io.Term.cout | |
467 | print >>IPython.utils.io.Term.cout, mq1 |
|
467 | print >>IPython.utils.io.Term.cout, mq1 | |
468 | print >>IPython.utils.io.Term.cout, self.marquee('Use <demo_name>.reset() if you want to rerun it.') |
|
468 | print >>IPython.utils.io.Term.cout, self.marquee('Use <demo_name>.reset() if you want to rerun it.') | |
469 | self.finished = True |
|
469 | self.finished = True | |
470 |
|
470 | |||
471 | # These methods are meant to be overridden by subclasses who may wish to |
|
471 | # These methods are meant to be overridden by subclasses who may wish to | |
472 | # customize the behavior of of their demos. |
|
472 | # customize the behavior of of their demos. | |
473 | def marquee(self,txt='',width=78,mark='*'): |
|
473 | def marquee(self,txt='',width=78,mark='*'): | |
474 | """Return the input string centered in a 'marquee'.""" |
|
474 | """Return the input string centered in a 'marquee'.""" | |
475 | return marquee(txt,width,mark) |
|
475 | return marquee(txt,width,mark) | |
476 |
|
476 | |||
477 | def pre_cmd(self): |
|
477 | def pre_cmd(self): | |
478 | """Method called before executing each block.""" |
|
478 | """Method called before executing each block.""" | |
479 | pass |
|
479 | pass | |
480 |
|
480 | |||
481 | def post_cmd(self): |
|
481 | def post_cmd(self): | |
482 | """Method called after executing each block.""" |
|
482 | """Method called after executing each block.""" | |
483 | pass |
|
483 | pass | |
484 |
|
484 | |||
485 |
|
485 | |||
486 | class IPythonDemo(Demo): |
|
486 | class IPythonDemo(Demo): | |
487 | """Class for interactive demos with IPython's input processing applied. |
|
487 | """Class for interactive demos with IPython's input processing applied. | |
488 |
|
488 | |||
489 | This subclasses Demo, but instead of executing each block by the Python |
|
489 | This subclasses Demo, but instead of executing each block by the Python | |
490 | interpreter (via exec), it actually calls IPython on it, so that any input |
|
490 | interpreter (via exec), it actually calls IPython on it, so that any input | |
491 | filters which may be in place are applied to the input block. |
|
491 | filters which may be in place are applied to the input block. | |
492 |
|
492 | |||
493 | If you have an interactive environment which exposes special input |
|
493 | If you have an interactive environment which exposes special input | |
494 | processing, you can use this class instead to write demo scripts which |
|
494 | processing, you can use this class instead to write demo scripts which | |
495 | operate exactly as if you had typed them interactively. The default Demo |
|
495 | operate exactly as if you had typed them interactively. The default Demo | |
496 | class requires the input to be valid, pure Python code. |
|
496 | class requires the input to be valid, pure Python code. | |
497 | """ |
|
497 | """ | |
498 |
|
498 | |||
499 |
def run |
|
499 | def run_cell(self,source): | |
500 | """Execute a string with one or more lines of code""" |
|
500 | """Execute a string with one or more lines of code""" | |
501 |
|
501 | |||
502 |
self.shell.run |
|
502 | self.shell.run_cell(source) | |
503 |
|
503 | |||
504 | class LineDemo(Demo): |
|
504 | class LineDemo(Demo): | |
505 | """Demo where each line is executed as a separate block. |
|
505 | """Demo where each line is executed as a separate block. | |
506 |
|
506 | |||
507 | The input script should be valid Python code. |
|
507 | The input script should be valid Python code. | |
508 |
|
508 | |||
509 | This class doesn't require any markup at all, and it's meant for simple |
|
509 | This class doesn't require any markup at all, and it's meant for simple | |
510 | scripts (with no nesting or any kind of indentation) which consist of |
|
510 | scripts (with no nesting or any kind of indentation) which consist of | |
511 | multiple lines of input to be executed, one at a time, as if they had been |
|
511 | multiple lines of input to be executed, one at a time, as if they had been | |
512 | typed in the interactive prompt. |
|
512 | typed in the interactive prompt. | |
513 |
|
513 | |||
514 | Note: the input can not have *any* indentation, which means that only |
|
514 | Note: the input can not have *any* indentation, which means that only | |
515 | single-lines of input are accepted, not even function definitions are |
|
515 | single-lines of input are accepted, not even function definitions are | |
516 | valid.""" |
|
516 | valid.""" | |
517 |
|
517 | |||
518 | def reload(self): |
|
518 | def reload(self): | |
519 | """Reload source from disk and initialize state.""" |
|
519 | """Reload source from disk and initialize state.""" | |
520 | # read data and parse into blocks |
|
520 | # read data and parse into blocks | |
521 | self.fload() |
|
521 | self.fload() | |
522 | lines = self.fobj.readlines() |
|
522 | lines = self.fobj.readlines() | |
523 | src_b = [l for l in lines if l.strip()] |
|
523 | src_b = [l for l in lines if l.strip()] | |
524 | nblocks = len(src_b) |
|
524 | nblocks = len(src_b) | |
525 | self.src = ''.join(lines) |
|
525 | self.src = ''.join(lines) | |
526 | self._silent = [False]*nblocks |
|
526 | self._silent = [False]*nblocks | |
527 | self._auto = [True]*nblocks |
|
527 | self._auto = [True]*nblocks | |
528 | self.auto_all = True |
|
528 | self.auto_all = True | |
529 | self.nblocks = nblocks |
|
529 | self.nblocks = nblocks | |
530 | self.src_blocks = src_b |
|
530 | self.src_blocks = src_b | |
531 |
|
531 | |||
532 | # also build syntax-highlighted source |
|
532 | # also build syntax-highlighted source | |
533 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) |
|
533 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) | |
534 |
|
534 | |||
535 | # ensure clean namespace and seek offset |
|
535 | # ensure clean namespace and seek offset | |
536 | self.reset() |
|
536 | self.reset() | |
537 |
|
537 | |||
538 |
|
538 | |||
539 | class IPythonLineDemo(IPythonDemo,LineDemo): |
|
539 | class IPythonLineDemo(IPythonDemo,LineDemo): | |
540 | """Variant of the LineDemo class whose input is processed by IPython.""" |
|
540 | """Variant of the LineDemo class whose input is processed by IPython.""" | |
541 | pass |
|
541 | pass | |
542 |
|
542 | |||
543 |
|
543 | |||
544 | class ClearMixin(object): |
|
544 | class ClearMixin(object): | |
545 | """Use this mixin to make Demo classes with less visual clutter. |
|
545 | """Use this mixin to make Demo classes with less visual clutter. | |
546 |
|
546 | |||
547 | Demos using this mixin will clear the screen before every block and use |
|
547 | Demos using this mixin will clear the screen before every block and use | |
548 | blank marquees. |
|
548 | blank marquees. | |
549 |
|
549 | |||
550 | Note that in order for the methods defined here to actually override those |
|
550 | Note that in order for the methods defined here to actually override those | |
551 | of the classes it's mixed with, it must go /first/ in the inheritance |
|
551 | of the classes it's mixed with, it must go /first/ in the inheritance | |
552 | tree. For example: |
|
552 | tree. For example: | |
553 |
|
553 | |||
554 | class ClearIPDemo(ClearMixin,IPythonDemo): pass |
|
554 | class ClearIPDemo(ClearMixin,IPythonDemo): pass | |
555 |
|
555 | |||
556 | will provide an IPythonDemo class with the mixin's features. |
|
556 | will provide an IPythonDemo class with the mixin's features. | |
557 | """ |
|
557 | """ | |
558 |
|
558 | |||
559 | def marquee(self,txt='',width=78,mark='*'): |
|
559 | def marquee(self,txt='',width=78,mark='*'): | |
560 | """Blank marquee that returns '' no matter what the input.""" |
|
560 | """Blank marquee that returns '' no matter what the input.""" | |
561 | return '' |
|
561 | return '' | |
562 |
|
562 | |||
563 | def pre_cmd(self): |
|
563 | def pre_cmd(self): | |
564 | """Method called before executing each block. |
|
564 | """Method called before executing each block. | |
565 |
|
565 | |||
566 | This one simply clears the screen.""" |
|
566 | This one simply clears the screen.""" | |
567 | from IPython.utils.terminal import term_clear |
|
567 | from IPython.utils.terminal import term_clear | |
568 | term_clear() |
|
568 | term_clear() | |
569 |
|
569 | |||
570 | class ClearDemo(ClearMixin,Demo): |
|
570 | class ClearDemo(ClearMixin,Demo): | |
571 | pass |
|
571 | pass | |
572 |
|
572 | |||
573 |
|
573 | |||
574 | class ClearIPDemo(ClearMixin,IPythonDemo): |
|
574 | class ClearIPDemo(ClearMixin,IPythonDemo): | |
575 | pass |
|
575 | pass |
@@ -1,627 +1,622 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | """A simple interactive kernel that talks to a frontend over 0MQ. |
|
2 | """A simple interactive kernel that talks to a frontend over 0MQ. | |
3 |
|
3 | |||
4 | Things to do: |
|
4 | Things to do: | |
5 |
|
5 | |||
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should |
|
6 | * Implement `set_parent` logic. Right before doing exec, the Kernel should | |
7 | call set_parent on all the PUB objects with the message about to be executed. |
|
7 | call set_parent on all the PUB objects with the message about to be executed. | |
8 | * Implement random port and security key logic. |
|
8 | * Implement random port and security key logic. | |
9 | * Implement control messages. |
|
9 | * Implement control messages. | |
10 | * Implement event loop and poll version. |
|
10 | * Implement event loop and poll version. | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Standard library imports. |
|
18 | # Standard library imports. | |
19 | import __builtin__ |
|
19 | import __builtin__ | |
20 | import atexit |
|
20 | import atexit | |
21 | import sys |
|
21 | import sys | |
22 | import time |
|
22 | import time | |
23 | import traceback |
|
23 | import traceback | |
24 |
|
24 | |||
25 | # System library imports. |
|
25 | # System library imports. | |
26 | import zmq |
|
26 | import zmq | |
27 |
|
27 | |||
28 | # Local imports. |
|
28 | # Local imports. | |
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.utils import io |
|
30 | from IPython.utils import io | |
31 | from IPython.utils.jsonutil import json_clean |
|
31 | from IPython.utils.jsonutil import json_clean | |
32 | from IPython.lib import pylabtools |
|
32 | from IPython.lib import pylabtools | |
33 | from IPython.utils.traitlets import Instance, Float |
|
33 | from IPython.utils.traitlets import Instance, Float | |
34 | from entry_point import (base_launch_kernel, make_argument_parser, make_kernel, |
|
34 | from entry_point import (base_launch_kernel, make_argument_parser, make_kernel, | |
35 | start_kernel) |
|
35 | start_kernel) | |
36 | from iostream import OutStream |
|
36 | from iostream import OutStream | |
37 | from session import Session, Message |
|
37 | from session import Session, Message | |
38 | from zmqshell import ZMQInteractiveShell |
|
38 | from zmqshell import ZMQInteractiveShell | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Main kernel class |
|
41 | # Main kernel class | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | class Kernel(Configurable): |
|
44 | class Kernel(Configurable): | |
45 |
|
45 | |||
46 | #--------------------------------------------------------------------------- |
|
46 | #--------------------------------------------------------------------------- | |
47 | # Kernel interface |
|
47 | # Kernel interface | |
48 | #--------------------------------------------------------------------------- |
|
48 | #--------------------------------------------------------------------------- | |
49 |
|
49 | |||
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
50 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
51 | session = Instance(Session) |
|
51 | session = Instance(Session) | |
52 | reply_socket = Instance('zmq.Socket') |
|
52 | reply_socket = Instance('zmq.Socket') | |
53 | pub_socket = Instance('zmq.Socket') |
|
53 | pub_socket = Instance('zmq.Socket') | |
54 | req_socket = Instance('zmq.Socket') |
|
54 | req_socket = Instance('zmq.Socket') | |
55 |
|
55 | |||
56 | # Private interface |
|
56 | # Private interface | |
57 |
|
57 | |||
58 | # Time to sleep after flushing the stdout/err buffers in each execute |
|
58 | # Time to sleep after flushing the stdout/err buffers in each execute | |
59 | # cycle. While this introduces a hard limit on the minimal latency of the |
|
59 | # cycle. While this introduces a hard limit on the minimal latency of the | |
60 | # execute cycle, it helps prevent output synchronization problems for |
|
60 | # execute cycle, it helps prevent output synchronization problems for | |
61 | # clients. |
|
61 | # clients. | |
62 | # Units are in seconds. The minimum zmq latency on local host is probably |
|
62 | # Units are in seconds. The minimum zmq latency on local host is probably | |
63 | # ~150 microseconds, set this to 500us for now. We may need to increase it |
|
63 | # ~150 microseconds, set this to 500us for now. We may need to increase it | |
64 | # a little if it's not enough after more interactive testing. |
|
64 | # a little if it's not enough after more interactive testing. | |
65 | _execute_sleep = Float(0.0005, config=True) |
|
65 | _execute_sleep = Float(0.0005, config=True) | |
66 |
|
66 | |||
67 | # Frequency of the kernel's event loop. |
|
67 | # Frequency of the kernel's event loop. | |
68 | # Units are in seconds, kernel subclasses for GUI toolkits may need to |
|
68 | # Units are in seconds, kernel subclasses for GUI toolkits may need to | |
69 | # adapt to milliseconds. |
|
69 | # adapt to milliseconds. | |
70 | _poll_interval = Float(0.05, config=True) |
|
70 | _poll_interval = Float(0.05, config=True) | |
71 |
|
71 | |||
72 | # If the shutdown was requested over the network, we leave here the |
|
72 | # If the shutdown was requested over the network, we leave here the | |
73 | # necessary reply message so it can be sent by our registered atexit |
|
73 | # necessary reply message so it can be sent by our registered atexit | |
74 | # handler. This ensures that the reply is only sent to clients truly at |
|
74 | # handler. This ensures that the reply is only sent to clients truly at | |
75 | # the end of our shutdown process (which happens after the underlying |
|
75 | # the end of our shutdown process (which happens after the underlying | |
76 | # IPython shell's own shutdown). |
|
76 | # IPython shell's own shutdown). | |
77 | _shutdown_message = None |
|
77 | _shutdown_message = None | |
78 |
|
78 | |||
79 | # This is a dict of port number that the kernel is listening on. It is set |
|
79 | # This is a dict of port number that the kernel is listening on. It is set | |
80 | # by record_ports and used by connect_request. |
|
80 | # by record_ports and used by connect_request. | |
81 | _recorded_ports = None |
|
81 | _recorded_ports = None | |
82 |
|
82 | |||
83 | def __init__(self, **kwargs): |
|
83 | def __init__(self, **kwargs): | |
84 | super(Kernel, self).__init__(**kwargs) |
|
84 | super(Kernel, self).__init__(**kwargs) | |
85 |
|
85 | |||
86 | # Before we even start up the shell, register *first* our exit handlers |
|
86 | # Before we even start up the shell, register *first* our exit handlers | |
87 | # so they come before the shell's |
|
87 | # so they come before the shell's | |
88 | atexit.register(self._at_shutdown) |
|
88 | atexit.register(self._at_shutdown) | |
89 |
|
89 | |||
90 | # Initialize the InteractiveShell subclass |
|
90 | # Initialize the InteractiveShell subclass | |
91 | self.shell = ZMQInteractiveShell.instance() |
|
91 | self.shell = ZMQInteractiveShell.instance() | |
92 | self.shell.displayhook.session = self.session |
|
92 | self.shell.displayhook.session = self.session | |
93 | self.shell.displayhook.pub_socket = self.pub_socket |
|
93 | self.shell.displayhook.pub_socket = self.pub_socket | |
94 |
|
94 | |||
95 | # TMP - hack while developing |
|
95 | # TMP - hack while developing | |
96 | self.shell._reply_content = None |
|
96 | self.shell._reply_content = None | |
97 |
|
97 | |||
98 | # Build dict of handlers for message types |
|
98 | # Build dict of handlers for message types | |
99 | msg_types = [ 'execute_request', 'complete_request', |
|
99 | msg_types = [ 'execute_request', 'complete_request', | |
100 | 'object_info_request', 'history_request', |
|
100 | 'object_info_request', 'history_request', | |
101 | 'connect_request', 'shutdown_request'] |
|
101 | 'connect_request', 'shutdown_request'] | |
102 | self.handlers = {} |
|
102 | self.handlers = {} | |
103 | for msg_type in msg_types: |
|
103 | for msg_type in msg_types: | |
104 | self.handlers[msg_type] = getattr(self, msg_type) |
|
104 | self.handlers[msg_type] = getattr(self, msg_type) | |
105 |
|
105 | |||
106 | def do_one_iteration(self): |
|
106 | def do_one_iteration(self): | |
107 | """Do one iteration of the kernel's evaluation loop. |
|
107 | """Do one iteration of the kernel's evaluation loop. | |
108 | """ |
|
108 | """ | |
109 | try: |
|
109 | try: | |
110 | ident = self.reply_socket.recv(zmq.NOBLOCK) |
|
110 | ident = self.reply_socket.recv(zmq.NOBLOCK) | |
111 | except zmq.ZMQError, e: |
|
111 | except zmq.ZMQError, e: | |
112 | if e.errno == zmq.EAGAIN: |
|
112 | if e.errno == zmq.EAGAIN: | |
113 | return |
|
113 | return | |
114 | else: |
|
114 | else: | |
115 | raise |
|
115 | raise | |
116 | # FIXME: Bug in pyzmq/zmq? |
|
116 | # FIXME: Bug in pyzmq/zmq? | |
117 | # assert self.reply_socket.rcvmore(), "Missing message part." |
|
117 | # assert self.reply_socket.rcvmore(), "Missing message part." | |
118 | msg = self.reply_socket.recv_json() |
|
118 | msg = self.reply_socket.recv_json() | |
119 |
|
119 | |||
120 | # Print some info about this message and leave a '--->' marker, so it's |
|
120 | # Print some info about this message and leave a '--->' marker, so it's | |
121 | # easier to trace visually the message chain when debugging. Each |
|
121 | # easier to trace visually the message chain when debugging. Each | |
122 | # handler prints its message at the end. |
|
122 | # handler prints its message at the end. | |
123 | # Eventually we'll move these from stdout to a logger. |
|
123 | # Eventually we'll move these from stdout to a logger. | |
124 | io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***') |
|
124 | io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***') | |
125 | io.raw_print(' Content: ', msg['content'], |
|
125 | io.raw_print(' Content: ', msg['content'], | |
126 | '\n --->\n ', sep='', end='') |
|
126 | '\n --->\n ', sep='', end='') | |
127 |
|
127 | |||
128 | # Find and call actual handler for message |
|
128 | # Find and call actual handler for message | |
129 | handler = self.handlers.get(msg['msg_type'], None) |
|
129 | handler = self.handlers.get(msg['msg_type'], None) | |
130 | if handler is None: |
|
130 | if handler is None: | |
131 | io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg) |
|
131 | io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg) | |
132 | else: |
|
132 | else: | |
133 | handler(ident, msg) |
|
133 | handler(ident, msg) | |
134 |
|
134 | |||
135 | # Check whether we should exit, in case the incoming message set the |
|
135 | # Check whether we should exit, in case the incoming message set the | |
136 | # exit flag on |
|
136 | # exit flag on | |
137 | if self.shell.exit_now: |
|
137 | if self.shell.exit_now: | |
138 | io.raw_print('\nExiting IPython kernel...') |
|
138 | io.raw_print('\nExiting IPython kernel...') | |
139 | # We do a normal, clean exit, which allows any actions registered |
|
139 | # We do a normal, clean exit, which allows any actions registered | |
140 | # via atexit (such as history saving) to take place. |
|
140 | # via atexit (such as history saving) to take place. | |
141 | sys.exit(0) |
|
141 | sys.exit(0) | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | def start(self): |
|
144 | def start(self): | |
145 | """ Start the kernel main loop. |
|
145 | """ Start the kernel main loop. | |
146 | """ |
|
146 | """ | |
147 | while True: |
|
147 | while True: | |
148 | time.sleep(self._poll_interval) |
|
148 | time.sleep(self._poll_interval) | |
149 | self.do_one_iteration() |
|
149 | self.do_one_iteration() | |
150 |
|
150 | |||
151 | def record_ports(self, xrep_port, pub_port, req_port, hb_port): |
|
151 | def record_ports(self, xrep_port, pub_port, req_port, hb_port): | |
152 | """Record the ports that this kernel is using. |
|
152 | """Record the ports that this kernel is using. | |
153 |
|
153 | |||
154 | The creator of the Kernel instance must call this methods if they |
|
154 | The creator of the Kernel instance must call this methods if they | |
155 | want the :meth:`connect_request` method to return the port numbers. |
|
155 | want the :meth:`connect_request` method to return the port numbers. | |
156 | """ |
|
156 | """ | |
157 | self._recorded_ports = { |
|
157 | self._recorded_ports = { | |
158 | 'xrep_port' : xrep_port, |
|
158 | 'xrep_port' : xrep_port, | |
159 | 'pub_port' : pub_port, |
|
159 | 'pub_port' : pub_port, | |
160 | 'req_port' : req_port, |
|
160 | 'req_port' : req_port, | |
161 | 'hb_port' : hb_port |
|
161 | 'hb_port' : hb_port | |
162 | } |
|
162 | } | |
163 |
|
163 | |||
164 | #--------------------------------------------------------------------------- |
|
164 | #--------------------------------------------------------------------------- | |
165 | # Kernel request handlers |
|
165 | # Kernel request handlers | |
166 | #--------------------------------------------------------------------------- |
|
166 | #--------------------------------------------------------------------------- | |
167 |
|
167 | |||
168 | def _publish_pyin(self, code, parent): |
|
168 | def _publish_pyin(self, code, parent): | |
169 | """Publish the code request on the pyin stream.""" |
|
169 | """Publish the code request on the pyin stream.""" | |
170 |
|
170 | |||
171 | pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) |
|
171 | pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent) | |
172 | self.pub_socket.send_json(pyin_msg) |
|
172 | self.pub_socket.send_json(pyin_msg) | |
173 |
|
173 | |||
174 | def execute_request(self, ident, parent): |
|
174 | def execute_request(self, ident, parent): | |
175 |
|
175 | |||
176 | status_msg = self.session.msg( |
|
176 | status_msg = self.session.msg( | |
177 | u'status', |
|
177 | u'status', | |
178 | {u'execution_state':u'busy'}, |
|
178 | {u'execution_state':u'busy'}, | |
179 | parent=parent |
|
179 | parent=parent | |
180 | ) |
|
180 | ) | |
181 | self.pub_socket.send_json(status_msg) |
|
181 | self.pub_socket.send_json(status_msg) | |
182 |
|
182 | |||
183 | try: |
|
183 | try: | |
184 | content = parent[u'content'] |
|
184 | content = parent[u'content'] | |
185 | code = content[u'code'] |
|
185 | code = content[u'code'] | |
186 | silent = content[u'silent'] |
|
186 | silent = content[u'silent'] | |
187 | except: |
|
187 | except: | |
188 | io.raw_print_err("Got bad msg: ") |
|
188 | io.raw_print_err("Got bad msg: ") | |
189 | io.raw_print_err(Message(parent)) |
|
189 | io.raw_print_err(Message(parent)) | |
190 | return |
|
190 | return | |
191 |
|
191 | |||
192 | shell = self.shell # we'll need this a lot here |
|
192 | shell = self.shell # we'll need this a lot here | |
193 |
|
193 | |||
194 | # Replace raw_input. Note that is not sufficient to replace |
|
194 | # Replace raw_input. Note that is not sufficient to replace | |
195 | # raw_input in the user namespace. |
|
195 | # raw_input in the user namespace. | |
196 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) |
|
196 | raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) | |
197 | __builtin__.raw_input = raw_input |
|
197 | __builtin__.raw_input = raw_input | |
198 |
|
198 | |||
199 | # Set the parent message of the display hook and out streams. |
|
199 | # Set the parent message of the display hook and out streams. | |
200 | shell.displayhook.set_parent(parent) |
|
200 | shell.displayhook.set_parent(parent) | |
201 | sys.stdout.set_parent(parent) |
|
201 | sys.stdout.set_parent(parent) | |
202 | sys.stderr.set_parent(parent) |
|
202 | sys.stderr.set_parent(parent) | |
203 |
|
203 | |||
204 | # Re-broadcast our input for the benefit of listening clients, and |
|
204 | # Re-broadcast our input for the benefit of listening clients, and | |
205 | # start computing output |
|
205 | # start computing output | |
206 | if not silent: |
|
206 | if not silent: | |
207 | self._publish_pyin(code, parent) |
|
207 | self._publish_pyin(code, parent) | |
208 |
|
208 | |||
209 | reply_content = {} |
|
209 | reply_content = {} | |
210 | try: |
|
210 | try: | |
211 | if silent: |
|
211 | if silent: | |
212 | # runcode uses 'exec' mode, so no displayhook will fire, and it |
|
212 | # run_code uses 'exec' mode, so no displayhook will fire, and it | |
213 | # doesn't call logging or history manipulations. Print |
|
213 | # doesn't call logging or history manipulations. Print | |
214 | # statements in that code will obviously still execute. |
|
214 | # statements in that code will obviously still execute. | |
215 | shell.runcode(code) |
|
215 | shell.run_code(code) | |
216 | else: |
|
216 | else: | |
217 |
# FIXME: |
|
217 | # FIXME: the shell calls the exception handler itself. | |
218 | shell._reply_content = None |
|
218 | shell._reply_content = None | |
219 |
|
||||
220 | # For now leave this here until we're sure we can stop using it |
|
|||
221 | #shell.runlines(code) |
|
|||
222 |
|
||||
223 | # Experimental: cell mode! Test more before turning into |
|
|||
224 | # default and removing the hacks around runlines. |
|
|||
225 | shell.run_cell(code) |
|
219 | shell.run_cell(code) | |
226 | except: |
|
220 | except: | |
227 | status = u'error' |
|
221 | status = u'error' | |
228 | # FIXME: this code right now isn't being used yet by default, |
|
222 | # FIXME: this code right now isn't being used yet by default, | |
229 | # because the runlines() call above directly fires off exception |
|
223 | # because the runlines() call above directly fires off exception | |
230 | # reporting. This code, therefore, is only active in the scenario |
|
224 | # reporting. This code, therefore, is only active in the scenario | |
231 | # where runlines itself has an unhandled exception. We need to |
|
225 | # where runlines itself has an unhandled exception. We need to | |
232 | # uniformize this, for all exception construction to come from a |
|
226 | # uniformize this, for all exception construction to come from a | |
233 | # single location in the codbase. |
|
227 | # single location in the codbase. | |
234 | etype, evalue, tb = sys.exc_info() |
|
228 | etype, evalue, tb = sys.exc_info() | |
235 | tb_list = traceback.format_exception(etype, evalue, tb) |
|
229 | tb_list = traceback.format_exception(etype, evalue, tb) | |
236 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) |
|
230 | reply_content.update(shell._showtraceback(etype, evalue, tb_list)) | |
237 | else: |
|
231 | else: | |
238 | status = u'ok' |
|
232 | status = u'ok' | |
239 |
|
233 | |||
240 | reply_content[u'status'] = status |
|
234 | reply_content[u'status'] = status | |
241 | # Compute the execution counter so clients can display prompts |
|
235 | ||
242 | reply_content['execution_count'] = shell.displayhook.prompt_count |
|
236 | # Return the execution counter so clients can display prompts | |
|
237 | reply_content['execution_count'] = shell.execution_count -1 | |||
243 |
|
238 | |||
244 | # FIXME - fish exception info out of shell, possibly left there by |
|
239 | # FIXME - fish exception info out of shell, possibly left there by | |
245 | # runlines. We'll need to clean up this logic later. |
|
240 | # runlines. We'll need to clean up this logic later. | |
246 | if shell._reply_content is not None: |
|
241 | if shell._reply_content is not None: | |
247 | reply_content.update(shell._reply_content) |
|
242 | reply_content.update(shell._reply_content) | |
248 |
|
243 | |||
249 | # At this point, we can tell whether the main code execution succeeded |
|
244 | # At this point, we can tell whether the main code execution succeeded | |
250 | # or not. If it did, we proceed to evaluate user_variables/expressions |
|
245 | # or not. If it did, we proceed to evaluate user_variables/expressions | |
251 | if reply_content['status'] == 'ok': |
|
246 | if reply_content['status'] == 'ok': | |
252 | reply_content[u'user_variables'] = \ |
|
247 | reply_content[u'user_variables'] = \ | |
253 | shell.user_variables(content[u'user_variables']) |
|
248 | shell.user_variables(content[u'user_variables']) | |
254 | reply_content[u'user_expressions'] = \ |
|
249 | reply_content[u'user_expressions'] = \ | |
255 | shell.user_expressions(content[u'user_expressions']) |
|
250 | shell.user_expressions(content[u'user_expressions']) | |
256 | else: |
|
251 | else: | |
257 | # If there was an error, don't even try to compute variables or |
|
252 | # If there was an error, don't even try to compute variables or | |
258 | # expressions |
|
253 | # expressions | |
259 | reply_content[u'user_variables'] = {} |
|
254 | reply_content[u'user_variables'] = {} | |
260 | reply_content[u'user_expressions'] = {} |
|
255 | reply_content[u'user_expressions'] = {} | |
261 |
|
256 | |||
262 | # Payloads should be retrieved regardless of outcome, so we can both |
|
257 | # Payloads should be retrieved regardless of outcome, so we can both | |
263 | # recover partial output (that could have been generated early in a |
|
258 | # recover partial output (that could have been generated early in a | |
264 | # block, before an error) and clear the payload system always. |
|
259 | # block, before an error) and clear the payload system always. | |
265 | reply_content[u'payload'] = shell.payload_manager.read_payload() |
|
260 | reply_content[u'payload'] = shell.payload_manager.read_payload() | |
266 | # Be agressive about clearing the payload because we don't want |
|
261 | # Be agressive about clearing the payload because we don't want | |
267 | # it to sit in memory until the next execute_request comes in. |
|
262 | # it to sit in memory until the next execute_request comes in. | |
268 | shell.payload_manager.clear_payload() |
|
263 | shell.payload_manager.clear_payload() | |
269 |
|
264 | |||
270 | # Send the reply. |
|
265 | # Send the reply. | |
271 | reply_msg = self.session.msg(u'execute_reply', reply_content, parent) |
|
266 | reply_msg = self.session.msg(u'execute_reply', reply_content, parent) | |
272 | io.raw_print(reply_msg) |
|
267 | io.raw_print(reply_msg) | |
273 |
|
268 | |||
274 | # Flush output before sending the reply. |
|
269 | # Flush output before sending the reply. | |
275 | sys.stdout.flush() |
|
270 | sys.stdout.flush() | |
276 | sys.stderr.flush() |
|
271 | sys.stderr.flush() | |
277 | # FIXME: on rare occasions, the flush doesn't seem to make it to the |
|
272 | # FIXME: on rare occasions, the flush doesn't seem to make it to the | |
278 | # clients... This seems to mitigate the problem, but we definitely need |
|
273 | # clients... This seems to mitigate the problem, but we definitely need | |
279 | # to better understand what's going on. |
|
274 | # to better understand what's going on. | |
280 | if self._execute_sleep: |
|
275 | if self._execute_sleep: | |
281 | time.sleep(self._execute_sleep) |
|
276 | time.sleep(self._execute_sleep) | |
282 |
|
277 | |||
283 | self.reply_socket.send(ident, zmq.SNDMORE) |
|
278 | self.reply_socket.send(ident, zmq.SNDMORE) | |
284 | self.reply_socket.send_json(reply_msg) |
|
279 | self.reply_socket.send_json(reply_msg) | |
285 | if reply_msg['content']['status'] == u'error': |
|
280 | if reply_msg['content']['status'] == u'error': | |
286 | self._abort_queue() |
|
281 | self._abort_queue() | |
287 |
|
282 | |||
288 | status_msg = self.session.msg( |
|
283 | status_msg = self.session.msg( | |
289 | u'status', |
|
284 | u'status', | |
290 | {u'execution_state':u'idle'}, |
|
285 | {u'execution_state':u'idle'}, | |
291 | parent=parent |
|
286 | parent=parent | |
292 | ) |
|
287 | ) | |
293 | self.pub_socket.send_json(status_msg) |
|
288 | self.pub_socket.send_json(status_msg) | |
294 |
|
289 | |||
295 | def complete_request(self, ident, parent): |
|
290 | def complete_request(self, ident, parent): | |
296 | txt, matches = self._complete(parent) |
|
291 | txt, matches = self._complete(parent) | |
297 | matches = {'matches' : matches, |
|
292 | matches = {'matches' : matches, | |
298 | 'matched_text' : txt, |
|
293 | 'matched_text' : txt, | |
299 | 'status' : 'ok'} |
|
294 | 'status' : 'ok'} | |
300 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', |
|
295 | completion_msg = self.session.send(self.reply_socket, 'complete_reply', | |
301 | matches, parent, ident) |
|
296 | matches, parent, ident) | |
302 | io.raw_print(completion_msg) |
|
297 | io.raw_print(completion_msg) | |
303 |
|
298 | |||
304 | def object_info_request(self, ident, parent): |
|
299 | def object_info_request(self, ident, parent): | |
305 | object_info = self.shell.object_inspect(parent['content']['oname']) |
|
300 | object_info = self.shell.object_inspect(parent['content']['oname']) | |
306 | # Before we send this object over, we scrub it for JSON usage |
|
301 | # Before we send this object over, we scrub it for JSON usage | |
307 | oinfo = json_clean(object_info) |
|
302 | oinfo = json_clean(object_info) | |
308 | msg = self.session.send(self.reply_socket, 'object_info_reply', |
|
303 | msg = self.session.send(self.reply_socket, 'object_info_reply', | |
309 | oinfo, parent, ident) |
|
304 | oinfo, parent, ident) | |
310 | io.raw_print(msg) |
|
305 | io.raw_print(msg) | |
311 |
|
306 | |||
312 | def history_request(self, ident, parent): |
|
307 | def history_request(self, ident, parent): | |
313 | output = parent['content']['output'] |
|
308 | output = parent['content']['output'] | |
314 | index = parent['content']['index'] |
|
309 | index = parent['content']['index'] | |
315 | raw = parent['content']['raw'] |
|
310 | raw = parent['content']['raw'] | |
316 | hist = self.shell.get_history(index=index, raw=raw, output=output) |
|
311 | hist = self.shell.get_history(index=index, raw=raw, output=output) | |
317 | content = {'history' : hist} |
|
312 | content = {'history' : hist} | |
318 | msg = self.session.send(self.reply_socket, 'history_reply', |
|
313 | msg = self.session.send(self.reply_socket, 'history_reply', | |
319 | content, parent, ident) |
|
314 | content, parent, ident) | |
320 | io.raw_print(msg) |
|
315 | io.raw_print(msg) | |
321 |
|
316 | |||
322 | def connect_request(self, ident, parent): |
|
317 | def connect_request(self, ident, parent): | |
323 | if self._recorded_ports is not None: |
|
318 | if self._recorded_ports is not None: | |
324 | content = self._recorded_ports.copy() |
|
319 | content = self._recorded_ports.copy() | |
325 | else: |
|
320 | else: | |
326 | content = {} |
|
321 | content = {} | |
327 | msg = self.session.send(self.reply_socket, 'connect_reply', |
|
322 | msg = self.session.send(self.reply_socket, 'connect_reply', | |
328 | content, parent, ident) |
|
323 | content, parent, ident) | |
329 | io.raw_print(msg) |
|
324 | io.raw_print(msg) | |
330 |
|
325 | |||
331 | def shutdown_request(self, ident, parent): |
|
326 | def shutdown_request(self, ident, parent): | |
332 | self.shell.exit_now = True |
|
327 | self.shell.exit_now = True | |
333 | self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent) |
|
328 | self._shutdown_message = self.session.msg(u'shutdown_reply', parent['content'], parent) | |
334 | sys.exit(0) |
|
329 | sys.exit(0) | |
335 |
|
330 | |||
336 | #--------------------------------------------------------------------------- |
|
331 | #--------------------------------------------------------------------------- | |
337 | # Protected interface |
|
332 | # Protected interface | |
338 | #--------------------------------------------------------------------------- |
|
333 | #--------------------------------------------------------------------------- | |
339 |
|
334 | |||
340 | def _abort_queue(self): |
|
335 | def _abort_queue(self): | |
341 | while True: |
|
336 | while True: | |
342 | try: |
|
337 | try: | |
343 | ident = self.reply_socket.recv(zmq.NOBLOCK) |
|
338 | ident = self.reply_socket.recv(zmq.NOBLOCK) | |
344 | except zmq.ZMQError, e: |
|
339 | except zmq.ZMQError, e: | |
345 | if e.errno == zmq.EAGAIN: |
|
340 | if e.errno == zmq.EAGAIN: | |
346 | break |
|
341 | break | |
347 | else: |
|
342 | else: | |
348 | assert self.reply_socket.rcvmore(), \ |
|
343 | assert self.reply_socket.rcvmore(), \ | |
349 | "Unexpected missing message part." |
|
344 | "Unexpected missing message part." | |
350 | msg = self.reply_socket.recv_json() |
|
345 | msg = self.reply_socket.recv_json() | |
351 | io.raw_print("Aborting:\n", Message(msg)) |
|
346 | io.raw_print("Aborting:\n", Message(msg)) | |
352 | msg_type = msg['msg_type'] |
|
347 | msg_type = msg['msg_type'] | |
353 | reply_type = msg_type.split('_')[0] + '_reply' |
|
348 | reply_type = msg_type.split('_')[0] + '_reply' | |
354 | reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) |
|
349 | reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg) | |
355 | io.raw_print(reply_msg) |
|
350 | io.raw_print(reply_msg) | |
356 | self.reply_socket.send(ident,zmq.SNDMORE) |
|
351 | self.reply_socket.send(ident,zmq.SNDMORE) | |
357 | self.reply_socket.send_json(reply_msg) |
|
352 | self.reply_socket.send_json(reply_msg) | |
358 | # We need to wait a bit for requests to come in. This can probably |
|
353 | # We need to wait a bit for requests to come in. This can probably | |
359 | # be set shorter for true asynchronous clients. |
|
354 | # be set shorter for true asynchronous clients. | |
360 | time.sleep(0.1) |
|
355 | time.sleep(0.1) | |
361 |
|
356 | |||
362 | def _raw_input(self, prompt, ident, parent): |
|
357 | def _raw_input(self, prompt, ident, parent): | |
363 | # Flush output before making the request. |
|
358 | # Flush output before making the request. | |
364 | sys.stderr.flush() |
|
359 | sys.stderr.flush() | |
365 | sys.stdout.flush() |
|
360 | sys.stdout.flush() | |
366 |
|
361 | |||
367 | # Send the input request. |
|
362 | # Send the input request. | |
368 | content = dict(prompt=prompt) |
|
363 | content = dict(prompt=prompt) | |
369 | msg = self.session.msg(u'input_request', content, parent) |
|
364 | msg = self.session.msg(u'input_request', content, parent) | |
370 | self.req_socket.send_json(msg) |
|
365 | self.req_socket.send_json(msg) | |
371 |
|
366 | |||
372 | # Await a response. |
|
367 | # Await a response. | |
373 | reply = self.req_socket.recv_json() |
|
368 | reply = self.req_socket.recv_json() | |
374 | try: |
|
369 | try: | |
375 | value = reply['content']['value'] |
|
370 | value = reply['content']['value'] | |
376 | except: |
|
371 | except: | |
377 | io.raw_print_err("Got bad raw_input reply: ") |
|
372 | io.raw_print_err("Got bad raw_input reply: ") | |
378 | io.raw_print_err(Message(parent)) |
|
373 | io.raw_print_err(Message(parent)) | |
379 | value = '' |
|
374 | value = '' | |
380 | return value |
|
375 | return value | |
381 |
|
376 | |||
382 | def _complete(self, msg): |
|
377 | def _complete(self, msg): | |
383 | c = msg['content'] |
|
378 | c = msg['content'] | |
384 | try: |
|
379 | try: | |
385 | cpos = int(c['cursor_pos']) |
|
380 | cpos = int(c['cursor_pos']) | |
386 | except: |
|
381 | except: | |
387 | # If we don't get something that we can convert to an integer, at |
|
382 | # If we don't get something that we can convert to an integer, at | |
388 | # least attempt the completion guessing the cursor is at the end of |
|
383 | # least attempt the completion guessing the cursor is at the end of | |
389 | # the text, if there's any, and otherwise of the line |
|
384 | # the text, if there's any, and otherwise of the line | |
390 | cpos = len(c['text']) |
|
385 | cpos = len(c['text']) | |
391 | if cpos==0: |
|
386 | if cpos==0: | |
392 | cpos = len(c['line']) |
|
387 | cpos = len(c['line']) | |
393 | return self.shell.complete(c['text'], c['line'], cpos) |
|
388 | return self.shell.complete(c['text'], c['line'], cpos) | |
394 |
|
389 | |||
395 | def _object_info(self, context): |
|
390 | def _object_info(self, context): | |
396 | symbol, leftover = self._symbol_from_context(context) |
|
391 | symbol, leftover = self._symbol_from_context(context) | |
397 | if symbol is not None and not leftover: |
|
392 | if symbol is not None and not leftover: | |
398 | doc = getattr(symbol, '__doc__', '') |
|
393 | doc = getattr(symbol, '__doc__', '') | |
399 | else: |
|
394 | else: | |
400 | doc = '' |
|
395 | doc = '' | |
401 | object_info = dict(docstring = doc) |
|
396 | object_info = dict(docstring = doc) | |
402 | return object_info |
|
397 | return object_info | |
403 |
|
398 | |||
404 | def _symbol_from_context(self, context): |
|
399 | def _symbol_from_context(self, context): | |
405 | if not context: |
|
400 | if not context: | |
406 | return None, context |
|
401 | return None, context | |
407 |
|
402 | |||
408 | base_symbol_string = context[0] |
|
403 | base_symbol_string = context[0] | |
409 | symbol = self.shell.user_ns.get(base_symbol_string, None) |
|
404 | symbol = self.shell.user_ns.get(base_symbol_string, None) | |
410 | if symbol is None: |
|
405 | if symbol is None: | |
411 | symbol = __builtin__.__dict__.get(base_symbol_string, None) |
|
406 | symbol = __builtin__.__dict__.get(base_symbol_string, None) | |
412 | if symbol is None: |
|
407 | if symbol is None: | |
413 | return None, context |
|
408 | return None, context | |
414 |
|
409 | |||
415 | context = context[1:] |
|
410 | context = context[1:] | |
416 | for i, name in enumerate(context): |
|
411 | for i, name in enumerate(context): | |
417 | new_symbol = getattr(symbol, name, None) |
|
412 | new_symbol = getattr(symbol, name, None) | |
418 | if new_symbol is None: |
|
413 | if new_symbol is None: | |
419 | return symbol, context[i:] |
|
414 | return symbol, context[i:] | |
420 | else: |
|
415 | else: | |
421 | symbol = new_symbol |
|
416 | symbol = new_symbol | |
422 |
|
417 | |||
423 | return symbol, [] |
|
418 | return symbol, [] | |
424 |
|
419 | |||
425 | def _at_shutdown(self): |
|
420 | def _at_shutdown(self): | |
426 | """Actions taken at shutdown by the kernel, called by python's atexit. |
|
421 | """Actions taken at shutdown by the kernel, called by python's atexit. | |
427 | """ |
|
422 | """ | |
428 | # io.rprint("Kernel at_shutdown") # dbg |
|
423 | # io.rprint("Kernel at_shutdown") # dbg | |
429 | if self._shutdown_message is not None: |
|
424 | if self._shutdown_message is not None: | |
430 | self.reply_socket.send_json(self._shutdown_message) |
|
425 | self.reply_socket.send_json(self._shutdown_message) | |
431 | self.pub_socket.send_json(self._shutdown_message) |
|
426 | self.pub_socket.send_json(self._shutdown_message) | |
432 | io.raw_print(self._shutdown_message) |
|
427 | io.raw_print(self._shutdown_message) | |
433 | # A very short sleep to give zmq time to flush its message buffers |
|
428 | # A very short sleep to give zmq time to flush its message buffers | |
434 | # before Python truly shuts down. |
|
429 | # before Python truly shuts down. | |
435 | time.sleep(0.01) |
|
430 | time.sleep(0.01) | |
436 |
|
431 | |||
437 |
|
432 | |||
438 | class QtKernel(Kernel): |
|
433 | class QtKernel(Kernel): | |
439 | """A Kernel subclass with Qt support.""" |
|
434 | """A Kernel subclass with Qt support.""" | |
440 |
|
435 | |||
441 | def start(self): |
|
436 | def start(self): | |
442 | """Start a kernel with QtPy4 event loop integration.""" |
|
437 | """Start a kernel with QtPy4 event loop integration.""" | |
443 |
|
438 | |||
444 | from PyQt4 import QtCore |
|
439 | from PyQt4 import QtCore | |
445 | from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 |
|
440 | from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4 | |
446 |
|
441 | |||
447 | self.app = get_app_qt4([" "]) |
|
442 | self.app = get_app_qt4([" "]) | |
448 | self.app.setQuitOnLastWindowClosed(False) |
|
443 | self.app.setQuitOnLastWindowClosed(False) | |
449 | self.timer = QtCore.QTimer() |
|
444 | self.timer = QtCore.QTimer() | |
450 | self.timer.timeout.connect(self.do_one_iteration) |
|
445 | self.timer.timeout.connect(self.do_one_iteration) | |
451 | # Units for the timer are in milliseconds |
|
446 | # Units for the timer are in milliseconds | |
452 | self.timer.start(1000*self._poll_interval) |
|
447 | self.timer.start(1000*self._poll_interval) | |
453 | start_event_loop_qt4(self.app) |
|
448 | start_event_loop_qt4(self.app) | |
454 |
|
449 | |||
455 |
|
450 | |||
456 | class WxKernel(Kernel): |
|
451 | class WxKernel(Kernel): | |
457 | """A Kernel subclass with Wx support.""" |
|
452 | """A Kernel subclass with Wx support.""" | |
458 |
|
453 | |||
459 | def start(self): |
|
454 | def start(self): | |
460 | """Start a kernel with wx event loop support.""" |
|
455 | """Start a kernel with wx event loop support.""" | |
461 |
|
456 | |||
462 | import wx |
|
457 | import wx | |
463 | from IPython.lib.guisupport import start_event_loop_wx |
|
458 | from IPython.lib.guisupport import start_event_loop_wx | |
464 |
|
459 | |||
465 | doi = self.do_one_iteration |
|
460 | doi = self.do_one_iteration | |
466 | # Wx uses milliseconds |
|
461 | # Wx uses milliseconds | |
467 | poll_interval = int(1000*self._poll_interval) |
|
462 | poll_interval = int(1000*self._poll_interval) | |
468 |
|
463 | |||
469 | # We have to put the wx.Timer in a wx.Frame for it to fire properly. |
|
464 | # We have to put the wx.Timer in a wx.Frame for it to fire properly. | |
470 | # We make the Frame hidden when we create it in the main app below. |
|
465 | # We make the Frame hidden when we create it in the main app below. | |
471 | class TimerFrame(wx.Frame): |
|
466 | class TimerFrame(wx.Frame): | |
472 | def __init__(self, func): |
|
467 | def __init__(self, func): | |
473 | wx.Frame.__init__(self, None, -1) |
|
468 | wx.Frame.__init__(self, None, -1) | |
474 | self.timer = wx.Timer(self) |
|
469 | self.timer = wx.Timer(self) | |
475 | # Units for the timer are in milliseconds |
|
470 | # Units for the timer are in milliseconds | |
476 | self.timer.Start(poll_interval) |
|
471 | self.timer.Start(poll_interval) | |
477 | self.Bind(wx.EVT_TIMER, self.on_timer) |
|
472 | self.Bind(wx.EVT_TIMER, self.on_timer) | |
478 | self.func = func |
|
473 | self.func = func | |
479 |
|
474 | |||
480 | def on_timer(self, event): |
|
475 | def on_timer(self, event): | |
481 | self.func() |
|
476 | self.func() | |
482 |
|
477 | |||
483 | # We need a custom wx.App to create our Frame subclass that has the |
|
478 | # We need a custom wx.App to create our Frame subclass that has the | |
484 | # wx.Timer to drive the ZMQ event loop. |
|
479 | # wx.Timer to drive the ZMQ event loop. | |
485 | class IPWxApp(wx.App): |
|
480 | class IPWxApp(wx.App): | |
486 | def OnInit(self): |
|
481 | def OnInit(self): | |
487 | self.frame = TimerFrame(doi) |
|
482 | self.frame = TimerFrame(doi) | |
488 | self.frame.Show(False) |
|
483 | self.frame.Show(False) | |
489 | return True |
|
484 | return True | |
490 |
|
485 | |||
491 | # The redirect=False here makes sure that wx doesn't replace |
|
486 | # The redirect=False here makes sure that wx doesn't replace | |
492 | # sys.stdout/stderr with its own classes. |
|
487 | # sys.stdout/stderr with its own classes. | |
493 | self.app = IPWxApp(redirect=False) |
|
488 | self.app = IPWxApp(redirect=False) | |
494 | start_event_loop_wx(self.app) |
|
489 | start_event_loop_wx(self.app) | |
495 |
|
490 | |||
496 |
|
491 | |||
497 | class TkKernel(Kernel): |
|
492 | class TkKernel(Kernel): | |
498 | """A Kernel subclass with Tk support.""" |
|
493 | """A Kernel subclass with Tk support.""" | |
499 |
|
494 | |||
500 | def start(self): |
|
495 | def start(self): | |
501 | """Start a Tk enabled event loop.""" |
|
496 | """Start a Tk enabled event loop.""" | |
502 |
|
497 | |||
503 | import Tkinter |
|
498 | import Tkinter | |
504 | doi = self.do_one_iteration |
|
499 | doi = self.do_one_iteration | |
505 | # Tk uses milliseconds |
|
500 | # Tk uses milliseconds | |
506 | poll_interval = int(1000*self._poll_interval) |
|
501 | poll_interval = int(1000*self._poll_interval) | |
507 | # For Tkinter, we create a Tk object and call its withdraw method. |
|
502 | # For Tkinter, we create a Tk object and call its withdraw method. | |
508 | class Timer(object): |
|
503 | class Timer(object): | |
509 | def __init__(self, func): |
|
504 | def __init__(self, func): | |
510 | self.app = Tkinter.Tk() |
|
505 | self.app = Tkinter.Tk() | |
511 | self.app.withdraw() |
|
506 | self.app.withdraw() | |
512 | self.func = func |
|
507 | self.func = func | |
513 |
|
508 | |||
514 | def on_timer(self): |
|
509 | def on_timer(self): | |
515 | self.func() |
|
510 | self.func() | |
516 | self.app.after(poll_interval, self.on_timer) |
|
511 | self.app.after(poll_interval, self.on_timer) | |
517 |
|
512 | |||
518 | def start(self): |
|
513 | def start(self): | |
519 | self.on_timer() # Call it once to get things going. |
|
514 | self.on_timer() # Call it once to get things going. | |
520 | self.app.mainloop() |
|
515 | self.app.mainloop() | |
521 |
|
516 | |||
522 | self.timer = Timer(doi) |
|
517 | self.timer = Timer(doi) | |
523 | self.timer.start() |
|
518 | self.timer.start() | |
524 |
|
519 | |||
525 |
|
520 | |||
526 | class GTKKernel(Kernel): |
|
521 | class GTKKernel(Kernel): | |
527 | """A Kernel subclass with GTK support.""" |
|
522 | """A Kernel subclass with GTK support.""" | |
528 |
|
523 | |||
529 | def start(self): |
|
524 | def start(self): | |
530 | """Start the kernel, coordinating with the GTK event loop""" |
|
525 | """Start the kernel, coordinating with the GTK event loop""" | |
531 | from .gui.gtkembed import GTKEmbed |
|
526 | from .gui.gtkembed import GTKEmbed | |
532 |
|
527 | |||
533 | gtk_kernel = GTKEmbed(self) |
|
528 | gtk_kernel = GTKEmbed(self) | |
534 | gtk_kernel.start() |
|
529 | gtk_kernel.start() | |
535 |
|
530 | |||
536 |
|
531 | |||
537 | #----------------------------------------------------------------------------- |
|
532 | #----------------------------------------------------------------------------- | |
538 | # Kernel main and launch functions |
|
533 | # Kernel main and launch functions | |
539 | #----------------------------------------------------------------------------- |
|
534 | #----------------------------------------------------------------------------- | |
540 |
|
535 | |||
541 | def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0, |
|
536 | def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0, | |
542 | independent=False, pylab=False): |
|
537 | independent=False, pylab=False): | |
543 | """Launches a localhost kernel, binding to the specified ports. |
|
538 | """Launches a localhost kernel, binding to the specified ports. | |
544 |
|
539 | |||
545 | Parameters |
|
540 | Parameters | |
546 | ---------- |
|
541 | ---------- | |
547 | xrep_port : int, optional |
|
542 | xrep_port : int, optional | |
548 | The port to use for XREP channel. |
|
543 | The port to use for XREP channel. | |
549 |
|
544 | |||
550 | pub_port : int, optional |
|
545 | pub_port : int, optional | |
551 | The port to use for the SUB channel. |
|
546 | The port to use for the SUB channel. | |
552 |
|
547 | |||
553 | req_port : int, optional |
|
548 | req_port : int, optional | |
554 | The port to use for the REQ (raw input) channel. |
|
549 | The port to use for the REQ (raw input) channel. | |
555 |
|
550 | |||
556 | hb_port : int, optional |
|
551 | hb_port : int, optional | |
557 | The port to use for the hearbeat REP channel. |
|
552 | The port to use for the hearbeat REP channel. | |
558 |
|
553 | |||
559 | independent : bool, optional (default False) |
|
554 | independent : bool, optional (default False) | |
560 | If set, the kernel process is guaranteed to survive if this process |
|
555 | If set, the kernel process is guaranteed to survive if this process | |
561 | dies. If not set, an effort is made to ensure that the kernel is killed |
|
556 | dies. If not set, an effort is made to ensure that the kernel is killed | |
562 | when this process dies. Note that in this case it is still good practice |
|
557 | when this process dies. Note that in this case it is still good practice | |
563 | to kill kernels manually before exiting. |
|
558 | to kill kernels manually before exiting. | |
564 |
|
559 | |||
565 | pylab : bool or string, optional (default False) |
|
560 | pylab : bool or string, optional (default False) | |
566 | If not False, the kernel will be launched with pylab enabled. If a |
|
561 | If not False, the kernel will be launched with pylab enabled. If a | |
567 | string is passed, matplotlib will use the specified backend. Otherwise, |
|
562 | string is passed, matplotlib will use the specified backend. Otherwise, | |
568 | matplotlib's default backend will be used. |
|
563 | matplotlib's default backend will be used. | |
569 |
|
564 | |||
570 | Returns |
|
565 | Returns | |
571 | ------- |
|
566 | ------- | |
572 | A tuple of form: |
|
567 | A tuple of form: | |
573 | (kernel_process, xrep_port, pub_port, req_port) |
|
568 | (kernel_process, xrep_port, pub_port, req_port) | |
574 | where kernel_process is a Popen object and the ports are integers. |
|
569 | where kernel_process is a Popen object and the ports are integers. | |
575 | """ |
|
570 | """ | |
576 | extra_arguments = [] |
|
571 | extra_arguments = [] | |
577 | if pylab: |
|
572 | if pylab: | |
578 | extra_arguments.append('--pylab') |
|
573 | extra_arguments.append('--pylab') | |
579 | if isinstance(pylab, basestring): |
|
574 | if isinstance(pylab, basestring): | |
580 | extra_arguments.append(pylab) |
|
575 | extra_arguments.append(pylab) | |
581 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', |
|
576 | return base_launch_kernel('from IPython.zmq.ipkernel import main; main()', | |
582 | xrep_port, pub_port, req_port, hb_port, |
|
577 | xrep_port, pub_port, req_port, hb_port, | |
583 | independent, extra_arguments) |
|
578 | independent, extra_arguments) | |
584 |
|
579 | |||
585 |
|
580 | |||
586 | def main(): |
|
581 | def main(): | |
587 | """ The IPython kernel main entry point. |
|
582 | """ The IPython kernel main entry point. | |
588 | """ |
|
583 | """ | |
589 | parser = make_argument_parser() |
|
584 | parser = make_argument_parser() | |
590 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', |
|
585 | parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?', | |
591 | const='auto', help = \ |
|
586 | const='auto', help = \ | |
592 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ |
|
587 | "Pre-load matplotlib and numpy for interactive use. If GUI is not \ | |
593 | given, the GUI backend is matplotlib's, otherwise use one of: \ |
|
588 | given, the GUI backend is matplotlib's, otherwise use one of: \ | |
594 | ['tk', 'gtk', 'qt', 'wx', 'inline'].") |
|
589 | ['tk', 'gtk', 'qt', 'wx', 'inline'].") | |
595 | namespace = parser.parse_args() |
|
590 | namespace = parser.parse_args() | |
596 |
|
591 | |||
597 | kernel_class = Kernel |
|
592 | kernel_class = Kernel | |
598 |
|
593 | |||
599 | kernel_classes = { |
|
594 | kernel_classes = { | |
600 | 'qt' : QtKernel, |
|
595 | 'qt' : QtKernel, | |
601 | 'qt4': QtKernel, |
|
596 | 'qt4': QtKernel, | |
602 | 'inline': Kernel, |
|
597 | 'inline': Kernel, | |
603 | 'wx' : WxKernel, |
|
598 | 'wx' : WxKernel, | |
604 | 'tk' : TkKernel, |
|
599 | 'tk' : TkKernel, | |
605 | 'gtk': GTKKernel, |
|
600 | 'gtk': GTKKernel, | |
606 | } |
|
601 | } | |
607 | if namespace.pylab: |
|
602 | if namespace.pylab: | |
608 | if namespace.pylab == 'auto': |
|
603 | if namespace.pylab == 'auto': | |
609 | gui, backend = pylabtools.find_gui_and_backend() |
|
604 | gui, backend = pylabtools.find_gui_and_backend() | |
610 | else: |
|
605 | else: | |
611 | gui, backend = pylabtools.find_gui_and_backend(namespace.pylab) |
|
606 | gui, backend = pylabtools.find_gui_and_backend(namespace.pylab) | |
612 | kernel_class = kernel_classes.get(gui) |
|
607 | kernel_class = kernel_classes.get(gui) | |
613 | if kernel_class is None: |
|
608 | if kernel_class is None: | |
614 | raise ValueError('GUI is not supported: %r' % gui) |
|
609 | raise ValueError('GUI is not supported: %r' % gui) | |
615 | pylabtools.activate_matplotlib(backend) |
|
610 | pylabtools.activate_matplotlib(backend) | |
616 |
|
611 | |||
617 | kernel = make_kernel(namespace, kernel_class, OutStream) |
|
612 | kernel = make_kernel(namespace, kernel_class, OutStream) | |
618 |
|
613 | |||
619 | if namespace.pylab: |
|
614 | if namespace.pylab: | |
620 | pylabtools.import_pylab(kernel.shell.user_ns, backend, |
|
615 | pylabtools.import_pylab(kernel.shell.user_ns, backend, | |
621 | shell=kernel.shell) |
|
616 | shell=kernel.shell) | |
622 |
|
617 | |||
623 | start_kernel(namespace, kernel) |
|
618 | start_kernel(namespace, kernel) | |
624 |
|
619 | |||
625 |
|
620 | |||
626 | if __name__ == '__main__': |
|
621 | if __name__ == '__main__': | |
627 | main() |
|
622 | main() |
General Comments 0
You need to be logged in to leave comments.
Login now