##// END OF EJS Templates
Refactor of prompts and the displayhook....
Brian Granger -
Show More
@@ -0,0 +1,284 b''
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
3
4 Authors:
5
6 * Fernando Perez
7 * Brian Granger
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2010 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22 import __builtin__
23 from pprint import PrettyPrinter
24 pformat = PrettyPrinter().pformat
25
26 from IPython.config.configurable import Configurable
27 from IPython.core import prompts
28 import IPython.utils.generics
29 import IPython.utils.io
30 from IPython.utils.traitlets import Instance
31 from IPython.utils.warn import warn
32
33 #-----------------------------------------------------------------------------
34 # Main displayhook class
35 #-----------------------------------------------------------------------------
36
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
39 # displayhook logic and calls into the prompt manager.
40
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
43 # attributes of InteractiveShell. They should be on ONE object only and the
44 # other objects should ask that one object for their values.
45
46 class DisplayHook(Configurable):
47 """The custom IPython displayhook to replace sys.displayhook.
48
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.
51
52 Currently this class does more than just the displayhook logic and that
53 extra logic should eventually be moved out of here.
54 """
55
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57
58 def __init__(self, shell=None, cache_size=1000,
59 colors='NoColor', input_sep='\n',
60 output_sep='\n', output_sep2='',
61 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
62 config=None):
63 super(DisplayHook, self).__init__(shell=shell, config=config)
64
65 cache_size_min = 3
66 if cache_size <= 0:
67 self.do_full_cache = 0
68 cache_size = 0
69 elif cache_size < cache_size_min:
70 self.do_full_cache = 0
71 cache_size = 0
72 warn('caching was disabled (min value for cache size is %s).' %
73 cache_size_min,level=3)
74 else:
75 self.do_full_cache = 1
76
77 self.cache_size = cache_size
78 self.input_sep = input_sep
79
80 # we need a reference to the user-level namespace
81 self.shell = shell
82
83 # Set input prompt strings and colors
84 if cache_size == 0:
85 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
86 or ps1.find(r'\N') > -1:
87 ps1 = '>>> '
88 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
89 or ps2.find(r'\N') > -1:
90 ps2 = '... '
91 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
92 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
93 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
94
95 self.color_table = prompts.PromptColors
96 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
97 pad_left=pad_left)
98 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
99 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
100 pad_left=pad_left)
101 self.set_colors(colors)
102
103 # other more normal stuff
104 # b/c each call to the In[] prompt raises it by 1, even the first.
105 self.prompt_count = 0
106 # Store the last prompt string each time, we need it for aligning
107 # continuation and auto-rewrite prompts
108 self.last_prompt = ''
109 self.output_sep = output_sep
110 self.output_sep2 = output_sep2
111 self._,self.__,self.___ = '','',''
112 self.pprint_types = map(type,[(),[],{}])
113
114 # these are deliberately global:
115 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
116 self.shell.user_ns.update(to_user_ns)
117
118 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
119 if p_str is None:
120 if self.do_full_cache:
121 return cache_def
122 else:
123 return no_cache_def
124 else:
125 return p_str
126
127 def set_colors(self, colors):
128 """Set the active color scheme and configure colors for the three
129 prompt subsystems."""
130
131 # FIXME: This modifying of the global prompts.prompt_specials needs
132 # to be fixed. We need to refactor all of the prompts stuff to use
133 # proper configuration and traits notifications.
134 if colors.lower()=='nocolor':
135 prompts.prompt_specials = prompts.prompt_specials_nocolor
136 else:
137 prompts.prompt_specials = prompts.prompt_specials_color
138
139 self.color_table.set_active_scheme(colors)
140 self.prompt1.set_colors()
141 self.prompt2.set_colors()
142 self.prompt_out.set_colors()
143
144 #-------------------------------------------------------------------------
145 # Methods used in __call__. Override these methods to modify the behavior
146 # of the displayhook.
147 #-------------------------------------------------------------------------
148
149 def check_for_underscore(self):
150 """Check if the user has set the '_' variable by hand."""
151 # If something injected a '_' variable in __builtin__, delete
152 # ipython's automatic one so we don't clobber that. gettext() in
153 # particular uses _, so we need to stay away from it.
154 if '_' in __builtin__.__dict__:
155 try:
156 del self.shell.user_ns['_']
157 except KeyError:
158 pass
159
160 def quite(self):
161 """Should we silence the display hook because of ';'?"""
162 # do not print output if input ends in ';'
163 try:
164 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
165 return True
166 except IndexError:
167 # some uses of ipshellembed may fail here
168 pass
169 return False
170
171 def write_output_prompt(self):
172 """Write the output prompt."""
173 # Use write, not print which adds an extra space.
174 IPython.utils.io.Term.cout.write(self.output_sep)
175 outprompt = str(self.prompt_out)
176 if self.do_full_cache:
177 IPython.utils.io.Term.cout.write(outprompt)
178
179 # TODO: Make this method an extension point. The previous implementation
180 # has both a result_display hook as well as a result_display generic
181 # function to customize the repr on a per class basis. We need to rethink
182 # the hooks mechanism before doing this though.
183 def compute_result_repr(self, result):
184 """Compute and return the repr of the object to be displayed.
185
186 This method only compute the string form of the repr and should NOT
187 actual print or write that to a stream. This method may also transform
188 the result itself, but the default implementation passes the original
189 through.
190 """
191 try:
192 if self.shell.pprint:
193 result_repr = pformat(result)
194 if '\n' in result_repr:
195 # So that multi-line strings line up with the left column of
196 # the screen, instead of having the output prompt mess up
197 # their first line.
198 result_repr = '\n' + result_repr
199 else:
200 result_repr = repr(result)
201 except TypeError:
202 # This happens when result.__repr__ doesn't return a string,
203 # such as when it returns None.
204 result_repr = '\n'
205 return result, result_repr
206
207 def write_result_repr(self, result_repr):
208 # We want to print because we want to always make sure we have a
209 # newline, even if all the prompt separators are ''. This is the
210 # standard IPython behavior.
211 print >>IPython.utils.io.Term.cout, result_repr
212
213 def update_user_ns(self, result):
214 """Update user_ns with various things like _, __, _1, etc."""
215
216 # Avoid recursive reference when displaying _oh/Out
217 if result is not self.shell.user_ns['_oh']:
218 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
219 warn('Output cache limit (currently '+
220 `self.cache_size`+' entries) hit.\n'
221 'Flushing cache and resetting history counter...\n'
222 'The only history variables available will be _,__,___ and _1\n'
223 'with the current result.')
224
225 self.flush()
226 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
227 # we cause buggy behavior for things like gettext).
228 if '_' not in __builtin__.__dict__:
229 self.___ = self.__
230 self.__ = self._
231 self._ = result
232 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
233
234 # hackish access to top-level namespace to create _1,_2... dynamically
235 to_main = {}
236 if self.do_full_cache:
237 new_result = '_'+`self.prompt_count`
238 to_main[new_result] = result
239 self.shell.user_ns.update(to_main)
240 self.shell.user_ns['_oh'][self.prompt_count] = result
241
242 def log_output(self, result):
243 """Log the output."""
244 if self.shell.logger.log_output:
245 self.shell.logger.log_write(repr(result),'output')
246
247 def finish_displayhook(self):
248 """Finish up all displayhook activities."""
249 IPython.utils.io.Term.cout.write(self.output_sep2)
250 IPython.utils.io.Term.cout.flush()
251
252 def __call__(self, result=None):
253 """Printing with history cache management.
254
255 This is invoked everytime the interpreter needs to print, and is
256 activated by setting the variable sys.displayhook to it.
257 """
258 self.check_for_underscore()
259 if result is not None and not self.quite():
260 self.write_output_prompt()
261 result, result_repr = self.compute_result_repr(result)
262 self.write_result_repr(result_repr)
263 self.update_user_ns(result)
264 self.log_output(result)
265 self.finish_displayhook()
266
267 def flush(self):
268 if not self.do_full_cache:
269 raise ValueError,"You shouldn't have reached the cache flush "\
270 "if full caching is not enabled!"
271 # delete auto-generated vars from global namespace
272
273 for n in range(1,self.prompt_count + 1):
274 key = '_'+`n`
275 try:
276 del self.shell.user_ns[key]
277 except: pass
278 self.shell.user_ns['_oh'].clear()
279
280 if '_' not in __builtin__.__dict__:
281 self.shell.user_ns.update({'_':None,'__':None, '___':None})
282 import gc
283 gc.collect() # xxx needed?
284
@@ -1,278 +1,278 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ History related magics and functionality """
2 """ History related magics and functionality """
3
3
4 # Stdlib imports
4 # Stdlib imports
5 import fnmatch
5 import fnmatch
6 import os
6 import os
7
7
8 import IPython.utils.io
8 import IPython.utils.io
9 from IPython.utils.io import ask_yes_no
9 from IPython.utils.io import ask_yes_no
10 from IPython.utils.warn import warn
10 from IPython.utils.warn import warn
11 from IPython.core import ipapi
11 from IPython.core import ipapi
12
12
13 def magic_history(self, parameter_s = ''):
13 def magic_history(self, parameter_s = ''):
14 """Print input history (_i<n> variables), with most recent last.
14 """Print input history (_i<n> variables), with most recent last.
15
15
16 %history -> print at most 40 inputs (some may be multi-line)\\
16 %history -> print at most 40 inputs (some may be multi-line)\\
17 %history n -> print at most n inputs\\
17 %history n -> print at most n inputs\\
18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
19
19
20 By default, input history is printed without line numbers so it can be
20 By default, input history is printed without line numbers so it can be
21 directly pasted into an editor.
21 directly pasted into an editor.
22
22
23 With -n, each input's number <n> is shown, and is accessible as the
23 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
24 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.
25 statements are printed starting at a new line for easy copy/paste.
26
26
27 Options:
27 Options:
28
28
29 -n: print line numbers for each input.
29 -n: print line numbers for each input.
30 This feature is only available if numbered prompts are in use.
30 This feature is only available if numbered prompts are in use.
31
31
32 -o: also print outputs for each input.
32 -o: also print outputs for each input.
33
33
34 -p: print classic '>>>' python prompts before each input. This is useful
34 -p: print classic '>>>' python prompts before each input. This is useful
35 for making documentation, and in conjunction with -o, for producing
35 for making documentation, and in conjunction with -o, for producing
36 doctest-ready output.
36 doctest-ready output.
37
37
38 -t: (default) print the 'translated' history, as IPython understands it.
38 -t: (default) print the 'translated' history, as IPython understands it.
39 IPython filters your input and converts it all into valid Python source
39 IPython filters your input and converts it all into valid Python source
40 before executing it (things like magics or aliases are turned into
40 before executing it (things like magics or aliases are turned into
41 function calls, for example). With this option, you'll see the native
41 function calls, for example). With this option, you'll see the native
42 history instead of the user-entered version: '%cd /' will be seen as
42 history instead of the user-entered version: '%cd /' will be seen as
43 '_ip.magic("%cd /")' instead of '%cd /'.
43 '_ip.magic("%cd /")' instead of '%cd /'.
44
44
45 -r: print the 'raw' history, i.e. the actual commands you typed.
45 -r: print the 'raw' history, i.e. the actual commands you typed.
46
46
47 -g: treat the arg as a pattern to grep for in (full) history.
47 -g: treat the arg as a pattern to grep for in (full) history.
48 This includes the "shadow history" (almost all commands ever written).
48 This includes the "shadow history" (almost all commands ever written).
49 Use '%hist -g' to show full shadow history (may be very long).
49 Use '%hist -g' to show full shadow history (may be very long).
50 In shadow history, every index nuwber starts with 0.
50 In shadow history, every index nuwber starts with 0.
51
51
52 -f FILENAME: instead of printing the output to the screen, redirect it to
52 -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
53 the given file. The file is always overwritten, though IPython asks for
54 confirmation first if it already exists.
54 confirmation first if it already exists.
55 """
55 """
56
56
57 if not self.outputcache.do_full_cache:
57 if not self.displayhook.do_full_cache:
58 print 'This feature is only available if numbered prompts are in use.'
58 print 'This feature is only available if numbered prompts are in use.'
59 return
59 return
60 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
60 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
61
61
62 # Check if output to specific file was requested.
62 # Check if output to specific file was requested.
63 try:
63 try:
64 outfname = opts['f']
64 outfname = opts['f']
65 except KeyError:
65 except KeyError:
66 outfile = IPython.utils.io.Term.cout # default
66 outfile = IPython.utils.io.Term.cout # default
67 # We don't want to close stdout at the end!
67 # We don't want to close stdout at the end!
68 close_at_end = False
68 close_at_end = False
69 else:
69 else:
70 if os.path.exists(outfname):
70 if os.path.exists(outfname):
71 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
71 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
72 print 'Aborting.'
72 print 'Aborting.'
73 return
73 return
74
74
75 outfile = open(outfname,'w')
75 outfile = open(outfname,'w')
76 close_at_end = True
76 close_at_end = True
77
77
78 if 't' in opts:
78 if 't' in opts:
79 input_hist = self.input_hist
79 input_hist = self.input_hist
80 elif 'r' in opts:
80 elif 'r' in opts:
81 input_hist = self.input_hist_raw
81 input_hist = self.input_hist_raw
82 else:
82 else:
83 input_hist = self.input_hist
83 input_hist = self.input_hist
84
84
85 default_length = 40
85 default_length = 40
86 pattern = None
86 pattern = None
87 if 'g' in opts:
87 if 'g' in opts:
88 init = 1
88 init = 1
89 final = len(input_hist)
89 final = len(input_hist)
90 parts = parameter_s.split(None, 1)
90 parts = parameter_s.split(None, 1)
91 if len(parts) == 1:
91 if len(parts) == 1:
92 parts += '*'
92 parts += '*'
93 head, pattern = parts
93 head, pattern = parts
94 pattern = "*" + pattern + "*"
94 pattern = "*" + pattern + "*"
95 elif len(args) == 0:
95 elif len(args) == 0:
96 final = len(input_hist)-1
96 final = len(input_hist)-1
97 init = max(1,final-default_length)
97 init = max(1,final-default_length)
98 elif len(args) == 1:
98 elif len(args) == 1:
99 final = len(input_hist)
99 final = len(input_hist)
100 init = max(1, final-int(args[0]))
100 init = max(1, final-int(args[0]))
101 elif len(args) == 2:
101 elif len(args) == 2:
102 init, final = map(int, args)
102 init, final = map(int, args)
103 else:
103 else:
104 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
104 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
105 print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__
105 print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__
106 return
106 return
107
107
108 width = len(str(final))
108 width = len(str(final))
109 line_sep = ['','\n']
109 line_sep = ['','\n']
110 print_nums = 'n' in opts
110 print_nums = 'n' in opts
111 print_outputs = 'o' in opts
111 print_outputs = 'o' in opts
112 pyprompts = 'p' in opts
112 pyprompts = 'p' in opts
113
113
114 found = False
114 found = False
115 if pattern is not None:
115 if pattern is not None:
116 sh = self.shadowhist.all()
116 sh = self.shadowhist.all()
117 for idx, s in sh:
117 for idx, s in sh:
118 if fnmatch.fnmatch(s, pattern):
118 if fnmatch.fnmatch(s, pattern):
119 print >> outfile, "0%d: %s" %(idx, s)
119 print >> outfile, "0%d: %s" %(idx, s)
120 found = True
120 found = True
121
121
122 if found:
122 if found:
123 print >> outfile, "==="
123 print >> outfile, "==="
124 print >> outfile, \
124 print >> outfile, \
125 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 "shadow history ends, fetch by %rep <number> (must start with 0)"
126 print >> outfile, "=== start of normal history ==="
126 print >> outfile, "=== start of normal history ==="
127
127
128 for in_num in range(init,final):
128 for in_num in range(init,final):
129 inline = input_hist[in_num]
129 inline = input_hist[in_num]
130 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
130 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
131 continue
131 continue
132
132
133 multiline = int(inline.count('\n') > 1)
133 multiline = int(inline.count('\n') > 1)
134 if print_nums:
134 if print_nums:
135 print >> outfile, \
135 print >> outfile, \
136 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
136 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
137 if pyprompts:
137 if pyprompts:
138 print >> outfile, '>>>',
138 print >> outfile, '>>>',
139 if multiline:
139 if multiline:
140 lines = inline.splitlines()
140 lines = inline.splitlines()
141 print >> outfile, '\n... '.join(lines)
141 print >> outfile, '\n... '.join(lines)
142 print >> outfile, '... '
142 print >> outfile, '... '
143 else:
143 else:
144 print >> outfile, inline,
144 print >> outfile, inline,
145 else:
145 else:
146 print >> outfile, inline,
146 print >> outfile, inline,
147 if print_outputs:
147 if print_outputs:
148 output = self.shell.user_ns['Out'].get(in_num)
148 output = self.shell.user_ns['Out'].get(in_num)
149 if output is not None:
149 if output is not None:
150 print >> outfile, repr(output)
150 print >> outfile, repr(output)
151
151
152 if close_at_end:
152 if close_at_end:
153 outfile.close()
153 outfile.close()
154
154
155
155
156 def magic_hist(self, parameter_s=''):
156 def magic_hist(self, parameter_s=''):
157 """Alternate name for %history."""
157 """Alternate name for %history."""
158 return self.magic_history(parameter_s)
158 return self.magic_history(parameter_s)
159
159
160
160
161 def rep_f(self, arg):
161 def rep_f(self, arg):
162 r""" Repeat a command, or get command to input line for editing
162 r""" Repeat a command, or get command to input line for editing
163
163
164 - %rep (no arguments):
164 - %rep (no arguments):
165
165
166 Place a string version of last computation result (stored in the special '_'
166 Place a string version of last computation result (stored in the special '_'
167 variable) to the next input prompt. Allows you to create elaborate command
167 variable) to the next input prompt. Allows you to create elaborate command
168 lines without using copy-paste::
168 lines without using copy-paste::
169
169
170 $ l = ["hei", "vaan"]
170 $ l = ["hei", "vaan"]
171 $ "".join(l)
171 $ "".join(l)
172 ==> heivaan
172 ==> heivaan
173 $ %rep
173 $ %rep
174 $ heivaan_ <== cursor blinking
174 $ heivaan_ <== cursor blinking
175
175
176 %rep 45
176 %rep 45
177
177
178 Place history line 45 to next input prompt. Use %hist to find out the
178 Place history line 45 to next input prompt. Use %hist to find out the
179 number.
179 number.
180
180
181 %rep 1-4 6-7 3
181 %rep 1-4 6-7 3
182
182
183 Repeat the specified lines immediately. Input slice syntax is the same as
183 Repeat the specified lines immediately. Input slice syntax is the same as
184 in %macro and %save.
184 in %macro and %save.
185
185
186 %rep foo
186 %rep foo
187
187
188 Place the most recent line that has the substring "foo" to next input.
188 Place the most recent line that has the substring "foo" to next input.
189 (e.g. 'svn ci -m foobar').
189 (e.g. 'svn ci -m foobar').
190 """
190 """
191
191
192 opts,args = self.parse_options(arg,'',mode='list')
192 opts,args = self.parse_options(arg,'',mode='list')
193 if not args:
193 if not args:
194 self.set_next_input(str(self.user_ns["_"]))
194 self.set_next_input(str(self.user_ns["_"]))
195 return
195 return
196
196
197 if len(args) == 1 and not '-' in args[0]:
197 if len(args) == 1 and not '-' in args[0]:
198 arg = args[0]
198 arg = args[0]
199 if len(arg) > 1 and arg.startswith('0'):
199 if len(arg) > 1 and arg.startswith('0'):
200 # get from shadow hist
200 # get from shadow hist
201 num = int(arg[1:])
201 num = int(arg[1:])
202 line = self.shadowhist.get(num)
202 line = self.shadowhist.get(num)
203 self.set_next_input(str(line))
203 self.set_next_input(str(line))
204 return
204 return
205 try:
205 try:
206 num = int(args[0])
206 num = int(args[0])
207 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
207 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
208 return
208 return
209 except ValueError:
209 except ValueError:
210 pass
210 pass
211
211
212 for h in reversed(self.input_hist_raw):
212 for h in reversed(self.input_hist_raw):
213 if 'rep' in h:
213 if 'rep' in h:
214 continue
214 continue
215 if fnmatch.fnmatch(h,'*' + arg + '*'):
215 if fnmatch.fnmatch(h,'*' + arg + '*'):
216 self.set_next_input(str(h).rstrip())
216 self.set_next_input(str(h).rstrip())
217 return
217 return
218
218
219 try:
219 try:
220 lines = self.extract_input_slices(args, True)
220 lines = self.extract_input_slices(args, True)
221 print "lines",lines
221 print "lines",lines
222 self.runlines(lines)
222 self.runlines(lines)
223 except ValueError:
223 except ValueError:
224 print "Not found in recent history:", args
224 print "Not found in recent history:", args
225
225
226
226
227 _sentinel = object()
227 _sentinel = object()
228
228
229 class ShadowHist(object):
229 class ShadowHist(object):
230 def __init__(self,db):
230 def __init__(self,db):
231 # cmd => idx mapping
231 # cmd => idx mapping
232 self.curidx = 0
232 self.curidx = 0
233 self.db = db
233 self.db = db
234 self.disabled = False
234 self.disabled = False
235
235
236 def inc_idx(self):
236 def inc_idx(self):
237 idx = self.db.get('shadowhist_idx', 1)
237 idx = self.db.get('shadowhist_idx', 1)
238 self.db['shadowhist_idx'] = idx + 1
238 self.db['shadowhist_idx'] = idx + 1
239 return idx
239 return idx
240
240
241 def add(self, ent):
241 def add(self, ent):
242 if self.disabled:
242 if self.disabled:
243 return
243 return
244 try:
244 try:
245 old = self.db.hget('shadowhist', ent, _sentinel)
245 old = self.db.hget('shadowhist', ent, _sentinel)
246 if old is not _sentinel:
246 if old is not _sentinel:
247 return
247 return
248 newidx = self.inc_idx()
248 newidx = self.inc_idx()
249 #print "new",newidx # dbg
249 #print "new",newidx # dbg
250 self.db.hset('shadowhist',ent, newidx)
250 self.db.hset('shadowhist',ent, newidx)
251 except:
251 except:
252 ipapi.get().showtraceback()
252 ipapi.get().showtraceback()
253 print "WARNING: disabling shadow history"
253 print "WARNING: disabling shadow history"
254 self.disabled = True
254 self.disabled = True
255
255
256 def all(self):
256 def all(self):
257 d = self.db.hdict('shadowhist')
257 d = self.db.hdict('shadowhist')
258 items = [(i,s) for (s,i) in d.items()]
258 items = [(i,s) for (s,i) in d.items()]
259 items.sort()
259 items.sort()
260 return items
260 return items
261
261
262 def get(self, idx):
262 def get(self, idx):
263 all = self.all()
263 all = self.all()
264
264
265 for k, v in all:
265 for k, v in all:
266 #print k,v
266 #print k,v
267 if k == idx:
267 if k == idx:
268 return v
268 return v
269
269
270
270
271 def init_ipython(ip):
271 def init_ipython(ip):
272 ip.define_magic("rep",rep_f)
272 ip.define_magic("rep",rep_f)
273 ip.define_magic("hist",magic_hist)
273 ip.define_magic("hist",magic_hist)
274 ip.define_magic("history",magic_history)
274 ip.define_magic("history",magic_history)
275
275
276 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 # XXX - ipy_completers are in quarantine, need to be updated to new apis
277 #import ipy_completers
277 #import ipy_completers
278 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
278 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,276 +1,267 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 pprint import PrettyPrinter
47 from IPython.core.error import TryNext
48
49 import IPython.utils.io
48 import IPython.utils.io
50 from IPython.utils.process import shell
49 from IPython.utils.process import shell
51
50
52 from IPython.core.error import TryNext
53
54 # List here all the default hooks. For now it's just the editor functions
51 # List here all the default hooks. For now it's just the editor functions
55 # but over time we'll move here all the public API for user-accessible things.
52 # but over time we'll move here all the public API for user-accessible things.
56
53
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
56 'generate_prompt','shell_hook',
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
61 'clipboard_get']
58 'clipboard_get']
62
59
63 pformat = PrettyPrinter().pformat
64
65 def editor(self,filename, linenum=None):
60 def editor(self,filename, linenum=None):
66 """Open the default editor at the given filename and linenumber.
61 """Open the default editor at the given filename and linenumber.
67
62
68 This is IPython's default editor hook, you can use it as an example to
63 This is IPython's default editor hook, you can use it as an example to
69 write your own modified one. To set your own editor function as the
64 write your own modified one. To set your own editor function as the
70 new editor hook, call ip.set_hook('editor',yourfunc)."""
65 new editor hook, call ip.set_hook('editor',yourfunc)."""
71
66
72 # IPython configures a default editor at startup by reading $EDITOR from
67 # IPython configures a default editor at startup by reading $EDITOR from
73 # the environment, and falling back on vi (unix) or notepad (win32).
68 # the environment, and falling back on vi (unix) or notepad (win32).
74 editor = self.editor
69 editor = self.editor
75
70
76 # marker for at which line to open the file (for existing objects)
71 # marker for at which line to open the file (for existing objects)
77 if linenum is None or editor=='notepad':
72 if linenum is None or editor=='notepad':
78 linemark = ''
73 linemark = ''
79 else:
74 else:
80 linemark = '+%d' % int(linenum)
75 linemark = '+%d' % int(linenum)
81
76
82 # Enclose in quotes if necessary and legal
77 # Enclose in quotes if necessary and legal
83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
78 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 editor = '"%s"' % editor
79 editor = '"%s"' % editor
85
80
86 # Call the actual editor
81 # Call the actual editor
87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
82 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
88 raise TryNext()
83 raise TryNext()
89
84
90 import tempfile
85 import tempfile
91 def fix_error_editor(self,filename,linenum,column,msg):
86 def fix_error_editor(self,filename,linenum,column,msg):
92 """Open the editor at the given filename, linenumber, column and
87 """Open the editor at the given filename, linenumber, column and
93 show an error message. This is used for correcting syntax errors.
88 show an error message. This is used for correcting syntax errors.
94 The current implementation only has special support for the VIM editor,
89 The current implementation only has special support for the VIM editor,
95 and falls back on the 'editor' hook if VIM is not used.
90 and falls back on the 'editor' hook if VIM is not used.
96
91
97 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
92 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
98 """
93 """
99 def vim_quickfix_file():
94 def vim_quickfix_file():
100 t = tempfile.NamedTemporaryFile()
95 t = tempfile.NamedTemporaryFile()
101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
96 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
102 t.flush()
97 t.flush()
103 return t
98 return t
104 if os.path.basename(self.editor) != 'vim':
99 if os.path.basename(self.editor) != 'vim':
105 self.hooks.editor(filename,linenum)
100 self.hooks.editor(filename,linenum)
106 return
101 return
107 t = vim_quickfix_file()
102 t = vim_quickfix_file()
108 try:
103 try:
109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
104 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
110 raise TryNext()
105 raise TryNext()
111 finally:
106 finally:
112 t.close()
107 t.close()
113
108
114
109
115 def synchronize_with_editor(self, filename, linenum, column):
110 def synchronize_with_editor(self, filename, linenum, column):
116 pass
111 pass
117
112
118
113
119 class CommandChainDispatcher:
114 class CommandChainDispatcher:
120 """ Dispatch calls to a chain of commands until some func can handle it
115 """ Dispatch calls to a chain of commands until some func can handle it
121
116
122 Usage: instantiate, execute "add" to add commands (with optional
117 Usage: instantiate, execute "add" to add commands (with optional
123 priority), execute normally via f() calling mechanism.
118 priority), execute normally via f() calling mechanism.
124
119
125 """
120 """
126 def __init__(self,commands=None):
121 def __init__(self,commands=None):
127 if commands is None:
122 if commands is None:
128 self.chain = []
123 self.chain = []
129 else:
124 else:
130 self.chain = commands
125 self.chain = commands
131
126
132
127
133 def __call__(self,*args, **kw):
128 def __call__(self,*args, **kw):
134 """ Command chain is called just like normal func.
129 """ Command chain is called just like normal func.
135
130
136 This will call all funcs in chain with the same args as were given to this
131 This will call all funcs in chain with the same args as were given to this
137 function, and return the result of first func that didn't raise
132 function, and return the result of first func that didn't raise
138 TryNext """
133 TryNext """
139
134
140 for prio,cmd in self.chain:
135 for prio,cmd in self.chain:
141 #print "prio",prio,"cmd",cmd #dbg
136 #print "prio",prio,"cmd",cmd #dbg
142 try:
137 try:
143 return cmd(*args, **kw)
138 return cmd(*args, **kw)
144 except TryNext, exc:
139 except TryNext, exc:
145 if exc.args or exc.kwargs:
140 if exc.args or exc.kwargs:
146 args = exc.args
141 args = exc.args
147 kw = exc.kwargs
142 kw = exc.kwargs
148 # if no function will accept it, raise TryNext up to the caller
143 # if no function will accept it, raise TryNext up to the caller
149 raise TryNext
144 raise TryNext
150
145
151 def __str__(self):
146 def __str__(self):
152 return str(self.chain)
147 return str(self.chain)
153
148
154 def add(self, func, priority=0):
149 def add(self, func, priority=0):
155 """ Add a func to the cmd chain with given priority """
150 """ Add a func to the cmd chain with given priority """
156 bisect.insort(self.chain,(priority,func))
151 bisect.insort(self.chain,(priority,func))
157
152
158 def __iter__(self):
153 def __iter__(self):
159 """ Return all objects in chain.
154 """ Return all objects in chain.
160
155
161 Handy if the objects are not callable.
156 Handy if the objects are not callable.
162 """
157 """
163 return iter(self.chain)
158 return iter(self.chain)
164
159
165
160
166 def result_display(self,arg):
161 def result_display(self,arg):
167 """ Default display hook.
162 """ Default display hook.
168
163
169 Called for displaying the result to the user.
164 Called for displaying the result to the user.
170 """
165 """
171
166
172 if self.pprint:
167 if self.pprint:
173 out = pformat(arg)
168 out = pformat(arg)
174 if '\n' in out:
169 if '\n' in out:
175 # So that multi-line strings line up with the left column of
170 # So that multi-line strings line up with the left column of
176 # the screen, instead of having the output prompt mess up
171 # the screen, instead of having the output prompt mess up
177 # their first line.
172 # their first line.
178 IPython.utils.io.Term.cout.write('\n')
173 IPython.utils.io.Term.cout.write('\n')
179 print >>IPython.utils.io.Term.cout, out
174 print >>IPython.utils.io.Term.cout, out
180 else:
175 else:
181 # By default, the interactive prompt uses repr() to display results,
176 # By default, the interactive prompt uses repr() to display results,
182 # so we should honor this. Users who'd rather use a different
177 # so we should honor this. Users who'd rather use a different
183 # mechanism can easily override this hook.
178 # mechanism can easily override this hook.
184 print >>IPython.utils.io.Term.cout, repr(arg)
179 print >>IPython.utils.io.Term.cout, repr(arg)
185 # the default display hook doesn't manipulate the value to put in history
180 # the default display hook doesn't manipulate the value to put in history
186 return None
181 return None
187
182
188
183
189 def input_prefilter(self,line):
184 def input_prefilter(self,line):
190 """ Default input prefilter
185 """ Default input prefilter
191
186
192 This returns the line as unchanged, so that the interpreter
187 This returns the line as unchanged, so that the interpreter
193 knows that nothing was done and proceeds with "classic" prefiltering
188 knows that nothing was done and proceeds with "classic" prefiltering
194 (%magics, !shell commands etc.).
189 (%magics, !shell commands etc.).
195
190
196 Note that leading whitespace is not passed to this hook. Prefilter
191 Note that leading whitespace is not passed to this hook. Prefilter
197 can't alter indentation.
192 can't alter indentation.
198
193
199 """
194 """
200 #print "attempt to rewrite",line #dbg
195 #print "attempt to rewrite",line #dbg
201 return line
196 return line
202
197
203
198
204 def shutdown_hook(self):
199 def shutdown_hook(self):
205 """ default shutdown hook
200 """ default shutdown hook
206
201
207 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
202 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
208 """
203 """
209
204
210 #print "default shutdown hook ok" # dbg
205 #print "default shutdown hook ok" # dbg
211 return
206 return
212
207
213
208
214 def late_startup_hook(self):
209 def late_startup_hook(self):
215 """ Executed after ipython has been constructed and configured
210 """ Executed after ipython has been constructed and configured
216
211
217 """
212 """
218 #print "default startup hook ok" # dbg
213 #print "default startup hook ok" # dbg
219
214
220
215
221 def generate_prompt(self, is_continuation):
216 def generate_prompt(self, is_continuation):
222 """ calculate and return a string with the prompt to display """
217 """ calculate and return a string with the prompt to display """
223 if is_continuation:
218 if is_continuation:
224 return str(self.outputcache.prompt2)
219 return str(self.displayhook.prompt2)
225 return str(self.outputcache.prompt1)
220 return str(self.displayhook.prompt1)
226
227
228 def generate_output_prompt(self):
229 return str(self.outputcache.prompt_out)
230
221
231
222
232 def shell_hook(self,cmd):
223 def shell_hook(self,cmd):
233 """ Run system/shell command a'la os.system() """
224 """ Run system/shell command a'la os.system() """
234
225
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
226 shell(cmd, header=self.system_header, verbose=self.system_verbose)
236
227
237
228
238 def show_in_pager(self,s):
229 def show_in_pager(self,s):
239 """ Run a string through pager """
230 """ Run a string through pager """
240 # raising TryNext here will use the default paging functionality
231 # raising TryNext here will use the default paging functionality
241 raise TryNext
232 raise TryNext
242
233
243
234
244 def pre_prompt_hook(self):
235 def pre_prompt_hook(self):
245 """ Run before displaying the next prompt
236 """ Run before displaying the next prompt
246
237
247 Use this e.g. to display output from asynchronous operations (in order
238 Use this e.g. to display output from asynchronous operations (in order
248 to not mess up text entry)
239 to not mess up text entry)
249 """
240 """
250
241
251 return None
242 return None
252
243
253
244
254 def pre_runcode_hook(self):
245 def pre_runcode_hook(self):
255 """ Executed before running the (prefiltered) code in IPython """
246 """ Executed before running the (prefiltered) code in IPython """
256 return None
247 return None
257
248
258
249
259 def clipboard_get(self):
250 def clipboard_get(self):
260 """ Get text from the clipboard.
251 """ Get text from the clipboard.
261 """
252 """
262 from IPython.lib.clipboard import (
253 from IPython.lib.clipboard import (
263 osx_clipboard_get, tkinter_clipboard_get,
254 osx_clipboard_get, tkinter_clipboard_get,
264 win32_clipboard_get
255 win32_clipboard_get
265 )
256 )
266 if sys.platform == 'win32':
257 if sys.platform == 'win32':
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
258 chain = [win32_clipboard_get, tkinter_clipboard_get]
268 elif sys.platform == 'darwin':
259 elif sys.platform == 'darwin':
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
260 chain = [osx_clipboard_get, tkinter_clipboard_get]
270 else:
261 else:
271 chain = [tkinter_clipboard_get]
262 chain = [tkinter_clipboard_get]
272 dispatcher = CommandChainDispatcher()
263 dispatcher = CommandChainDispatcher()
273 for func in chain:
264 for func in chain:
274 dispatcher.add(func)
265 dispatcher.add(func)
275 text = dispatcher()
266 text = dispatcher()
276 return text
267 return text
@@ -1,2060 +1,2060 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import codeop
22 import codeop
23 import exceptions
23 import exceptions
24 import new
24 import new
25 import os
25 import os
26 import re
26 import re
27 import string
27 import string
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.core import debugger, oinspect
32 from IPython.core import debugger, oinspect
33 from IPython.core import history as ipcorehist
33 from IPython.core import history as ipcorehist
34 from IPython.core import prefilter
34 from IPython.core import prefilter
35 from IPython.core import shadowns
35 from IPython.core import shadowns
36 from IPython.core import ultratb
36 from IPython.core import ultratb
37 from IPython.core.alias import AliasManager
37 from IPython.core.alias import AliasManager
38 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.config.configurable import Configurable
39 from IPython.config.configurable import Configurable
40 from IPython.core.display_trap import DisplayTrap
40 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.error import UsageError
41 from IPython.core.error import UsageError
42 from IPython.core.extensions import ExtensionManager
42 from IPython.core.extensions import ExtensionManager
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
44 from IPython.core.inputlist import InputList
45 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.plugin import PluginManager
47 from IPython.core.plugin import PluginManager
48 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prefilter import PrefilterManager
49 from IPython.core.prompts import CachedOutput
49 from IPython.core.displayhook import DisplayHook
50 import IPython.core.hooks
50 import IPython.core.hooks
51 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.utils import PyColorize
52 from IPython.utils import PyColorize
53 from IPython.utils import pickleshare
53 from IPython.utils import pickleshare
54 from IPython.utils.doctestreload import doctest_reload
54 from IPython.utils.doctestreload import doctest_reload
55 from IPython.utils.ipstruct import Struct
55 from IPython.utils.ipstruct import Struct
56 import IPython.utils.io
56 import IPython.utils.io
57 from IPython.utils.io import ask_yes_no
57 from IPython.utils.io import ask_yes_no
58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
59 from IPython.utils.process import getoutput, getoutputerror
59 from IPython.utils.process import getoutput, getoutputerror
60 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.strdispatch import StrDispatch
61 from IPython.utils.syspathcontext import prepended_to_syspath
61 from IPython.utils.syspathcontext import prepended_to_syspath
62 from IPython.utils.text import num_ini_spaces
62 from IPython.utils.text import num_ini_spaces
63 from IPython.utils.warn import warn, error, fatal
63 from IPython.utils.warn import warn, error, fatal
64 from IPython.utils.traitlets import (
64 from IPython.utils.traitlets import (
65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
66 )
66 )
67
67
68 # from IPython.utils import growl
68 # from IPython.utils import growl
69 # growl.start("IPython")
69 # growl.start("IPython")
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Globals
72 # Globals
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 # compiled regexps for autoindent management
75 # compiled regexps for autoindent management
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77
77
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79 # Utilities
79 # Utilities
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81
81
82 # store the builtin raw_input globally, and use this always, in case user code
82 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
84 raw_input_original = raw_input
85
85
86 def softspace(file, newvalue):
86 def softspace(file, newvalue):
87 """Copied from code.py, to remove the dependency"""
87 """Copied from code.py, to remove the dependency"""
88
88
89 oldvalue = 0
89 oldvalue = 0
90 try:
90 try:
91 oldvalue = file.softspace
91 oldvalue = file.softspace
92 except AttributeError:
92 except AttributeError:
93 pass
93 pass
94 try:
94 try:
95 file.softspace = newvalue
95 file.softspace = newvalue
96 except (AttributeError, TypeError):
96 except (AttributeError, TypeError):
97 # "attribute-less object" or "read-only attributes"
97 # "attribute-less object" or "read-only attributes"
98 pass
98 pass
99 return oldvalue
99 return oldvalue
100
100
101
101
102 def no_op(*a, **kw): pass
102 def no_op(*a, **kw): pass
103
103
104 class SpaceInInput(exceptions.Exception): pass
104 class SpaceInInput(exceptions.Exception): pass
105
105
106 class Bunch: pass
106 class Bunch: pass
107
107
108 class SyntaxTB(ultratb.ListTB):
108 class SyntaxTB(ultratb.ListTB):
109 """Extension which holds some state: the last exception value"""
109 """Extension which holds some state: the last exception value"""
110
110
111 def __init__(self,color_scheme = 'NoColor'):
111 def __init__(self,color_scheme = 'NoColor'):
112 ultratb.ListTB.__init__(self,color_scheme)
112 ultratb.ListTB.__init__(self,color_scheme)
113 self.last_syntax_error = None
113 self.last_syntax_error = None
114
114
115 def __call__(self, etype, value, elist):
115 def __call__(self, etype, value, elist):
116 self.last_syntax_error = value
116 self.last_syntax_error = value
117 ultratb.ListTB.__call__(self,etype,value,elist)
117 ultratb.ListTB.__call__(self,etype,value,elist)
118
118
119 def clear_err_state(self):
119 def clear_err_state(self):
120 """Return the current error state and clear it"""
120 """Return the current error state and clear it"""
121 e = self.last_syntax_error
121 e = self.last_syntax_error
122 self.last_syntax_error = None
122 self.last_syntax_error = None
123 return e
123 return e
124
124
125
125
126 def get_default_colors():
126 def get_default_colors():
127 if sys.platform=='darwin':
127 if sys.platform=='darwin':
128 return "LightBG"
128 return "LightBG"
129 elif os.name=='nt':
129 elif os.name=='nt':
130 return 'Linux'
130 return 'Linux'
131 else:
131 else:
132 return 'Linux'
132 return 'Linux'
133
133
134
134
135 class SeparateStr(Str):
135 class SeparateStr(Str):
136 """A Str subclass to validate separate_in, separate_out, etc.
136 """A Str subclass to validate separate_in, separate_out, etc.
137
137
138 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
138 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
139 """
139 """
140
140
141 def validate(self, obj, value):
141 def validate(self, obj, value):
142 if value == '0': value = ''
142 if value == '0': value = ''
143 value = value.replace('\\n','\n')
143 value = value.replace('\\n','\n')
144 return super(SeparateStr, self).validate(obj, value)
144 return super(SeparateStr, self).validate(obj, value)
145
145
146
146
147 #-----------------------------------------------------------------------------
147 #-----------------------------------------------------------------------------
148 # Main IPython class
148 # Main IPython class
149 #-----------------------------------------------------------------------------
149 #-----------------------------------------------------------------------------
150
150
151
151
152 class InteractiveShell(Configurable, Magic):
152 class InteractiveShell(Configurable, Magic):
153 """An enhanced, interactive shell for Python."""
153 """An enhanced, interactive shell for Python."""
154
154
155 autocall = Enum((0,1,2), default_value=1, config=True)
155 autocall = Enum((0,1,2), default_value=1, config=True)
156 # TODO: remove all autoindent logic and put into frontends.
156 # TODO: remove all autoindent logic and put into frontends.
157 # We can't do this yet because even runlines uses the autoindent.
157 # We can't do this yet because even runlines uses the autoindent.
158 autoindent = CBool(True, config=True)
158 autoindent = CBool(True, config=True)
159 automagic = CBool(True, config=True)
159 automagic = CBool(True, config=True)
160 cache_size = Int(1000, config=True)
160 cache_size = Int(1000, config=True)
161 color_info = CBool(True, config=True)
161 color_info = CBool(True, config=True)
162 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
162 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
163 default_value=get_default_colors(), config=True)
163 default_value=get_default_colors(), config=True)
164 debug = CBool(False, config=True)
164 debug = CBool(False, config=True)
165 deep_reload = CBool(False, config=True)
165 deep_reload = CBool(False, config=True)
166 filename = Str("<ipython console>")
166 filename = Str("<ipython console>")
167 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
167 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
168 logstart = CBool(False, config=True)
168 logstart = CBool(False, config=True)
169 logfile = Str('', config=True)
169 logfile = Str('', config=True)
170 logappend = Str('', config=True)
170 logappend = Str('', config=True)
171 object_info_string_level = Enum((0,1,2), default_value=0,
171 object_info_string_level = Enum((0,1,2), default_value=0,
172 config=True)
172 config=True)
173 pdb = CBool(False, config=True)
173 pdb = CBool(False, config=True)
174 pprint = CBool(True, config=True)
174 pprint = CBool(True, config=True)
175 profile = Str('', config=True)
175 profile = Str('', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
179 prompts_pad_left = CBool(True, config=True)
179 prompts_pad_left = CBool(True, config=True)
180 quiet = CBool(False, config=True)
180 quiet = CBool(False, config=True)
181
181
182 # The readline stuff will eventually be moved to the terminal subclass
182 # The readline stuff will eventually be moved to the terminal subclass
183 # but for now, we can't do that as readline is welded in everywhere.
183 # but for now, we can't do that as readline is welded in everywhere.
184 readline_use = CBool(True, config=True)
184 readline_use = CBool(True, config=True)
185 readline_merge_completions = CBool(True, config=True)
185 readline_merge_completions = CBool(True, config=True)
186 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
187 readline_remove_delims = Str('-/~', config=True)
187 readline_remove_delims = Str('-/~', config=True)
188 readline_parse_and_bind = List([
188 readline_parse_and_bind = List([
189 'tab: complete',
189 'tab: complete',
190 '"\C-l": clear-screen',
190 '"\C-l": clear-screen',
191 'set show-all-if-ambiguous on',
191 'set show-all-if-ambiguous on',
192 '"\C-o": tab-insert',
192 '"\C-o": tab-insert',
193 '"\M-i": " "',
193 '"\M-i": " "',
194 '"\M-o": "\d\d\d\d"',
194 '"\M-o": "\d\d\d\d"',
195 '"\M-I": "\d\d\d\d"',
195 '"\M-I": "\d\d\d\d"',
196 '"\C-r": reverse-search-history',
196 '"\C-r": reverse-search-history',
197 '"\C-s": forward-search-history',
197 '"\C-s": forward-search-history',
198 '"\C-p": history-search-backward',
198 '"\C-p": history-search-backward',
199 '"\C-n": history-search-forward',
199 '"\C-n": history-search-forward',
200 '"\e[A": history-search-backward',
200 '"\e[A": history-search-backward',
201 '"\e[B": history-search-forward',
201 '"\e[B": history-search-forward',
202 '"\C-k": kill-line',
202 '"\C-k": kill-line',
203 '"\C-u": unix-line-discard',
203 '"\C-u": unix-line-discard',
204 ], allow_none=False, config=True)
204 ], allow_none=False, config=True)
205
205
206 # TODO: this part of prompt management should be moved to the frontends.
206 # TODO: this part of prompt management should be moved to the frontends.
207 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
208 separate_in = SeparateStr('\n', config=True)
208 separate_in = SeparateStr('\n', config=True)
209 separate_out = SeparateStr('', config=True)
209 separate_out = SeparateStr('\n', config=True)
210 separate_out2 = SeparateStr('', config=True)
210 separate_out2 = SeparateStr('\n', config=True)
211 system_header = Str('IPython system call: ', config=True)
211 system_header = Str('IPython system call: ', config=True)
212 system_verbose = CBool(False, config=True)
212 system_verbose = CBool(False, config=True)
213 wildcards_case_sensitive = CBool(True, config=True)
213 wildcards_case_sensitive = CBool(True, config=True)
214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
215 default_value='Context', config=True)
215 default_value='Context', config=True)
216
216
217 # Subcomponents of InteractiveShell
217 # Subcomponents of InteractiveShell
218 alias_manager = Instance('IPython.core.alias.AliasManager')
218 alias_manager = Instance('IPython.core.alias.AliasManager')
219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
224
224
225 def __init__(self, config=None, ipython_dir=None,
225 def __init__(self, config=None, ipython_dir=None,
226 user_ns=None, user_global_ns=None,
226 user_ns=None, user_global_ns=None,
227 custom_exceptions=((),None)):
227 custom_exceptions=((),None)):
228
228
229 # This is where traits with a config_key argument are updated
229 # This is where traits with a config_key argument are updated
230 # from the values on config.
230 # from the values on config.
231 super(InteractiveShell, self).__init__(config=config)
231 super(InteractiveShell, self).__init__(config=config)
232
232
233 # These are relatively independent and stateless
233 # These are relatively independent and stateless
234 self.init_ipython_dir(ipython_dir)
234 self.init_ipython_dir(ipython_dir)
235 self.init_instance_attrs()
235 self.init_instance_attrs()
236
236
237 # Create namespaces (user_ns, user_global_ns, etc.)
237 # Create namespaces (user_ns, user_global_ns, etc.)
238 self.init_create_namespaces(user_ns, user_global_ns)
238 self.init_create_namespaces(user_ns, user_global_ns)
239 # This has to be done after init_create_namespaces because it uses
239 # This has to be done after init_create_namespaces because it uses
240 # something in self.user_ns, but before init_sys_modules, which
240 # something in self.user_ns, but before init_sys_modules, which
241 # is the first thing to modify sys.
241 # is the first thing to modify sys.
242 self.save_sys_module_state()
242 self.save_sys_module_state()
243 self.init_sys_modules()
243 self.init_sys_modules()
244
244
245 self.init_history()
245 self.init_history()
246 self.init_encoding()
246 self.init_encoding()
247 self.init_prefilter()
247 self.init_prefilter()
248
248
249 Magic.__init__(self, self)
249 Magic.__init__(self, self)
250
250
251 self.init_syntax_highlighting()
251 self.init_syntax_highlighting()
252 self.init_hooks()
252 self.init_hooks()
253 self.init_pushd_popd_magic()
253 self.init_pushd_popd_magic()
254 # TODO: init_io() needs to happen before init_traceback handlers
254 # TODO: init_io() needs to happen before init_traceback handlers
255 # because the traceback handlers hardcode the stdout/stderr streams.
255 # because the traceback handlers hardcode the stdout/stderr streams.
256 # This logic in in debugger.Pdb and should eventually be changed.
256 # This logic in in debugger.Pdb and should eventually be changed.
257 self.init_io()
257 self.init_io()
258 self.init_traceback_handlers(custom_exceptions)
258 self.init_traceback_handlers(custom_exceptions)
259 self.init_user_ns()
259 self.init_user_ns()
260 self.init_logger()
260 self.init_logger()
261 self.init_alias()
261 self.init_alias()
262 self.init_builtins()
262 self.init_builtins()
263
263
264 # pre_config_initialization
264 # pre_config_initialization
265 self.init_shadow_hist()
265 self.init_shadow_hist()
266
266
267 # The next section should contain averything that was in ipmaker.
267 # The next section should contain averything that was in ipmaker.
268 self.init_logstart()
268 self.init_logstart()
269
269
270 # The following was in post_config_initialization
270 # The following was in post_config_initialization
271 self.init_inspector()
271 self.init_inspector()
272 self.init_readline()
272 self.init_readline()
273 self.init_prompts()
273 self.init_prompts()
274 self.init_displayhook()
274 self.init_displayhook()
275 self.init_reload_doctest()
275 self.init_reload_doctest()
276 self.init_magics()
276 self.init_magics()
277 self.init_pdb()
277 self.init_pdb()
278 self.init_extension_manager()
278 self.init_extension_manager()
279 self.init_plugin_manager()
279 self.init_plugin_manager()
280 self.hooks.late_startup_hook()
280 self.hooks.late_startup_hook()
281
281
282 @classmethod
282 @classmethod
283 def instance(cls, *args, **kwargs):
283 def instance(cls, *args, **kwargs):
284 """Returns a global InteractiveShell instance."""
284 """Returns a global InteractiveShell instance."""
285 if not hasattr(cls, "_instance"):
285 if not hasattr(cls, "_instance"):
286 cls._instance = cls(*args, **kwargs)
286 cls._instance = cls(*args, **kwargs)
287 return cls._instance
287 return cls._instance
288
288
289 @classmethod
289 @classmethod
290 def initialized(cls):
290 def initialized(cls):
291 return hasattr(cls, "_instance")
291 return hasattr(cls, "_instance")
292
292
293 def get_ipython(self):
293 def get_ipython(self):
294 """Return the currently running IPython instance."""
294 """Return the currently running IPython instance."""
295 return self
295 return self
296
296
297 #-------------------------------------------------------------------------
297 #-------------------------------------------------------------------------
298 # Trait changed handlers
298 # Trait changed handlers
299 #-------------------------------------------------------------------------
299 #-------------------------------------------------------------------------
300
300
301 def _ipython_dir_changed(self, name, new):
301 def _ipython_dir_changed(self, name, new):
302 if not os.path.isdir(new):
302 if not os.path.isdir(new):
303 os.makedirs(new, mode = 0777)
303 os.makedirs(new, mode = 0777)
304
304
305 def set_autoindent(self,value=None):
305 def set_autoindent(self,value=None):
306 """Set the autoindent flag, checking for readline support.
306 """Set the autoindent flag, checking for readline support.
307
307
308 If called with no arguments, it acts as a toggle."""
308 If called with no arguments, it acts as a toggle."""
309
309
310 if not self.has_readline:
310 if not self.has_readline:
311 if os.name == 'posix':
311 if os.name == 'posix':
312 warn("The auto-indent feature requires the readline library")
312 warn("The auto-indent feature requires the readline library")
313 self.autoindent = 0
313 self.autoindent = 0
314 return
314 return
315 if value is None:
315 if value is None:
316 self.autoindent = not self.autoindent
316 self.autoindent = not self.autoindent
317 else:
317 else:
318 self.autoindent = value
318 self.autoindent = value
319
319
320 #-------------------------------------------------------------------------
320 #-------------------------------------------------------------------------
321 # init_* methods called by __init__
321 # init_* methods called by __init__
322 #-------------------------------------------------------------------------
322 #-------------------------------------------------------------------------
323
323
324 def init_ipython_dir(self, ipython_dir):
324 def init_ipython_dir(self, ipython_dir):
325 if ipython_dir is not None:
325 if ipython_dir is not None:
326 self.ipython_dir = ipython_dir
326 self.ipython_dir = ipython_dir
327 self.config.Global.ipython_dir = self.ipython_dir
327 self.config.Global.ipython_dir = self.ipython_dir
328 return
328 return
329
329
330 if hasattr(self.config.Global, 'ipython_dir'):
330 if hasattr(self.config.Global, 'ipython_dir'):
331 self.ipython_dir = self.config.Global.ipython_dir
331 self.ipython_dir = self.config.Global.ipython_dir
332 else:
332 else:
333 self.ipython_dir = get_ipython_dir()
333 self.ipython_dir = get_ipython_dir()
334
334
335 # All children can just read this
335 # All children can just read this
336 self.config.Global.ipython_dir = self.ipython_dir
336 self.config.Global.ipython_dir = self.ipython_dir
337
337
338 def init_instance_attrs(self):
338 def init_instance_attrs(self):
339 self.more = False
339 self.more = False
340
340
341 # command compiler
341 # command compiler
342 self.compile = codeop.CommandCompiler()
342 self.compile = codeop.CommandCompiler()
343
343
344 # User input buffer
344 # User input buffer
345 self.buffer = []
345 self.buffer = []
346
346
347 # Make an empty namespace, which extension writers can rely on both
347 # Make an empty namespace, which extension writers can rely on both
348 # existing and NEVER being used by ipython itself. This gives them a
348 # existing and NEVER being used by ipython itself. This gives them a
349 # convenient location for storing additional information and state
349 # convenient location for storing additional information and state
350 # their extensions may require, without fear of collisions with other
350 # their extensions may require, without fear of collisions with other
351 # ipython names that may develop later.
351 # ipython names that may develop later.
352 self.meta = Struct()
352 self.meta = Struct()
353
353
354 # Object variable to store code object waiting execution. This is
354 # Object variable to store code object waiting execution. This is
355 # used mainly by the multithreaded shells, but it can come in handy in
355 # used mainly by the multithreaded shells, but it can come in handy in
356 # other situations. No need to use a Queue here, since it's a single
356 # other situations. No need to use a Queue here, since it's a single
357 # item which gets cleared once run.
357 # item which gets cleared once run.
358 self.code_to_run = None
358 self.code_to_run = None
359
359
360 # Temporary files used for various purposes. Deleted at exit.
360 # Temporary files used for various purposes. Deleted at exit.
361 self.tempfiles = []
361 self.tempfiles = []
362
362
363 # Keep track of readline usage (later set by init_readline)
363 # Keep track of readline usage (later set by init_readline)
364 self.has_readline = False
364 self.has_readline = False
365
365
366 # keep track of where we started running (mainly for crash post-mortem)
366 # keep track of where we started running (mainly for crash post-mortem)
367 # This is not being used anywhere currently.
367 # This is not being used anywhere currently.
368 self.starting_dir = os.getcwd()
368 self.starting_dir = os.getcwd()
369
369
370 # Indentation management
370 # Indentation management
371 self.indent_current_nsp = 0
371 self.indent_current_nsp = 0
372
372
373 def init_encoding(self):
373 def init_encoding(self):
374 # Get system encoding at startup time. Certain terminals (like Emacs
374 # Get system encoding at startup time. Certain terminals (like Emacs
375 # under Win32 have it set to None, and we need to have a known valid
375 # under Win32 have it set to None, and we need to have a known valid
376 # encoding to use in the raw_input() method
376 # encoding to use in the raw_input() method
377 try:
377 try:
378 self.stdin_encoding = sys.stdin.encoding or 'ascii'
378 self.stdin_encoding = sys.stdin.encoding or 'ascii'
379 except AttributeError:
379 except AttributeError:
380 self.stdin_encoding = 'ascii'
380 self.stdin_encoding = 'ascii'
381
381
382 def init_syntax_highlighting(self):
382 def init_syntax_highlighting(self):
383 # Python source parser/formatter for syntax highlighting
383 # Python source parser/formatter for syntax highlighting
384 pyformat = PyColorize.Parser().format
384 pyformat = PyColorize.Parser().format
385 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
385 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
386
386
387 def init_pushd_popd_magic(self):
387 def init_pushd_popd_magic(self):
388 # for pushd/popd management
388 # for pushd/popd management
389 try:
389 try:
390 self.home_dir = get_home_dir()
390 self.home_dir = get_home_dir()
391 except HomeDirError, msg:
391 except HomeDirError, msg:
392 fatal(msg)
392 fatal(msg)
393
393
394 self.dir_stack = []
394 self.dir_stack = []
395
395
396 def init_logger(self):
396 def init_logger(self):
397 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
397 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
398 # local shortcut, this is used a LOT
398 # local shortcut, this is used a LOT
399 self.log = self.logger.log
399 self.log = self.logger.log
400
400
401 def init_logstart(self):
401 def init_logstart(self):
402 if self.logappend:
402 if self.logappend:
403 self.magic_logstart(self.logappend + ' append')
403 self.magic_logstart(self.logappend + ' append')
404 elif self.logfile:
404 elif self.logfile:
405 self.magic_logstart(self.logfile)
405 self.magic_logstart(self.logfile)
406 elif self.logstart:
406 elif self.logstart:
407 self.magic_logstart()
407 self.magic_logstart()
408
408
409 def init_builtins(self):
409 def init_builtins(self):
410 self.builtin_trap = BuiltinTrap(shell=self)
410 self.builtin_trap = BuiltinTrap(shell=self)
411
411
412 def init_inspector(self):
412 def init_inspector(self):
413 # Object inspector
413 # Object inspector
414 self.inspector = oinspect.Inspector(oinspect.InspectColors,
414 self.inspector = oinspect.Inspector(oinspect.InspectColors,
415 PyColorize.ANSICodeColors,
415 PyColorize.ANSICodeColors,
416 'NoColor',
416 'NoColor',
417 self.object_info_string_level)
417 self.object_info_string_level)
418
418
419 def init_io(self):
419 def init_io(self):
420 import IPython.utils.io
420 import IPython.utils.io
421 if sys.platform == 'win32' and readline.have_readline and \
421 if sys.platform == 'win32' and readline.have_readline and \
422 self.readline_use:
422 self.readline_use:
423 Term = IPython.utils.io.IOTerm(
423 Term = IPython.utils.io.IOTerm(
424 cout=readline._outputfile,cerr=readline._outputfile
424 cout=readline._outputfile,cerr=readline._outputfile
425 )
425 )
426 else:
426 else:
427 Term = IPython.utils.io.IOTerm()
427 Term = IPython.utils.io.IOTerm()
428 IPython.utils.io.Term = Term
428 IPython.utils.io.Term = Term
429
429
430 def init_prompts(self):
430 def init_prompts(self):
431 # Initialize cache, set in/out prompts and printing system
431 # TODO: This is a pass for now because the prompts are managed inside
432 self.outputcache = CachedOutput(self,
432 # the DisplayHook. Once there is a separate prompt manager, this
433 self.cache_size,
433 # will initialize that object and all prompt related information.
434 self.pprint,
434 pass
435
436 def init_displayhook(self):
437 # Initialize displayhook, set in/out prompts and printing system
438 self.displayhook = DisplayHook( shell=self,
439 cache_size=self.cache_size,
435 input_sep = self.separate_in,
440 input_sep = self.separate_in,
436 output_sep = self.separate_out,
441 output_sep = self.separate_out,
437 output_sep2 = self.separate_out2,
442 output_sep2 = self.separate_out2,
438 ps1 = self.prompt_in1,
443 ps1 = self.prompt_in1,
439 ps2 = self.prompt_in2,
444 ps2 = self.prompt_in2,
440 ps_out = self.prompt_out,
445 ps_out = self.prompt_out,
441 pad_left = self.prompts_pad_left)
446 pad_left = self.prompts_pad_left)
442
447 # This is a context manager that installs/revmoes the displayhook at
443 # user may have over-ridden the default print hook:
448 # the appropriate time.
444 try:
449 self.display_trap = DisplayTrap(hook=self.displayhook)
445 self.outputcache.__class__.display = self.hooks.display
446 except AttributeError:
447 pass
448
449 def init_displayhook(self):
450 self.display_trap = DisplayTrap(hook=self.outputcache)
451
450
452 def init_reload_doctest(self):
451 def init_reload_doctest(self):
453 # Do a proper resetting of doctest, including the necessary displayhook
452 # Do a proper resetting of doctest, including the necessary displayhook
454 # monkeypatching
453 # monkeypatching
455 try:
454 try:
456 doctest_reload()
455 doctest_reload()
457 except ImportError:
456 except ImportError:
458 warn("doctest module does not exist.")
457 warn("doctest module does not exist.")
459
458
460 #-------------------------------------------------------------------------
459 #-------------------------------------------------------------------------
461 # Things related to injections into the sys module
460 # Things related to injections into the sys module
462 #-------------------------------------------------------------------------
461 #-------------------------------------------------------------------------
463
462
464 def save_sys_module_state(self):
463 def save_sys_module_state(self):
465 """Save the state of hooks in the sys module.
464 """Save the state of hooks in the sys module.
466
465
467 This has to be called after self.user_ns is created.
466 This has to be called after self.user_ns is created.
468 """
467 """
469 self._orig_sys_module_state = {}
468 self._orig_sys_module_state = {}
470 self._orig_sys_module_state['stdin'] = sys.stdin
469 self._orig_sys_module_state['stdin'] = sys.stdin
471 self._orig_sys_module_state['stdout'] = sys.stdout
470 self._orig_sys_module_state['stdout'] = sys.stdout
472 self._orig_sys_module_state['stderr'] = sys.stderr
471 self._orig_sys_module_state['stderr'] = sys.stderr
473 self._orig_sys_module_state['excepthook'] = sys.excepthook
472 self._orig_sys_module_state['excepthook'] = sys.excepthook
474 try:
473 try:
475 self._orig_sys_modules_main_name = self.user_ns['__name__']
474 self._orig_sys_modules_main_name = self.user_ns['__name__']
476 except KeyError:
475 except KeyError:
477 pass
476 pass
478
477
479 def restore_sys_module_state(self):
478 def restore_sys_module_state(self):
480 """Restore the state of the sys module."""
479 """Restore the state of the sys module."""
481 try:
480 try:
482 for k, v in self._orig_sys_module_state.items():
481 for k, v in self._orig_sys_module_state.items():
483 setattr(sys, k, v)
482 setattr(sys, k, v)
484 except AttributeError:
483 except AttributeError:
485 pass
484 pass
486 try:
485 try:
487 delattr(sys, 'ipcompleter')
486 delattr(sys, 'ipcompleter')
488 except AttributeError:
487 except AttributeError:
489 pass
488 pass
490 # Reset what what done in self.init_sys_modules
489 # Reset what what done in self.init_sys_modules
491 try:
490 try:
492 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
491 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
493 except (AttributeError, KeyError):
492 except (AttributeError, KeyError):
494 pass
493 pass
495
494
496 #-------------------------------------------------------------------------
495 #-------------------------------------------------------------------------
497 # Things related to hooks
496 # Things related to hooks
498 #-------------------------------------------------------------------------
497 #-------------------------------------------------------------------------
499
498
500 def init_hooks(self):
499 def init_hooks(self):
501 # hooks holds pointers used for user-side customizations
500 # hooks holds pointers used for user-side customizations
502 self.hooks = Struct()
501 self.hooks = Struct()
503
502
504 self.strdispatchers = {}
503 self.strdispatchers = {}
505
504
506 # Set all default hooks, defined in the IPython.hooks module.
505 # Set all default hooks, defined in the IPython.hooks module.
507 hooks = IPython.core.hooks
506 hooks = IPython.core.hooks
508 for hook_name in hooks.__all__:
507 for hook_name in hooks.__all__:
509 # default hooks have priority 100, i.e. low; user hooks should have
508 # default hooks have priority 100, i.e. low; user hooks should have
510 # 0-100 priority
509 # 0-100 priority
511 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
510 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
512
511
513 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
512 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
514 """set_hook(name,hook) -> sets an internal IPython hook.
513 """set_hook(name,hook) -> sets an internal IPython hook.
515
514
516 IPython exposes some of its internal API as user-modifiable hooks. By
515 IPython exposes some of its internal API as user-modifiable hooks. By
517 adding your function to one of these hooks, you can modify IPython's
516 adding your function to one of these hooks, you can modify IPython's
518 behavior to call at runtime your own routines."""
517 behavior to call at runtime your own routines."""
519
518
520 # At some point in the future, this should validate the hook before it
519 # At some point in the future, this should validate the hook before it
521 # accepts it. Probably at least check that the hook takes the number
520 # accepts it. Probably at least check that the hook takes the number
522 # of args it's supposed to.
521 # of args it's supposed to.
523
522
524 f = new.instancemethod(hook,self,self.__class__)
523 f = new.instancemethod(hook,self,self.__class__)
525
524
526 # check if the hook is for strdispatcher first
525 # check if the hook is for strdispatcher first
527 if str_key is not None:
526 if str_key is not None:
528 sdp = self.strdispatchers.get(name, StrDispatch())
527 sdp = self.strdispatchers.get(name, StrDispatch())
529 sdp.add_s(str_key, f, priority )
528 sdp.add_s(str_key, f, priority )
530 self.strdispatchers[name] = sdp
529 self.strdispatchers[name] = sdp
531 return
530 return
532 if re_key is not None:
531 if re_key is not None:
533 sdp = self.strdispatchers.get(name, StrDispatch())
532 sdp = self.strdispatchers.get(name, StrDispatch())
534 sdp.add_re(re.compile(re_key), f, priority )
533 sdp.add_re(re.compile(re_key), f, priority )
535 self.strdispatchers[name] = sdp
534 self.strdispatchers[name] = sdp
536 return
535 return
537
536
538 dp = getattr(self.hooks, name, None)
537 dp = getattr(self.hooks, name, None)
539 if name not in IPython.core.hooks.__all__:
538 if name not in IPython.core.hooks.__all__:
540 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
539 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
541 if not dp:
540 if not dp:
542 dp = IPython.core.hooks.CommandChainDispatcher()
541 dp = IPython.core.hooks.CommandChainDispatcher()
543
542
544 try:
543 try:
545 dp.add(f,priority)
544 dp.add(f,priority)
546 except AttributeError:
545 except AttributeError:
547 # it was not commandchain, plain old func - replace
546 # it was not commandchain, plain old func - replace
548 dp = f
547 dp = f
549
548
550 setattr(self.hooks,name, dp)
549 setattr(self.hooks,name, dp)
551
550
552 #-------------------------------------------------------------------------
551 #-------------------------------------------------------------------------
553 # Things related to the "main" module
552 # Things related to the "main" module
554 #-------------------------------------------------------------------------
553 #-------------------------------------------------------------------------
555
554
556 def new_main_mod(self,ns=None):
555 def new_main_mod(self,ns=None):
557 """Return a new 'main' module object for user code execution.
556 """Return a new 'main' module object for user code execution.
558 """
557 """
559 main_mod = self._user_main_module
558 main_mod = self._user_main_module
560 init_fakemod_dict(main_mod,ns)
559 init_fakemod_dict(main_mod,ns)
561 return main_mod
560 return main_mod
562
561
563 def cache_main_mod(self,ns,fname):
562 def cache_main_mod(self,ns,fname):
564 """Cache a main module's namespace.
563 """Cache a main module's namespace.
565
564
566 When scripts are executed via %run, we must keep a reference to the
565 When scripts are executed via %run, we must keep a reference to the
567 namespace of their __main__ module (a FakeModule instance) around so
566 namespace of their __main__ module (a FakeModule instance) around so
568 that Python doesn't clear it, rendering objects defined therein
567 that Python doesn't clear it, rendering objects defined therein
569 useless.
568 useless.
570
569
571 This method keeps said reference in a private dict, keyed by the
570 This method keeps said reference in a private dict, keyed by the
572 absolute path of the module object (which corresponds to the script
571 absolute path of the module object (which corresponds to the script
573 path). This way, for multiple executions of the same script we only
572 path). This way, for multiple executions of the same script we only
574 keep one copy of the namespace (the last one), thus preventing memory
573 keep one copy of the namespace (the last one), thus preventing memory
575 leaks from old references while allowing the objects from the last
574 leaks from old references while allowing the objects from the last
576 execution to be accessible.
575 execution to be accessible.
577
576
578 Note: we can not allow the actual FakeModule instances to be deleted,
577 Note: we can not allow the actual FakeModule instances to be deleted,
579 because of how Python tears down modules (it hard-sets all their
578 because of how Python tears down modules (it hard-sets all their
580 references to None without regard for reference counts). This method
579 references to None without regard for reference counts). This method
581 must therefore make a *copy* of the given namespace, to allow the
580 must therefore make a *copy* of the given namespace, to allow the
582 original module's __dict__ to be cleared and reused.
581 original module's __dict__ to be cleared and reused.
583
582
584
583
585 Parameters
584 Parameters
586 ----------
585 ----------
587 ns : a namespace (a dict, typically)
586 ns : a namespace (a dict, typically)
588
587
589 fname : str
588 fname : str
590 Filename associated with the namespace.
589 Filename associated with the namespace.
591
590
592 Examples
591 Examples
593 --------
592 --------
594
593
595 In [10]: import IPython
594 In [10]: import IPython
596
595
597 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
596 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
598
597
599 In [12]: IPython.__file__ in _ip._main_ns_cache
598 In [12]: IPython.__file__ in _ip._main_ns_cache
600 Out[12]: True
599 Out[12]: True
601 """
600 """
602 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
601 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
603
602
604 def clear_main_mod_cache(self):
603 def clear_main_mod_cache(self):
605 """Clear the cache of main modules.
604 """Clear the cache of main modules.
606
605
607 Mainly for use by utilities like %reset.
606 Mainly for use by utilities like %reset.
608
607
609 Examples
608 Examples
610 --------
609 --------
611
610
612 In [15]: import IPython
611 In [15]: import IPython
613
612
614 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
613 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
615
614
616 In [17]: len(_ip._main_ns_cache) > 0
615 In [17]: len(_ip._main_ns_cache) > 0
617 Out[17]: True
616 Out[17]: True
618
617
619 In [18]: _ip.clear_main_mod_cache()
618 In [18]: _ip.clear_main_mod_cache()
620
619
621 In [19]: len(_ip._main_ns_cache) == 0
620 In [19]: len(_ip._main_ns_cache) == 0
622 Out[19]: True
621 Out[19]: True
623 """
622 """
624 self._main_ns_cache.clear()
623 self._main_ns_cache.clear()
625
624
626 #-------------------------------------------------------------------------
625 #-------------------------------------------------------------------------
627 # Things related to debugging
626 # Things related to debugging
628 #-------------------------------------------------------------------------
627 #-------------------------------------------------------------------------
629
628
630 def init_pdb(self):
629 def init_pdb(self):
631 # Set calling of pdb on exceptions
630 # Set calling of pdb on exceptions
632 # self.call_pdb is a property
631 # self.call_pdb is a property
633 self.call_pdb = self.pdb
632 self.call_pdb = self.pdb
634
633
635 def _get_call_pdb(self):
634 def _get_call_pdb(self):
636 return self._call_pdb
635 return self._call_pdb
637
636
638 def _set_call_pdb(self,val):
637 def _set_call_pdb(self,val):
639
638
640 if val not in (0,1,False,True):
639 if val not in (0,1,False,True):
641 raise ValueError,'new call_pdb value must be boolean'
640 raise ValueError,'new call_pdb value must be boolean'
642
641
643 # store value in instance
642 # store value in instance
644 self._call_pdb = val
643 self._call_pdb = val
645
644
646 # notify the actual exception handlers
645 # notify the actual exception handlers
647 self.InteractiveTB.call_pdb = val
646 self.InteractiveTB.call_pdb = val
648
647
649 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
648 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
650 'Control auto-activation of pdb at exceptions')
649 'Control auto-activation of pdb at exceptions')
651
650
652 def debugger(self,force=False):
651 def debugger(self,force=False):
653 """Call the pydb/pdb debugger.
652 """Call the pydb/pdb debugger.
654
653
655 Keywords:
654 Keywords:
656
655
657 - force(False): by default, this routine checks the instance call_pdb
656 - force(False): by default, this routine checks the instance call_pdb
658 flag and does not actually invoke the debugger if the flag is false.
657 flag and does not actually invoke the debugger if the flag is false.
659 The 'force' option forces the debugger to activate even if the flag
658 The 'force' option forces the debugger to activate even if the flag
660 is false.
659 is false.
661 """
660 """
662
661
663 if not (force or self.call_pdb):
662 if not (force or self.call_pdb):
664 return
663 return
665
664
666 if not hasattr(sys,'last_traceback'):
665 if not hasattr(sys,'last_traceback'):
667 error('No traceback has been produced, nothing to debug.')
666 error('No traceback has been produced, nothing to debug.')
668 return
667 return
669
668
670 # use pydb if available
669 # use pydb if available
671 if debugger.has_pydb:
670 if debugger.has_pydb:
672 from pydb import pm
671 from pydb import pm
673 else:
672 else:
674 # fallback to our internal debugger
673 # fallback to our internal debugger
675 pm = lambda : self.InteractiveTB.debugger(force=True)
674 pm = lambda : self.InteractiveTB.debugger(force=True)
676 self.history_saving_wrapper(pm)()
675 self.history_saving_wrapper(pm)()
677
676
678 #-------------------------------------------------------------------------
677 #-------------------------------------------------------------------------
679 # Things related to IPython's various namespaces
678 # Things related to IPython's various namespaces
680 #-------------------------------------------------------------------------
679 #-------------------------------------------------------------------------
681
680
682 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
681 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
683 # Create the namespace where the user will operate. user_ns is
682 # Create the namespace where the user will operate. user_ns is
684 # normally the only one used, and it is passed to the exec calls as
683 # normally the only one used, and it is passed to the exec calls as
685 # the locals argument. But we do carry a user_global_ns namespace
684 # the locals argument. But we do carry a user_global_ns namespace
686 # given as the exec 'globals' argument, This is useful in embedding
685 # given as the exec 'globals' argument, This is useful in embedding
687 # situations where the ipython shell opens in a context where the
686 # situations where the ipython shell opens in a context where the
688 # distinction between locals and globals is meaningful. For
687 # distinction between locals and globals is meaningful. For
689 # non-embedded contexts, it is just the same object as the user_ns dict.
688 # non-embedded contexts, it is just the same object as the user_ns dict.
690
689
691 # FIXME. For some strange reason, __builtins__ is showing up at user
690 # FIXME. For some strange reason, __builtins__ is showing up at user
692 # level as a dict instead of a module. This is a manual fix, but I
691 # level as a dict instead of a module. This is a manual fix, but I
693 # should really track down where the problem is coming from. Alex
692 # should really track down where the problem is coming from. Alex
694 # Schmolck reported this problem first.
693 # Schmolck reported this problem first.
695
694
696 # A useful post by Alex Martelli on this topic:
695 # A useful post by Alex Martelli on this topic:
697 # Re: inconsistent value from __builtins__
696 # Re: inconsistent value from __builtins__
698 # Von: Alex Martelli <aleaxit@yahoo.com>
697 # Von: Alex Martelli <aleaxit@yahoo.com>
699 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
698 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
700 # Gruppen: comp.lang.python
699 # Gruppen: comp.lang.python
701
700
702 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
701 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
703 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
702 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
704 # > <type 'dict'>
703 # > <type 'dict'>
705 # > >>> print type(__builtins__)
704 # > >>> print type(__builtins__)
706 # > <type 'module'>
705 # > <type 'module'>
707 # > Is this difference in return value intentional?
706 # > Is this difference in return value intentional?
708
707
709 # Well, it's documented that '__builtins__' can be either a dictionary
708 # Well, it's documented that '__builtins__' can be either a dictionary
710 # or a module, and it's been that way for a long time. Whether it's
709 # or a module, and it's been that way for a long time. Whether it's
711 # intentional (or sensible), I don't know. In any case, the idea is
710 # intentional (or sensible), I don't know. In any case, the idea is
712 # that if you need to access the built-in namespace directly, you
711 # that if you need to access the built-in namespace directly, you
713 # should start with "import __builtin__" (note, no 's') which will
712 # should start with "import __builtin__" (note, no 's') which will
714 # definitely give you a module. Yeah, it's somewhat confusing:-(.
713 # definitely give you a module. Yeah, it's somewhat confusing:-(.
715
714
716 # These routines return properly built dicts as needed by the rest of
715 # These routines return properly built dicts as needed by the rest of
717 # the code, and can also be used by extension writers to generate
716 # the code, and can also be used by extension writers to generate
718 # properly initialized namespaces.
717 # properly initialized namespaces.
719 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
718 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
720
719
721 # Assign namespaces
720 # Assign namespaces
722 # This is the namespace where all normal user variables live
721 # This is the namespace where all normal user variables live
723 self.user_ns = user_ns
722 self.user_ns = user_ns
724 self.user_global_ns = user_global_ns
723 self.user_global_ns = user_global_ns
725
724
726 # An auxiliary namespace that checks what parts of the user_ns were
725 # An auxiliary namespace that checks what parts of the user_ns were
727 # loaded at startup, so we can list later only variables defined in
726 # loaded at startup, so we can list later only variables defined in
728 # actual interactive use. Since it is always a subset of user_ns, it
727 # actual interactive use. Since it is always a subset of user_ns, it
729 # doesn't need to be separately tracked in the ns_table.
728 # doesn't need to be separately tracked in the ns_table.
730 self.user_ns_hidden = {}
729 self.user_ns_hidden = {}
731
730
732 # A namespace to keep track of internal data structures to prevent
731 # A namespace to keep track of internal data structures to prevent
733 # them from cluttering user-visible stuff. Will be updated later
732 # them from cluttering user-visible stuff. Will be updated later
734 self.internal_ns = {}
733 self.internal_ns = {}
735
734
736 # Now that FakeModule produces a real module, we've run into a nasty
735 # Now that FakeModule produces a real module, we've run into a nasty
737 # problem: after script execution (via %run), the module where the user
736 # problem: after script execution (via %run), the module where the user
738 # code ran is deleted. Now that this object is a true module (needed
737 # code ran is deleted. Now that this object is a true module (needed
739 # so docetst and other tools work correctly), the Python module
738 # so docetst and other tools work correctly), the Python module
740 # teardown mechanism runs over it, and sets to None every variable
739 # teardown mechanism runs over it, and sets to None every variable
741 # present in that module. Top-level references to objects from the
740 # present in that module. Top-level references to objects from the
742 # script survive, because the user_ns is updated with them. However,
741 # script survive, because the user_ns is updated with them. However,
743 # calling functions defined in the script that use other things from
742 # calling functions defined in the script that use other things from
744 # the script will fail, because the function's closure had references
743 # the script will fail, because the function's closure had references
745 # to the original objects, which are now all None. So we must protect
744 # to the original objects, which are now all None. So we must protect
746 # these modules from deletion by keeping a cache.
745 # these modules from deletion by keeping a cache.
747 #
746 #
748 # To avoid keeping stale modules around (we only need the one from the
747 # To avoid keeping stale modules around (we only need the one from the
749 # last run), we use a dict keyed with the full path to the script, so
748 # last run), we use a dict keyed with the full path to the script, so
750 # only the last version of the module is held in the cache. Note,
749 # only the last version of the module is held in the cache. Note,
751 # however, that we must cache the module *namespace contents* (their
750 # however, that we must cache the module *namespace contents* (their
752 # __dict__). Because if we try to cache the actual modules, old ones
751 # __dict__). Because if we try to cache the actual modules, old ones
753 # (uncached) could be destroyed while still holding references (such as
752 # (uncached) could be destroyed while still holding references (such as
754 # those held by GUI objects that tend to be long-lived)>
753 # those held by GUI objects that tend to be long-lived)>
755 #
754 #
756 # The %reset command will flush this cache. See the cache_main_mod()
755 # The %reset command will flush this cache. See the cache_main_mod()
757 # and clear_main_mod_cache() methods for details on use.
756 # and clear_main_mod_cache() methods for details on use.
758
757
759 # This is the cache used for 'main' namespaces
758 # This is the cache used for 'main' namespaces
760 self._main_ns_cache = {}
759 self._main_ns_cache = {}
761 # And this is the single instance of FakeModule whose __dict__ we keep
760 # And this is the single instance of FakeModule whose __dict__ we keep
762 # copying and clearing for reuse on each %run
761 # copying and clearing for reuse on each %run
763 self._user_main_module = FakeModule()
762 self._user_main_module = FakeModule()
764
763
765 # A table holding all the namespaces IPython deals with, so that
764 # A table holding all the namespaces IPython deals with, so that
766 # introspection facilities can search easily.
765 # introspection facilities can search easily.
767 self.ns_table = {'user':user_ns,
766 self.ns_table = {'user':user_ns,
768 'user_global':user_global_ns,
767 'user_global':user_global_ns,
769 'internal':self.internal_ns,
768 'internal':self.internal_ns,
770 'builtin':__builtin__.__dict__
769 'builtin':__builtin__.__dict__
771 }
770 }
772
771
773 # Similarly, track all namespaces where references can be held and that
772 # Similarly, track all namespaces where references can be held and that
774 # we can safely clear (so it can NOT include builtin). This one can be
773 # we can safely clear (so it can NOT include builtin). This one can be
775 # a simple list.
774 # a simple list.
776 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
775 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
777 self.internal_ns, self._main_ns_cache ]
776 self.internal_ns, self._main_ns_cache ]
778
777
779 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
778 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
780 """Return a valid local and global user interactive namespaces.
779 """Return a valid local and global user interactive namespaces.
781
780
782 This builds a dict with the minimal information needed to operate as a
781 This builds a dict with the minimal information needed to operate as a
783 valid IPython user namespace, which you can pass to the various
782 valid IPython user namespace, which you can pass to the various
784 embedding classes in ipython. The default implementation returns the
783 embedding classes in ipython. The default implementation returns the
785 same dict for both the locals and the globals to allow functions to
784 same dict for both the locals and the globals to allow functions to
786 refer to variables in the namespace. Customized implementations can
785 refer to variables in the namespace. Customized implementations can
787 return different dicts. The locals dictionary can actually be anything
786 return different dicts. The locals dictionary can actually be anything
788 following the basic mapping protocol of a dict, but the globals dict
787 following the basic mapping protocol of a dict, but the globals dict
789 must be a true dict, not even a subclass. It is recommended that any
788 must be a true dict, not even a subclass. It is recommended that any
790 custom object for the locals namespace synchronize with the globals
789 custom object for the locals namespace synchronize with the globals
791 dict somehow.
790 dict somehow.
792
791
793 Raises TypeError if the provided globals namespace is not a true dict.
792 Raises TypeError if the provided globals namespace is not a true dict.
794
793
795 Parameters
794 Parameters
796 ----------
795 ----------
797 user_ns : dict-like, optional
796 user_ns : dict-like, optional
798 The current user namespace. The items in this namespace should
797 The current user namespace. The items in this namespace should
799 be included in the output. If None, an appropriate blank
798 be included in the output. If None, an appropriate blank
800 namespace should be created.
799 namespace should be created.
801 user_global_ns : dict, optional
800 user_global_ns : dict, optional
802 The current user global namespace. The items in this namespace
801 The current user global namespace. The items in this namespace
803 should be included in the output. If None, an appropriate
802 should be included in the output. If None, an appropriate
804 blank namespace should be created.
803 blank namespace should be created.
805
804
806 Returns
805 Returns
807 -------
806 -------
808 A pair of dictionary-like object to be used as the local namespace
807 A pair of dictionary-like object to be used as the local namespace
809 of the interpreter and a dict to be used as the global namespace.
808 of the interpreter and a dict to be used as the global namespace.
810 """
809 """
811
810
812
811
813 # We must ensure that __builtin__ (without the final 's') is always
812 # We must ensure that __builtin__ (without the final 's') is always
814 # available and pointing to the __builtin__ *module*. For more details:
813 # available and pointing to the __builtin__ *module*. For more details:
815 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
814 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
816
815
817 if user_ns is None:
816 if user_ns is None:
818 # Set __name__ to __main__ to better match the behavior of the
817 # Set __name__ to __main__ to better match the behavior of the
819 # normal interpreter.
818 # normal interpreter.
820 user_ns = {'__name__' :'__main__',
819 user_ns = {'__name__' :'__main__',
821 '__builtin__' : __builtin__,
820 '__builtin__' : __builtin__,
822 '__builtins__' : __builtin__,
821 '__builtins__' : __builtin__,
823 }
822 }
824 else:
823 else:
825 user_ns.setdefault('__name__','__main__')
824 user_ns.setdefault('__name__','__main__')
826 user_ns.setdefault('__builtin__',__builtin__)
825 user_ns.setdefault('__builtin__',__builtin__)
827 user_ns.setdefault('__builtins__',__builtin__)
826 user_ns.setdefault('__builtins__',__builtin__)
828
827
829 if user_global_ns is None:
828 if user_global_ns is None:
830 user_global_ns = user_ns
829 user_global_ns = user_ns
831 if type(user_global_ns) is not dict:
830 if type(user_global_ns) is not dict:
832 raise TypeError("user_global_ns must be a true dict; got %r"
831 raise TypeError("user_global_ns must be a true dict; got %r"
833 % type(user_global_ns))
832 % type(user_global_ns))
834
833
835 return user_ns, user_global_ns
834 return user_ns, user_global_ns
836
835
837 def init_sys_modules(self):
836 def init_sys_modules(self):
838 # We need to insert into sys.modules something that looks like a
837 # We need to insert into sys.modules something that looks like a
839 # module but which accesses the IPython namespace, for shelve and
838 # module but which accesses the IPython namespace, for shelve and
840 # pickle to work interactively. Normally they rely on getting
839 # pickle to work interactively. Normally they rely on getting
841 # everything out of __main__, but for embedding purposes each IPython
840 # everything out of __main__, but for embedding purposes each IPython
842 # instance has its own private namespace, so we can't go shoving
841 # instance has its own private namespace, so we can't go shoving
843 # everything into __main__.
842 # everything into __main__.
844
843
845 # note, however, that we should only do this for non-embedded
844 # note, however, that we should only do this for non-embedded
846 # ipythons, which really mimic the __main__.__dict__ with their own
845 # ipythons, which really mimic the __main__.__dict__ with their own
847 # namespace. Embedded instances, on the other hand, should not do
846 # namespace. Embedded instances, on the other hand, should not do
848 # this because they need to manage the user local/global namespaces
847 # this because they need to manage the user local/global namespaces
849 # only, but they live within a 'normal' __main__ (meaning, they
848 # only, but they live within a 'normal' __main__ (meaning, they
850 # shouldn't overtake the execution environment of the script they're
849 # shouldn't overtake the execution environment of the script they're
851 # embedded in).
850 # embedded in).
852
851
853 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
852 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
854
853
855 try:
854 try:
856 main_name = self.user_ns['__name__']
855 main_name = self.user_ns['__name__']
857 except KeyError:
856 except KeyError:
858 raise KeyError('user_ns dictionary MUST have a "__name__" key')
857 raise KeyError('user_ns dictionary MUST have a "__name__" key')
859 else:
858 else:
860 sys.modules[main_name] = FakeModule(self.user_ns)
859 sys.modules[main_name] = FakeModule(self.user_ns)
861
860
862 def init_user_ns(self):
861 def init_user_ns(self):
863 """Initialize all user-visible namespaces to their minimum defaults.
862 """Initialize all user-visible namespaces to their minimum defaults.
864
863
865 Certain history lists are also initialized here, as they effectively
864 Certain history lists are also initialized here, as they effectively
866 act as user namespaces.
865 act as user namespaces.
867
866
868 Notes
867 Notes
869 -----
868 -----
870 All data structures here are only filled in, they are NOT reset by this
869 All data structures here are only filled in, they are NOT reset by this
871 method. If they were not empty before, data will simply be added to
870 method. If they were not empty before, data will simply be added to
872 therm.
871 therm.
873 """
872 """
874 # This function works in two parts: first we put a few things in
873 # This function works in two parts: first we put a few things in
875 # user_ns, and we sync that contents into user_ns_hidden so that these
874 # user_ns, and we sync that contents into user_ns_hidden so that these
876 # initial variables aren't shown by %who. After the sync, we add the
875 # initial variables aren't shown by %who. After the sync, we add the
877 # rest of what we *do* want the user to see with %who even on a new
876 # rest of what we *do* want the user to see with %who even on a new
878 # session (probably nothing, so theye really only see their own stuff)
877 # session (probably nothing, so theye really only see their own stuff)
879
878
880 # The user dict must *always* have a __builtin__ reference to the
879 # The user dict must *always* have a __builtin__ reference to the
881 # Python standard __builtin__ namespace, which must be imported.
880 # Python standard __builtin__ namespace, which must be imported.
882 # This is so that certain operations in prompt evaluation can be
881 # This is so that certain operations in prompt evaluation can be
883 # reliably executed with builtins. Note that we can NOT use
882 # reliably executed with builtins. Note that we can NOT use
884 # __builtins__ (note the 's'), because that can either be a dict or a
883 # __builtins__ (note the 's'), because that can either be a dict or a
885 # module, and can even mutate at runtime, depending on the context
884 # module, and can even mutate at runtime, depending on the context
886 # (Python makes no guarantees on it). In contrast, __builtin__ is
885 # (Python makes no guarantees on it). In contrast, __builtin__ is
887 # always a module object, though it must be explicitly imported.
886 # always a module object, though it must be explicitly imported.
888
887
889 # For more details:
888 # For more details:
890 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
889 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
891 ns = dict(__builtin__ = __builtin__)
890 ns = dict(__builtin__ = __builtin__)
892
891
893 # Put 'help' in the user namespace
892 # Put 'help' in the user namespace
894 try:
893 try:
895 from site import _Helper
894 from site import _Helper
896 ns['help'] = _Helper()
895 ns['help'] = _Helper()
897 except ImportError:
896 except ImportError:
898 warn('help() not available - check site.py')
897 warn('help() not available - check site.py')
899
898
900 # make global variables for user access to the histories
899 # make global variables for user access to the histories
901 ns['_ih'] = self.input_hist
900 ns['_ih'] = self.input_hist
902 ns['_oh'] = self.output_hist
901 ns['_oh'] = self.output_hist
903 ns['_dh'] = self.dir_hist
902 ns['_dh'] = self.dir_hist
904
903
905 ns['_sh'] = shadowns
904 ns['_sh'] = shadowns
906
905
907 # user aliases to input and output histories. These shouldn't show up
906 # user aliases to input and output histories. These shouldn't show up
908 # in %who, as they can have very large reprs.
907 # in %who, as they can have very large reprs.
909 ns['In'] = self.input_hist
908 ns['In'] = self.input_hist
910 ns['Out'] = self.output_hist
909 ns['Out'] = self.output_hist
911
910
912 # Store myself as the public api!!!
911 # Store myself as the public api!!!
913 ns['get_ipython'] = self.get_ipython
912 ns['get_ipython'] = self.get_ipython
914
913
915 # Sync what we've added so far to user_ns_hidden so these aren't seen
914 # Sync what we've added so far to user_ns_hidden so these aren't seen
916 # by %who
915 # by %who
917 self.user_ns_hidden.update(ns)
916 self.user_ns_hidden.update(ns)
918
917
919 # Anything put into ns now would show up in %who. Think twice before
918 # Anything put into ns now would show up in %who. Think twice before
920 # putting anything here, as we really want %who to show the user their
919 # putting anything here, as we really want %who to show the user their
921 # stuff, not our variables.
920 # stuff, not our variables.
922
921
923 # Finally, update the real user's namespace
922 # Finally, update the real user's namespace
924 self.user_ns.update(ns)
923 self.user_ns.update(ns)
925
924
926
925
927 def reset(self):
926 def reset(self):
928 """Clear all internal namespaces.
927 """Clear all internal namespaces.
929
928
930 Note that this is much more aggressive than %reset, since it clears
929 Note that this is much more aggressive than %reset, since it clears
931 fully all namespaces, as well as all input/output lists.
930 fully all namespaces, as well as all input/output lists.
932 """
931 """
933 for ns in self.ns_refs_table:
932 for ns in self.ns_refs_table:
934 ns.clear()
933 ns.clear()
935
934
936 self.alias_manager.clear_aliases()
935 self.alias_manager.clear_aliases()
937
936
938 # Clear input and output histories
937 # Clear input and output histories
939 self.input_hist[:] = []
938 self.input_hist[:] = []
940 self.input_hist_raw[:] = []
939 self.input_hist_raw[:] = []
941 self.output_hist.clear()
940 self.output_hist.clear()
942
941
943 # Restore the user namespaces to minimal usability
942 # Restore the user namespaces to minimal usability
944 self.init_user_ns()
943 self.init_user_ns()
945
944
946 # Restore the default and user aliases
945 # Restore the default and user aliases
947 self.alias_manager.init_aliases()
946 self.alias_manager.init_aliases()
948
947
949 def reset_selective(self, regex=None):
948 def reset_selective(self, regex=None):
950 """Clear selective variables from internal namespaces based on a specified regular expression.
949 """Clear selective variables from internal namespaces based on a specified regular expression.
951
950
952 Parameters
951 Parameters
953 ----------
952 ----------
954 regex : string or compiled pattern, optional
953 regex : string or compiled pattern, optional
955 A regular expression pattern that will be used in searching variable names in the users
954 A regular expression pattern that will be used in searching variable names in the users
956 namespaces.
955 namespaces.
957 """
956 """
958 if regex is not None:
957 if regex is not None:
959 try:
958 try:
960 m = re.compile(regex)
959 m = re.compile(regex)
961 except TypeError:
960 except TypeError:
962 raise TypeError('regex must be a string or compiled pattern')
961 raise TypeError('regex must be a string or compiled pattern')
963 # Search for keys in each namespace that match the given regex
962 # Search for keys in each namespace that match the given regex
964 # If a match is found, delete the key/value pair.
963 # If a match is found, delete the key/value pair.
965 for ns in self.ns_refs_table:
964 for ns in self.ns_refs_table:
966 for var in ns:
965 for var in ns:
967 if m.search(var):
966 if m.search(var):
968 del ns[var]
967 del ns[var]
969
968
970 def push(self, variables, interactive=True):
969 def push(self, variables, interactive=True):
971 """Inject a group of variables into the IPython user namespace.
970 """Inject a group of variables into the IPython user namespace.
972
971
973 Parameters
972 Parameters
974 ----------
973 ----------
975 variables : dict, str or list/tuple of str
974 variables : dict, str or list/tuple of str
976 The variables to inject into the user's namespace. If a dict,
975 The variables to inject into the user's namespace. If a dict,
977 a simple update is done. If a str, the string is assumed to
976 a simple update is done. If a str, the string is assumed to
978 have variable names separated by spaces. A list/tuple of str
977 have variable names separated by spaces. A list/tuple of str
979 can also be used to give the variable names. If just the variable
978 can also be used to give the variable names. If just the variable
980 names are give (list/tuple/str) then the variable values looked
979 names are give (list/tuple/str) then the variable values looked
981 up in the callers frame.
980 up in the callers frame.
982 interactive : bool
981 interactive : bool
983 If True (default), the variables will be listed with the ``who``
982 If True (default), the variables will be listed with the ``who``
984 magic.
983 magic.
985 """
984 """
986 vdict = None
985 vdict = None
987
986
988 # We need a dict of name/value pairs to do namespace updates.
987 # We need a dict of name/value pairs to do namespace updates.
989 if isinstance(variables, dict):
988 if isinstance(variables, dict):
990 vdict = variables
989 vdict = variables
991 elif isinstance(variables, (basestring, list, tuple)):
990 elif isinstance(variables, (basestring, list, tuple)):
992 if isinstance(variables, basestring):
991 if isinstance(variables, basestring):
993 vlist = variables.split()
992 vlist = variables.split()
994 else:
993 else:
995 vlist = variables
994 vlist = variables
996 vdict = {}
995 vdict = {}
997 cf = sys._getframe(1)
996 cf = sys._getframe(1)
998 for name in vlist:
997 for name in vlist:
999 try:
998 try:
1000 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
999 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1001 except:
1000 except:
1002 print ('Could not get variable %s from %s' %
1001 print ('Could not get variable %s from %s' %
1003 (name,cf.f_code.co_name))
1002 (name,cf.f_code.co_name))
1004 else:
1003 else:
1005 raise ValueError('variables must be a dict/str/list/tuple')
1004 raise ValueError('variables must be a dict/str/list/tuple')
1006
1005
1007 # Propagate variables to user namespace
1006 # Propagate variables to user namespace
1008 self.user_ns.update(vdict)
1007 self.user_ns.update(vdict)
1009
1008
1010 # And configure interactive visibility
1009 # And configure interactive visibility
1011 config_ns = self.user_ns_hidden
1010 config_ns = self.user_ns_hidden
1012 if interactive:
1011 if interactive:
1013 for name, val in vdict.iteritems():
1012 for name, val in vdict.iteritems():
1014 config_ns.pop(name, None)
1013 config_ns.pop(name, None)
1015 else:
1014 else:
1016 for name,val in vdict.iteritems():
1015 for name,val in vdict.iteritems():
1017 config_ns[name] = val
1016 config_ns[name] = val
1018
1017
1019 #-------------------------------------------------------------------------
1018 #-------------------------------------------------------------------------
1020 # Things related to history management
1019 # Things related to history management
1021 #-------------------------------------------------------------------------
1020 #-------------------------------------------------------------------------
1022
1021
1023 def init_history(self):
1022 def init_history(self):
1024 # List of input with multi-line handling.
1023 # List of input with multi-line handling.
1025 self.input_hist = InputList()
1024 self.input_hist = InputList()
1026 # This one will hold the 'raw' input history, without any
1025 # This one will hold the 'raw' input history, without any
1027 # pre-processing. This will allow users to retrieve the input just as
1026 # pre-processing. This will allow users to retrieve the input just as
1028 # it was exactly typed in by the user, with %hist -r.
1027 # it was exactly typed in by the user, with %hist -r.
1029 self.input_hist_raw = InputList()
1028 self.input_hist_raw = InputList()
1030
1029
1031 # list of visited directories
1030 # list of visited directories
1032 try:
1031 try:
1033 self.dir_hist = [os.getcwd()]
1032 self.dir_hist = [os.getcwd()]
1034 except OSError:
1033 except OSError:
1035 self.dir_hist = []
1034 self.dir_hist = []
1036
1035
1037 # dict of output history
1036 # dict of output history
1038 self.output_hist = {}
1037 self.output_hist = {}
1039
1038
1040 # Now the history file
1039 # Now the history file
1041 if self.profile:
1040 if self.profile:
1042 histfname = 'history-%s' % self.profile
1041 histfname = 'history-%s' % self.profile
1043 else:
1042 else:
1044 histfname = 'history'
1043 histfname = 'history'
1045 self.histfile = os.path.join(self.ipython_dir, histfname)
1044 self.histfile = os.path.join(self.ipython_dir, histfname)
1046
1045
1047 # Fill the history zero entry, user counter starts at 1
1046 # Fill the history zero entry, user counter starts at 1
1048 self.input_hist.append('\n')
1047 self.input_hist.append('\n')
1049 self.input_hist_raw.append('\n')
1048 self.input_hist_raw.append('\n')
1050
1049
1051 def init_shadow_hist(self):
1050 def init_shadow_hist(self):
1052 try:
1051 try:
1053 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1052 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1054 except exceptions.UnicodeDecodeError:
1053 except exceptions.UnicodeDecodeError:
1055 print "Your ipython_dir can't be decoded to unicode!"
1054 print "Your ipython_dir can't be decoded to unicode!"
1056 print "Please set HOME environment variable to something that"
1055 print "Please set HOME environment variable to something that"
1057 print r"only has ASCII characters, e.g. c:\home"
1056 print r"only has ASCII characters, e.g. c:\home"
1058 print "Now it is", self.ipython_dir
1057 print "Now it is", self.ipython_dir
1059 sys.exit()
1058 sys.exit()
1060 self.shadowhist = ipcorehist.ShadowHist(self.db)
1059 self.shadowhist = ipcorehist.ShadowHist(self.db)
1061
1060
1062 def savehist(self):
1061 def savehist(self):
1063 """Save input history to a file (via readline library)."""
1062 """Save input history to a file (via readline library)."""
1064
1063
1065 try:
1064 try:
1066 self.readline.write_history_file(self.histfile)
1065 self.readline.write_history_file(self.histfile)
1067 except:
1066 except:
1068 print 'Unable to save IPython command history to file: ' + \
1067 print 'Unable to save IPython command history to file: ' + \
1069 `self.histfile`
1068 `self.histfile`
1070
1069
1071 def reloadhist(self):
1070 def reloadhist(self):
1072 """Reload the input history from disk file."""
1071 """Reload the input history from disk file."""
1073
1072
1074 try:
1073 try:
1075 self.readline.clear_history()
1074 self.readline.clear_history()
1076 self.readline.read_history_file(self.shell.histfile)
1075 self.readline.read_history_file(self.shell.histfile)
1077 except AttributeError:
1076 except AttributeError:
1078 pass
1077 pass
1079
1078
1080 def history_saving_wrapper(self, func):
1079 def history_saving_wrapper(self, func):
1081 """ Wrap func for readline history saving
1080 """ Wrap func for readline history saving
1082
1081
1083 Convert func into callable that saves & restores
1082 Convert func into callable that saves & restores
1084 history around the call """
1083 history around the call """
1085
1084
1086 if self.has_readline:
1085 if self.has_readline:
1087 from IPython.utils import rlineimpl as readline
1086 from IPython.utils import rlineimpl as readline
1088 else:
1087 else:
1089 return func
1088 return func
1090
1089
1091 def wrapper():
1090 def wrapper():
1092 self.savehist()
1091 self.savehist()
1093 try:
1092 try:
1094 func()
1093 func()
1095 finally:
1094 finally:
1096 readline.read_history_file(self.histfile)
1095 readline.read_history_file(self.histfile)
1097 return wrapper
1096 return wrapper
1098
1097
1099 #-------------------------------------------------------------------------
1098 #-------------------------------------------------------------------------
1100 # Things related to exception handling and tracebacks (not debugging)
1099 # Things related to exception handling and tracebacks (not debugging)
1101 #-------------------------------------------------------------------------
1100 #-------------------------------------------------------------------------
1102
1101
1103 def init_traceback_handlers(self, custom_exceptions):
1102 def init_traceback_handlers(self, custom_exceptions):
1104 # Syntax error handler.
1103 # Syntax error handler.
1105 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1104 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1106
1105
1107 # The interactive one is initialized with an offset, meaning we always
1106 # The interactive one is initialized with an offset, meaning we always
1108 # want to remove the topmost item in the traceback, which is our own
1107 # want to remove the topmost item in the traceback, which is our own
1109 # internal code. Valid modes: ['Plain','Context','Verbose']
1108 # internal code. Valid modes: ['Plain','Context','Verbose']
1110 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1109 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1111 color_scheme='NoColor',
1110 color_scheme='NoColor',
1112 tb_offset = 1)
1111 tb_offset = 1)
1113
1112
1114 # The instance will store a pointer to the system-wide exception hook,
1113 # The instance will store a pointer to the system-wide exception hook,
1115 # so that runtime code (such as magics) can access it. This is because
1114 # so that runtime code (such as magics) can access it. This is because
1116 # during the read-eval loop, it may get temporarily overwritten.
1115 # during the read-eval loop, it may get temporarily overwritten.
1117 self.sys_excepthook = sys.excepthook
1116 self.sys_excepthook = sys.excepthook
1118
1117
1119 # and add any custom exception handlers the user may have specified
1118 # and add any custom exception handlers the user may have specified
1120 self.set_custom_exc(*custom_exceptions)
1119 self.set_custom_exc(*custom_exceptions)
1121
1120
1122 # Set the exception mode
1121 # Set the exception mode
1123 self.InteractiveTB.set_mode(mode=self.xmode)
1122 self.InteractiveTB.set_mode(mode=self.xmode)
1124
1123
1125 def set_custom_exc(self,exc_tuple,handler):
1124 def set_custom_exc(self,exc_tuple,handler):
1126 """set_custom_exc(exc_tuple,handler)
1125 """set_custom_exc(exc_tuple,handler)
1127
1126
1128 Set a custom exception handler, which will be called if any of the
1127 Set a custom exception handler, which will be called if any of the
1129 exceptions in exc_tuple occur in the mainloop (specifically, in the
1128 exceptions in exc_tuple occur in the mainloop (specifically, in the
1130 runcode() method.
1129 runcode() method.
1131
1130
1132 Inputs:
1131 Inputs:
1133
1132
1134 - exc_tuple: a *tuple* of valid exceptions to call the defined
1133 - exc_tuple: a *tuple* of valid exceptions to call the defined
1135 handler for. It is very important that you use a tuple, and NOT A
1134 handler for. It is very important that you use a tuple, and NOT A
1136 LIST here, because of the way Python's except statement works. If
1135 LIST here, because of the way Python's except statement works. If
1137 you only want to trap a single exception, use a singleton tuple:
1136 you only want to trap a single exception, use a singleton tuple:
1138
1137
1139 exc_tuple == (MyCustomException,)
1138 exc_tuple == (MyCustomException,)
1140
1139
1141 - handler: this must be defined as a function with the following
1140 - handler: this must be defined as a function with the following
1142 basic interface: def my_handler(self,etype,value,tb).
1141 basic interface: def my_handler(self,etype,value,tb).
1143
1142
1144 This will be made into an instance method (via new.instancemethod)
1143 This will be made into an instance method (via new.instancemethod)
1145 of IPython itself, and it will be called if any of the exceptions
1144 of IPython itself, and it will be called if any of the exceptions
1146 listed in the exc_tuple are caught. If the handler is None, an
1145 listed in the exc_tuple are caught. If the handler is None, an
1147 internal basic one is used, which just prints basic info.
1146 internal basic one is used, which just prints basic info.
1148
1147
1149 WARNING: by putting in your own exception handler into IPython's main
1148 WARNING: by putting in your own exception handler into IPython's main
1150 execution loop, you run a very good chance of nasty crashes. This
1149 execution loop, you run a very good chance of nasty crashes. This
1151 facility should only be used if you really know what you are doing."""
1150 facility should only be used if you really know what you are doing."""
1152
1151
1153 assert type(exc_tuple)==type(()) , \
1152 assert type(exc_tuple)==type(()) , \
1154 "The custom exceptions must be given AS A TUPLE."
1153 "The custom exceptions must be given AS A TUPLE."
1155
1154
1156 def dummy_handler(self,etype,value,tb):
1155 def dummy_handler(self,etype,value,tb):
1157 print '*** Simple custom exception handler ***'
1156 print '*** Simple custom exception handler ***'
1158 print 'Exception type :',etype
1157 print 'Exception type :',etype
1159 print 'Exception value:',value
1158 print 'Exception value:',value
1160 print 'Traceback :',tb
1159 print 'Traceback :',tb
1161 print 'Source code :','\n'.join(self.buffer)
1160 print 'Source code :','\n'.join(self.buffer)
1162
1161
1163 if handler is None: handler = dummy_handler
1162 if handler is None: handler = dummy_handler
1164
1163
1165 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1164 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1166 self.custom_exceptions = exc_tuple
1165 self.custom_exceptions = exc_tuple
1167
1166
1168 def excepthook(self, etype, value, tb):
1167 def excepthook(self, etype, value, tb):
1169 """One more defense for GUI apps that call sys.excepthook.
1168 """One more defense for GUI apps that call sys.excepthook.
1170
1169
1171 GUI frameworks like wxPython trap exceptions and call
1170 GUI frameworks like wxPython trap exceptions and call
1172 sys.excepthook themselves. I guess this is a feature that
1171 sys.excepthook themselves. I guess this is a feature that
1173 enables them to keep running after exceptions that would
1172 enables them to keep running after exceptions that would
1174 otherwise kill their mainloop. This is a bother for IPython
1173 otherwise kill their mainloop. This is a bother for IPython
1175 which excepts to catch all of the program exceptions with a try:
1174 which excepts to catch all of the program exceptions with a try:
1176 except: statement.
1175 except: statement.
1177
1176
1178 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1177 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1179 any app directly invokes sys.excepthook, it will look to the user like
1178 any app directly invokes sys.excepthook, it will look to the user like
1180 IPython crashed. In order to work around this, we can disable the
1179 IPython crashed. In order to work around this, we can disable the
1181 CrashHandler and replace it with this excepthook instead, which prints a
1180 CrashHandler and replace it with this excepthook instead, which prints a
1182 regular traceback using our InteractiveTB. In this fashion, apps which
1181 regular traceback using our InteractiveTB. In this fashion, apps which
1183 call sys.excepthook will generate a regular-looking exception from
1182 call sys.excepthook will generate a regular-looking exception from
1184 IPython, and the CrashHandler will only be triggered by real IPython
1183 IPython, and the CrashHandler will only be triggered by real IPython
1185 crashes.
1184 crashes.
1186
1185
1187 This hook should be used sparingly, only in places which are not likely
1186 This hook should be used sparingly, only in places which are not likely
1188 to be true IPython errors.
1187 to be true IPython errors.
1189 """
1188 """
1190 self.showtraceback((etype,value,tb),tb_offset=0)
1189 self.showtraceback((etype,value,tb),tb_offset=0)
1191
1190
1192 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1191 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1193 exception_only=False):
1192 exception_only=False):
1194 """Display the exception that just occurred.
1193 """Display the exception that just occurred.
1195
1194
1196 If nothing is known about the exception, this is the method which
1195 If nothing is known about the exception, this is the method which
1197 should be used throughout the code for presenting user tracebacks,
1196 should be used throughout the code for presenting user tracebacks,
1198 rather than directly invoking the InteractiveTB object.
1197 rather than directly invoking the InteractiveTB object.
1199
1198
1200 A specific showsyntaxerror() also exists, but this method can take
1199 A specific showsyntaxerror() also exists, but this method can take
1201 care of calling it if needed, so unless you are explicitly catching a
1200 care of calling it if needed, so unless you are explicitly catching a
1202 SyntaxError exception, don't try to analyze the stack manually and
1201 SyntaxError exception, don't try to analyze the stack manually and
1203 simply call this method."""
1202 simply call this method."""
1204
1203
1205 try:
1204 try:
1206 if exc_tuple is None:
1205 if exc_tuple is None:
1207 etype, value, tb = sys.exc_info()
1206 etype, value, tb = sys.exc_info()
1208 else:
1207 else:
1209 etype, value, tb = exc_tuple
1208 etype, value, tb = exc_tuple
1210
1209
1211 if etype is None:
1210 if etype is None:
1212 if hasattr(sys, 'last_type'):
1211 if hasattr(sys, 'last_type'):
1213 etype, value, tb = sys.last_type, sys.last_value, \
1212 etype, value, tb = sys.last_type, sys.last_value, \
1214 sys.last_traceback
1213 sys.last_traceback
1215 else:
1214 else:
1216 self.write('No traceback available to show.\n')
1215 self.write('No traceback available to show.\n')
1217 return
1216 return
1218
1217
1219 if etype is SyntaxError:
1218 if etype is SyntaxError:
1220 # Though this won't be called by syntax errors in the input
1219 # Though this won't be called by syntax errors in the input
1221 # line, there may be SyntaxError cases whith imported code.
1220 # line, there may be SyntaxError cases whith imported code.
1222 self.showsyntaxerror(filename)
1221 self.showsyntaxerror(filename)
1223 elif etype is UsageError:
1222 elif etype is UsageError:
1224 print "UsageError:", value
1223 print "UsageError:", value
1225 else:
1224 else:
1226 # WARNING: these variables are somewhat deprecated and not
1225 # WARNING: these variables are somewhat deprecated and not
1227 # necessarily safe to use in a threaded environment, but tools
1226 # necessarily safe to use in a threaded environment, but tools
1228 # like pdb depend on their existence, so let's set them. If we
1227 # like pdb depend on their existence, so let's set them. If we
1229 # find problems in the field, we'll need to revisit their use.
1228 # find problems in the field, we'll need to revisit their use.
1230 sys.last_type = etype
1229 sys.last_type = etype
1231 sys.last_value = value
1230 sys.last_value = value
1232 sys.last_traceback = tb
1231 sys.last_traceback = tb
1233
1232
1234 if etype in self.custom_exceptions:
1233 if etype in self.custom_exceptions:
1235 self.CustomTB(etype,value,tb)
1234 self.CustomTB(etype,value,tb)
1236 else:
1235 else:
1237 if exception_only:
1236 if exception_only:
1238 m = ('An exception has occurred, use %tb to see the '
1237 m = ('An exception has occurred, use %tb to see the '
1239 'full traceback.')
1238 'full traceback.')
1240 print m
1239 print m
1241 self.InteractiveTB.show_exception_only(etype, value)
1240 self.InteractiveTB.show_exception_only(etype, value)
1242 else:
1241 else:
1243 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1242 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1244 if self.InteractiveTB.call_pdb:
1243 if self.InteractiveTB.call_pdb:
1245 # pdb mucks up readline, fix it back
1244 # pdb mucks up readline, fix it back
1246 self.set_completer()
1245 self.set_completer()
1247
1246
1248 except KeyboardInterrupt:
1247 except KeyboardInterrupt:
1249 self.write("\nKeyboardInterrupt\n")
1248 self.write("\nKeyboardInterrupt\n")
1250
1249
1251
1250
1252 def showsyntaxerror(self, filename=None):
1251 def showsyntaxerror(self, filename=None):
1253 """Display the syntax error that just occurred.
1252 """Display the syntax error that just occurred.
1254
1253
1255 This doesn't display a stack trace because there isn't one.
1254 This doesn't display a stack trace because there isn't one.
1256
1255
1257 If a filename is given, it is stuffed in the exception instead
1256 If a filename is given, it is stuffed in the exception instead
1258 of what was there before (because Python's parser always uses
1257 of what was there before (because Python's parser always uses
1259 "<string>" when reading from a string).
1258 "<string>" when reading from a string).
1260 """
1259 """
1261 etype, value, last_traceback = sys.exc_info()
1260 etype, value, last_traceback = sys.exc_info()
1262
1261
1263 # See note about these variables in showtraceback() above
1262 # See note about these variables in showtraceback() above
1264 sys.last_type = etype
1263 sys.last_type = etype
1265 sys.last_value = value
1264 sys.last_value = value
1266 sys.last_traceback = last_traceback
1265 sys.last_traceback = last_traceback
1267
1266
1268 if filename and etype is SyntaxError:
1267 if filename and etype is SyntaxError:
1269 # Work hard to stuff the correct filename in the exception
1268 # Work hard to stuff the correct filename in the exception
1270 try:
1269 try:
1271 msg, (dummy_filename, lineno, offset, line) = value
1270 msg, (dummy_filename, lineno, offset, line) = value
1272 except:
1271 except:
1273 # Not the format we expect; leave it alone
1272 # Not the format we expect; leave it alone
1274 pass
1273 pass
1275 else:
1274 else:
1276 # Stuff in the right filename
1275 # Stuff in the right filename
1277 try:
1276 try:
1278 # Assume SyntaxError is a class exception
1277 # Assume SyntaxError is a class exception
1279 value = SyntaxError(msg, (filename, lineno, offset, line))
1278 value = SyntaxError(msg, (filename, lineno, offset, line))
1280 except:
1279 except:
1281 # If that failed, assume SyntaxError is a string
1280 # If that failed, assume SyntaxError is a string
1282 value = msg, (filename, lineno, offset, line)
1281 value = msg, (filename, lineno, offset, line)
1283 self.SyntaxTB(etype,value,[])
1282 self.SyntaxTB(etype,value,[])
1284
1283
1285 #-------------------------------------------------------------------------
1284 #-------------------------------------------------------------------------
1286 # Things related to tab completion
1285 # Things related to tab completion
1287 #-------------------------------------------------------------------------
1286 #-------------------------------------------------------------------------
1288
1287
1289 def complete(self, text):
1288 def complete(self, text):
1290 """Return a sorted list of all possible completions on text.
1289 """Return a sorted list of all possible completions on text.
1291
1290
1292 Inputs:
1291 Inputs:
1293
1292
1294 - text: a string of text to be completed on.
1293 - text: a string of text to be completed on.
1295
1294
1296 This is a wrapper around the completion mechanism, similar to what
1295 This is a wrapper around the completion mechanism, similar to what
1297 readline does at the command line when the TAB key is hit. By
1296 readline does at the command line when the TAB key is hit. By
1298 exposing it as a method, it can be used by other non-readline
1297 exposing it as a method, it can be used by other non-readline
1299 environments (such as GUIs) for text completion.
1298 environments (such as GUIs) for text completion.
1300
1299
1301 Simple usage example:
1300 Simple usage example:
1302
1301
1303 In [7]: x = 'hello'
1302 In [7]: x = 'hello'
1304
1303
1305 In [8]: x
1304 In [8]: x
1306 Out[8]: 'hello'
1305 Out[8]: 'hello'
1307
1306
1308 In [9]: print x
1307 In [9]: print x
1309 hello
1308 hello
1310
1309
1311 In [10]: _ip.complete('x.l')
1310 In [10]: _ip.complete('x.l')
1312 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1311 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1313 """
1312 """
1314
1313
1315 # Inject names into __builtin__ so we can complete on the added names.
1314 # Inject names into __builtin__ so we can complete on the added names.
1316 with self.builtin_trap:
1315 with self.builtin_trap:
1317 complete = self.Completer.complete
1316 complete = self.Completer.complete
1318 state = 0
1317 state = 0
1319 # use a dict so we get unique keys, since ipyhton's multiple
1318 # use a dict so we get unique keys, since ipyhton's multiple
1320 # completers can return duplicates. When we make 2.4 a requirement,
1319 # completers can return duplicates. When we make 2.4 a requirement,
1321 # start using sets instead, which are faster.
1320 # start using sets instead, which are faster.
1322 comps = {}
1321 comps = {}
1323 while True:
1322 while True:
1324 newcomp = complete(text,state,line_buffer=text)
1323 newcomp = complete(text,state,line_buffer=text)
1325 if newcomp is None:
1324 if newcomp is None:
1326 break
1325 break
1327 comps[newcomp] = 1
1326 comps[newcomp] = 1
1328 state += 1
1327 state += 1
1329 outcomps = comps.keys()
1328 outcomps = comps.keys()
1330 outcomps.sort()
1329 outcomps.sort()
1331 #print "T:",text,"OC:",outcomps # dbg
1330 #print "T:",text,"OC:",outcomps # dbg
1332 #print "vars:",self.user_ns.keys()
1331 #print "vars:",self.user_ns.keys()
1333 return outcomps
1332 return outcomps
1334
1333
1335 def set_custom_completer(self,completer,pos=0):
1334 def set_custom_completer(self,completer,pos=0):
1336 """Adds a new custom completer function.
1335 """Adds a new custom completer function.
1337
1336
1338 The position argument (defaults to 0) is the index in the completers
1337 The position argument (defaults to 0) is the index in the completers
1339 list where you want the completer to be inserted."""
1338 list where you want the completer to be inserted."""
1340
1339
1341 newcomp = new.instancemethod(completer,self.Completer,
1340 newcomp = new.instancemethod(completer,self.Completer,
1342 self.Completer.__class__)
1341 self.Completer.__class__)
1343 self.Completer.matchers.insert(pos,newcomp)
1342 self.Completer.matchers.insert(pos,newcomp)
1344
1343
1345 def set_completer(self):
1344 def set_completer(self):
1346 """Reset readline's completer to be our own."""
1345 """Reset readline's completer to be our own."""
1347 self.readline.set_completer(self.Completer.complete)
1346 self.readline.set_completer(self.Completer.complete)
1348
1347
1349 def set_completer_frame(self, frame=None):
1348 def set_completer_frame(self, frame=None):
1350 """Set the frame of the completer."""
1349 """Set the frame of the completer."""
1351 if frame:
1350 if frame:
1352 self.Completer.namespace = frame.f_locals
1351 self.Completer.namespace = frame.f_locals
1353 self.Completer.global_namespace = frame.f_globals
1352 self.Completer.global_namespace = frame.f_globals
1354 else:
1353 else:
1355 self.Completer.namespace = self.user_ns
1354 self.Completer.namespace = self.user_ns
1356 self.Completer.global_namespace = self.user_global_ns
1355 self.Completer.global_namespace = self.user_global_ns
1357
1356
1358 #-------------------------------------------------------------------------
1357 #-------------------------------------------------------------------------
1359 # Things related to readline
1358 # Things related to readline
1360 #-------------------------------------------------------------------------
1359 #-------------------------------------------------------------------------
1361
1360
1362 def init_readline(self):
1361 def init_readline(self):
1363 """Command history completion/saving/reloading."""
1362 """Command history completion/saving/reloading."""
1364
1363
1365 if self.readline_use:
1364 if self.readline_use:
1366 import IPython.utils.rlineimpl as readline
1365 import IPython.utils.rlineimpl as readline
1367
1366
1368 self.rl_next_input = None
1367 self.rl_next_input = None
1369 self.rl_do_indent = False
1368 self.rl_do_indent = False
1370
1369
1371 if not self.readline_use or not readline.have_readline:
1370 if not self.readline_use or not readline.have_readline:
1372 self.has_readline = False
1371 self.has_readline = False
1373 self.readline = None
1372 self.readline = None
1374 # Set a number of methods that depend on readline to be no-op
1373 # Set a number of methods that depend on readline to be no-op
1375 self.savehist = no_op
1374 self.savehist = no_op
1376 self.reloadhist = no_op
1375 self.reloadhist = no_op
1377 self.set_completer = no_op
1376 self.set_completer = no_op
1378 self.set_custom_completer = no_op
1377 self.set_custom_completer = no_op
1379 self.set_completer_frame = no_op
1378 self.set_completer_frame = no_op
1380 warn('Readline services not available or not loaded.')
1379 warn('Readline services not available or not loaded.')
1381 else:
1380 else:
1382 self.has_readline = True
1381 self.has_readline = True
1383 self.readline = readline
1382 self.readline = readline
1384 sys.modules['readline'] = readline
1383 sys.modules['readline'] = readline
1385 import atexit
1384 import atexit
1386 from IPython.core.completer import IPCompleter
1385 from IPython.core.completer import IPCompleter
1387 self.Completer = IPCompleter(self,
1386 self.Completer = IPCompleter(self,
1388 self.user_ns,
1387 self.user_ns,
1389 self.user_global_ns,
1388 self.user_global_ns,
1390 self.readline_omit__names,
1389 self.readline_omit__names,
1391 self.alias_manager.alias_table)
1390 self.alias_manager.alias_table)
1392 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1391 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1393 self.strdispatchers['complete_command'] = sdisp
1392 self.strdispatchers['complete_command'] = sdisp
1394 self.Completer.custom_completers = sdisp
1393 self.Completer.custom_completers = sdisp
1395 # Platform-specific configuration
1394 # Platform-specific configuration
1396 if os.name == 'nt':
1395 if os.name == 'nt':
1397 self.readline_startup_hook = readline.set_pre_input_hook
1396 self.readline_startup_hook = readline.set_pre_input_hook
1398 else:
1397 else:
1399 self.readline_startup_hook = readline.set_startup_hook
1398 self.readline_startup_hook = readline.set_startup_hook
1400
1399
1401 # Load user's initrc file (readline config)
1400 # Load user's initrc file (readline config)
1402 # Or if libedit is used, load editrc.
1401 # Or if libedit is used, load editrc.
1403 inputrc_name = os.environ.get('INPUTRC')
1402 inputrc_name = os.environ.get('INPUTRC')
1404 if inputrc_name is None:
1403 if inputrc_name is None:
1405 home_dir = get_home_dir()
1404 home_dir = get_home_dir()
1406 if home_dir is not None:
1405 if home_dir is not None:
1407 inputrc_name = '.inputrc'
1406 inputrc_name = '.inputrc'
1408 if readline.uses_libedit:
1407 if readline.uses_libedit:
1409 inputrc_name = '.editrc'
1408 inputrc_name = '.editrc'
1410 inputrc_name = os.path.join(home_dir, inputrc_name)
1409 inputrc_name = os.path.join(home_dir, inputrc_name)
1411 if os.path.isfile(inputrc_name):
1410 if os.path.isfile(inputrc_name):
1412 try:
1411 try:
1413 readline.read_init_file(inputrc_name)
1412 readline.read_init_file(inputrc_name)
1414 except:
1413 except:
1415 warn('Problems reading readline initialization file <%s>'
1414 warn('Problems reading readline initialization file <%s>'
1416 % inputrc_name)
1415 % inputrc_name)
1417
1416
1418 # save this in sys so embedded copies can restore it properly
1417 # save this in sys so embedded copies can restore it properly
1419 sys.ipcompleter = self.Completer.complete
1418 sys.ipcompleter = self.Completer.complete
1420 self.set_completer()
1419 self.set_completer()
1421
1420
1422 # Configure readline according to user's prefs
1421 # Configure readline according to user's prefs
1423 # This is only done if GNU readline is being used. If libedit
1422 # This is only done if GNU readline is being used. If libedit
1424 # is being used (as on Leopard) the readline config is
1423 # is being used (as on Leopard) the readline config is
1425 # not run as the syntax for libedit is different.
1424 # not run as the syntax for libedit is different.
1426 if not readline.uses_libedit:
1425 if not readline.uses_libedit:
1427 for rlcommand in self.readline_parse_and_bind:
1426 for rlcommand in self.readline_parse_and_bind:
1428 #print "loading rl:",rlcommand # dbg
1427 #print "loading rl:",rlcommand # dbg
1429 readline.parse_and_bind(rlcommand)
1428 readline.parse_and_bind(rlcommand)
1430
1429
1431 # Remove some chars from the delimiters list. If we encounter
1430 # Remove some chars from the delimiters list. If we encounter
1432 # unicode chars, discard them.
1431 # unicode chars, discard them.
1433 delims = readline.get_completer_delims().encode("ascii", "ignore")
1432 delims = readline.get_completer_delims().encode("ascii", "ignore")
1434 delims = delims.translate(string._idmap,
1433 delims = delims.translate(string._idmap,
1435 self.readline_remove_delims)
1434 self.readline_remove_delims)
1436 readline.set_completer_delims(delims)
1435 readline.set_completer_delims(delims)
1437 # otherwise we end up with a monster history after a while:
1436 # otherwise we end up with a monster history after a while:
1438 readline.set_history_length(1000)
1437 readline.set_history_length(1000)
1439 try:
1438 try:
1440 #print '*** Reading readline history' # dbg
1439 #print '*** Reading readline history' # dbg
1441 readline.read_history_file(self.histfile)
1440 readline.read_history_file(self.histfile)
1442 except IOError:
1441 except IOError:
1443 pass # It doesn't exist yet.
1442 pass # It doesn't exist yet.
1444
1443
1445 atexit.register(self.atexit_operations)
1444 atexit.register(self.atexit_operations)
1446 del atexit
1445 del atexit
1447
1446
1448 # Configure auto-indent for all platforms
1447 # Configure auto-indent for all platforms
1449 self.set_autoindent(self.autoindent)
1448 self.set_autoindent(self.autoindent)
1450
1449
1451 def set_next_input(self, s):
1450 def set_next_input(self, s):
1452 """ Sets the 'default' input string for the next command line.
1451 """ Sets the 'default' input string for the next command line.
1453
1452
1454 Requires readline.
1453 Requires readline.
1455
1454
1456 Example:
1455 Example:
1457
1456
1458 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1457 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1459 [D:\ipython]|2> Hello Word_ # cursor is here
1458 [D:\ipython]|2> Hello Word_ # cursor is here
1460 """
1459 """
1461
1460
1462 self.rl_next_input = s
1461 self.rl_next_input = s
1463
1462
1464 # Maybe move this to the terminal subclass?
1463 # Maybe move this to the terminal subclass?
1465 def pre_readline(self):
1464 def pre_readline(self):
1466 """readline hook to be used at the start of each line.
1465 """readline hook to be used at the start of each line.
1467
1466
1468 Currently it handles auto-indent only."""
1467 Currently it handles auto-indent only."""
1469
1468
1470 if self.rl_do_indent:
1469 if self.rl_do_indent:
1471 self.readline.insert_text(self._indent_current_str())
1470 self.readline.insert_text(self._indent_current_str())
1472 if self.rl_next_input is not None:
1471 if self.rl_next_input is not None:
1473 self.readline.insert_text(self.rl_next_input)
1472 self.readline.insert_text(self.rl_next_input)
1474 self.rl_next_input = None
1473 self.rl_next_input = None
1475
1474
1476 def _indent_current_str(self):
1475 def _indent_current_str(self):
1477 """return the current level of indentation as a string"""
1476 """return the current level of indentation as a string"""
1478 return self.indent_current_nsp * ' '
1477 return self.indent_current_nsp * ' '
1479
1478
1480 #-------------------------------------------------------------------------
1479 #-------------------------------------------------------------------------
1481 # Things related to magics
1480 # Things related to magics
1482 #-------------------------------------------------------------------------
1481 #-------------------------------------------------------------------------
1483
1482
1484 def init_magics(self):
1483 def init_magics(self):
1485 # Set user colors (don't do it in the constructor above so that it
1484 # FIXME: Move the color initialization to the DisplayHook, which
1486 # doesn't crash if colors option is invalid)
1485 # should be split into a prompt manager and displayhook. We probably
1486 # even need a centralize colors management object.
1487 self.magic_colors(self.colors)
1487 self.magic_colors(self.colors)
1488 # History was moved to a separate module
1488 # History was moved to a separate module
1489 from . import history
1489 from . import history
1490 history.init_ipython(self)
1490 history.init_ipython(self)
1491
1491
1492 def magic(self,arg_s):
1492 def magic(self,arg_s):
1493 """Call a magic function by name.
1493 """Call a magic function by name.
1494
1494
1495 Input: a string containing the name of the magic function to call and any
1495 Input: a string containing the name of the magic function to call and any
1496 additional arguments to be passed to the magic.
1496 additional arguments to be passed to the magic.
1497
1497
1498 magic('name -opt foo bar') is equivalent to typing at the ipython
1498 magic('name -opt foo bar') is equivalent to typing at the ipython
1499 prompt:
1499 prompt:
1500
1500
1501 In[1]: %name -opt foo bar
1501 In[1]: %name -opt foo bar
1502
1502
1503 To call a magic without arguments, simply use magic('name').
1503 To call a magic without arguments, simply use magic('name').
1504
1504
1505 This provides a proper Python function to call IPython's magics in any
1505 This provides a proper Python function to call IPython's magics in any
1506 valid Python code you can type at the interpreter, including loops and
1506 valid Python code you can type at the interpreter, including loops and
1507 compound statements.
1507 compound statements.
1508 """
1508 """
1509 args = arg_s.split(' ',1)
1509 args = arg_s.split(' ',1)
1510 magic_name = args[0]
1510 magic_name = args[0]
1511 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1511 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1512
1512
1513 try:
1513 try:
1514 magic_args = args[1]
1514 magic_args = args[1]
1515 except IndexError:
1515 except IndexError:
1516 magic_args = ''
1516 magic_args = ''
1517 fn = getattr(self,'magic_'+magic_name,None)
1517 fn = getattr(self,'magic_'+magic_name,None)
1518 if fn is None:
1518 if fn is None:
1519 error("Magic function `%s` not found." % magic_name)
1519 error("Magic function `%s` not found." % magic_name)
1520 else:
1520 else:
1521 magic_args = self.var_expand(magic_args,1)
1521 magic_args = self.var_expand(magic_args,1)
1522 with nested(self.builtin_trap,):
1522 with nested(self.builtin_trap,):
1523 result = fn(magic_args)
1523 result = fn(magic_args)
1524 return result
1524 return result
1525
1525
1526 def define_magic(self, magicname, func):
1526 def define_magic(self, magicname, func):
1527 """Expose own function as magic function for ipython
1527 """Expose own function as magic function for ipython
1528
1528
1529 def foo_impl(self,parameter_s=''):
1529 def foo_impl(self,parameter_s=''):
1530 'My very own magic!. (Use docstrings, IPython reads them).'
1530 'My very own magic!. (Use docstrings, IPython reads them).'
1531 print 'Magic function. Passed parameter is between < >:'
1531 print 'Magic function. Passed parameter is between < >:'
1532 print '<%s>' % parameter_s
1532 print '<%s>' % parameter_s
1533 print 'The self object is:',self
1533 print 'The self object is:',self
1534
1534
1535 self.define_magic('foo',foo_impl)
1535 self.define_magic('foo',foo_impl)
1536 """
1536 """
1537
1537
1538 import new
1538 import new
1539 im = new.instancemethod(func,self, self.__class__)
1539 im = new.instancemethod(func,self, self.__class__)
1540 old = getattr(self, "magic_" + magicname, None)
1540 old = getattr(self, "magic_" + magicname, None)
1541 setattr(self, "magic_" + magicname, im)
1541 setattr(self, "magic_" + magicname, im)
1542 return old
1542 return old
1543
1543
1544 #-------------------------------------------------------------------------
1544 #-------------------------------------------------------------------------
1545 # Things related to macros
1545 # Things related to macros
1546 #-------------------------------------------------------------------------
1546 #-------------------------------------------------------------------------
1547
1547
1548 def define_macro(self, name, themacro):
1548 def define_macro(self, name, themacro):
1549 """Define a new macro
1549 """Define a new macro
1550
1550
1551 Parameters
1551 Parameters
1552 ----------
1552 ----------
1553 name : str
1553 name : str
1554 The name of the macro.
1554 The name of the macro.
1555 themacro : str or Macro
1555 themacro : str or Macro
1556 The action to do upon invoking the macro. If a string, a new
1556 The action to do upon invoking the macro. If a string, a new
1557 Macro object is created by passing the string to it.
1557 Macro object is created by passing the string to it.
1558 """
1558 """
1559
1559
1560 from IPython.core import macro
1560 from IPython.core import macro
1561
1561
1562 if isinstance(themacro, basestring):
1562 if isinstance(themacro, basestring):
1563 themacro = macro.Macro(themacro)
1563 themacro = macro.Macro(themacro)
1564 if not isinstance(themacro, macro.Macro):
1564 if not isinstance(themacro, macro.Macro):
1565 raise ValueError('A macro must be a string or a Macro instance.')
1565 raise ValueError('A macro must be a string or a Macro instance.')
1566 self.user_ns[name] = themacro
1566 self.user_ns[name] = themacro
1567
1567
1568 #-------------------------------------------------------------------------
1568 #-------------------------------------------------------------------------
1569 # Things related to the running of system commands
1569 # Things related to the running of system commands
1570 #-------------------------------------------------------------------------
1570 #-------------------------------------------------------------------------
1571
1571
1572 def system(self, cmd):
1572 def system(self, cmd):
1573 """Make a system call, using IPython."""
1573 """Make a system call, using IPython."""
1574 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1574 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1575
1575
1576 #-------------------------------------------------------------------------
1576 #-------------------------------------------------------------------------
1577 # Things related to aliases
1577 # Things related to aliases
1578 #-------------------------------------------------------------------------
1578 #-------------------------------------------------------------------------
1579
1579
1580 def init_alias(self):
1580 def init_alias(self):
1581 self.alias_manager = AliasManager(shell=self, config=self.config)
1581 self.alias_manager = AliasManager(shell=self, config=self.config)
1582 self.ns_table['alias'] = self.alias_manager.alias_table,
1582 self.ns_table['alias'] = self.alias_manager.alias_table,
1583
1583
1584 #-------------------------------------------------------------------------
1584 #-------------------------------------------------------------------------
1585 # Things related to extensions and plugins
1585 # Things related to extensions and plugins
1586 #-------------------------------------------------------------------------
1586 #-------------------------------------------------------------------------
1587
1587
1588 def init_extension_manager(self):
1588 def init_extension_manager(self):
1589 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1589 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1590
1590
1591 def init_plugin_manager(self):
1591 def init_plugin_manager(self):
1592 self.plugin_manager = PluginManager(config=self.config)
1592 self.plugin_manager = PluginManager(config=self.config)
1593
1593
1594 #-------------------------------------------------------------------------
1594 #-------------------------------------------------------------------------
1595 # Things related to the prefilter
1595 # Things related to the prefilter
1596 #-------------------------------------------------------------------------
1596 #-------------------------------------------------------------------------
1597
1597
1598 def init_prefilter(self):
1598 def init_prefilter(self):
1599 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1599 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1600 # Ultimately this will be refactored in the new interpreter code, but
1600 # Ultimately this will be refactored in the new interpreter code, but
1601 # for now, we should expose the main prefilter method (there's legacy
1601 # for now, we should expose the main prefilter method (there's legacy
1602 # code out there that may rely on this).
1602 # code out there that may rely on this).
1603 self.prefilter = self.prefilter_manager.prefilter_lines
1603 self.prefilter = self.prefilter_manager.prefilter_lines
1604
1604
1605 #-------------------------------------------------------------------------
1605 #-------------------------------------------------------------------------
1606 # Things related to the running of code
1606 # Things related to the running of code
1607 #-------------------------------------------------------------------------
1607 #-------------------------------------------------------------------------
1608
1608
1609 def ex(self, cmd):
1609 def ex(self, cmd):
1610 """Execute a normal python statement in user namespace."""
1610 """Execute a normal python statement in user namespace."""
1611 with nested(self.builtin_trap,):
1611 with nested(self.builtin_trap,):
1612 exec cmd in self.user_global_ns, self.user_ns
1612 exec cmd in self.user_global_ns, self.user_ns
1613
1613
1614 def ev(self, expr):
1614 def ev(self, expr):
1615 """Evaluate python expression expr in user namespace.
1615 """Evaluate python expression expr in user namespace.
1616
1616
1617 Returns the result of evaluation
1617 Returns the result of evaluation
1618 """
1618 """
1619 with nested(self.builtin_trap,):
1619 with nested(self.builtin_trap,):
1620 return eval(expr, self.user_global_ns, self.user_ns)
1620 return eval(expr, self.user_global_ns, self.user_ns)
1621
1621
1622 def safe_execfile(self, fname, *where, **kw):
1622 def safe_execfile(self, fname, *where, **kw):
1623 """A safe version of the builtin execfile().
1623 """A safe version of the builtin execfile().
1624
1624
1625 This version will never throw an exception, but instead print
1625 This version will never throw an exception, but instead print
1626 helpful error messages to the screen. This only works on pure
1626 helpful error messages to the screen. This only works on pure
1627 Python files with the .py extension.
1627 Python files with the .py extension.
1628
1628
1629 Parameters
1629 Parameters
1630 ----------
1630 ----------
1631 fname : string
1631 fname : string
1632 The name of the file to be executed.
1632 The name of the file to be executed.
1633 where : tuple
1633 where : tuple
1634 One or two namespaces, passed to execfile() as (globals,locals).
1634 One or two namespaces, passed to execfile() as (globals,locals).
1635 If only one is given, it is passed as both.
1635 If only one is given, it is passed as both.
1636 exit_ignore : bool (False)
1636 exit_ignore : bool (False)
1637 If True, then silence SystemExit for non-zero status (it is always
1637 If True, then silence SystemExit for non-zero status (it is always
1638 silenced for zero status, as it is so common).
1638 silenced for zero status, as it is so common).
1639 """
1639 """
1640 kw.setdefault('exit_ignore', False)
1640 kw.setdefault('exit_ignore', False)
1641
1641
1642 fname = os.path.abspath(os.path.expanduser(fname))
1642 fname = os.path.abspath(os.path.expanduser(fname))
1643
1643
1644 # Make sure we have a .py file
1644 # Make sure we have a .py file
1645 if not fname.endswith('.py'):
1645 if not fname.endswith('.py'):
1646 warn('File must end with .py to be run using execfile: <%s>' % fname)
1646 warn('File must end with .py to be run using execfile: <%s>' % fname)
1647
1647
1648 # Make sure we can open the file
1648 # Make sure we can open the file
1649 try:
1649 try:
1650 with open(fname) as thefile:
1650 with open(fname) as thefile:
1651 pass
1651 pass
1652 except:
1652 except:
1653 warn('Could not open file <%s> for safe execution.' % fname)
1653 warn('Could not open file <%s> for safe execution.' % fname)
1654 return
1654 return
1655
1655
1656 # Find things also in current directory. This is needed to mimic the
1656 # Find things also in current directory. This is needed to mimic the
1657 # behavior of running a script from the system command line, where
1657 # behavior of running a script from the system command line, where
1658 # Python inserts the script's directory into sys.path
1658 # Python inserts the script's directory into sys.path
1659 dname = os.path.dirname(fname)
1659 dname = os.path.dirname(fname)
1660
1660
1661 with prepended_to_syspath(dname):
1661 with prepended_to_syspath(dname):
1662 try:
1662 try:
1663 execfile(fname,*where)
1663 execfile(fname,*where)
1664 except SystemExit, status:
1664 except SystemExit, status:
1665 # If the call was made with 0 or None exit status (sys.exit(0)
1665 # If the call was made with 0 or None exit status (sys.exit(0)
1666 # or sys.exit() ), don't bother showing a traceback, as both of
1666 # or sys.exit() ), don't bother showing a traceback, as both of
1667 # these are considered normal by the OS:
1667 # these are considered normal by the OS:
1668 # > python -c'import sys;sys.exit(0)'; echo $?
1668 # > python -c'import sys;sys.exit(0)'; echo $?
1669 # 0
1669 # 0
1670 # > python -c'import sys;sys.exit()'; echo $?
1670 # > python -c'import sys;sys.exit()'; echo $?
1671 # 0
1671 # 0
1672 # For other exit status, we show the exception unless
1672 # For other exit status, we show the exception unless
1673 # explicitly silenced, but only in short form.
1673 # explicitly silenced, but only in short form.
1674 if status.code not in (0, None) and not kw['exit_ignore']:
1674 if status.code not in (0, None) and not kw['exit_ignore']:
1675 self.showtraceback(exception_only=True)
1675 self.showtraceback(exception_only=True)
1676 except:
1676 except:
1677 self.showtraceback()
1677 self.showtraceback()
1678
1678
1679 def safe_execfile_ipy(self, fname):
1679 def safe_execfile_ipy(self, fname):
1680 """Like safe_execfile, but for .ipy files with IPython syntax.
1680 """Like safe_execfile, but for .ipy files with IPython syntax.
1681
1681
1682 Parameters
1682 Parameters
1683 ----------
1683 ----------
1684 fname : str
1684 fname : str
1685 The name of the file to execute. The filename must have a
1685 The name of the file to execute. The filename must have a
1686 .ipy extension.
1686 .ipy extension.
1687 """
1687 """
1688 fname = os.path.abspath(os.path.expanduser(fname))
1688 fname = os.path.abspath(os.path.expanduser(fname))
1689
1689
1690 # Make sure we have a .py file
1690 # Make sure we have a .py file
1691 if not fname.endswith('.ipy'):
1691 if not fname.endswith('.ipy'):
1692 warn('File must end with .py to be run using execfile: <%s>' % fname)
1692 warn('File must end with .py to be run using execfile: <%s>' % fname)
1693
1693
1694 # Make sure we can open the file
1694 # Make sure we can open the file
1695 try:
1695 try:
1696 with open(fname) as thefile:
1696 with open(fname) as thefile:
1697 pass
1697 pass
1698 except:
1698 except:
1699 warn('Could not open file <%s> for safe execution.' % fname)
1699 warn('Could not open file <%s> for safe execution.' % fname)
1700 return
1700 return
1701
1701
1702 # Find things also in current directory. This is needed to mimic the
1702 # Find things also in current directory. This is needed to mimic the
1703 # behavior of running a script from the system command line, where
1703 # behavior of running a script from the system command line, where
1704 # Python inserts the script's directory into sys.path
1704 # Python inserts the script's directory into sys.path
1705 dname = os.path.dirname(fname)
1705 dname = os.path.dirname(fname)
1706
1706
1707 with prepended_to_syspath(dname):
1707 with prepended_to_syspath(dname):
1708 try:
1708 try:
1709 with open(fname) as thefile:
1709 with open(fname) as thefile:
1710 script = thefile.read()
1710 script = thefile.read()
1711 # self.runlines currently captures all exceptions
1711 # self.runlines currently captures all exceptions
1712 # raise in user code. It would be nice if there were
1712 # raise in user code. It would be nice if there were
1713 # versions of runlines, execfile that did raise, so
1713 # versions of runlines, execfile that did raise, so
1714 # we could catch the errors.
1714 # we could catch the errors.
1715 self.runlines(script, clean=True)
1715 self.runlines(script, clean=True)
1716 except:
1716 except:
1717 self.showtraceback()
1717 self.showtraceback()
1718 warn('Unknown failure executing file: <%s>' % fname)
1718 warn('Unknown failure executing file: <%s>' % fname)
1719
1719
1720 def runlines(self, lines, clean=False):
1720 def runlines(self, lines, clean=False):
1721 """Run a string of one or more lines of source.
1721 """Run a string of one or more lines of source.
1722
1722
1723 This method is capable of running a string containing multiple source
1723 This method is capable of running a string containing multiple source
1724 lines, as if they had been entered at the IPython prompt. Since it
1724 lines, as if they had been entered at the IPython prompt. Since it
1725 exposes IPython's processing machinery, the given strings can contain
1725 exposes IPython's processing machinery, the given strings can contain
1726 magic calls (%magic), special shell access (!cmd), etc.
1726 magic calls (%magic), special shell access (!cmd), etc.
1727 """
1727 """
1728
1728
1729 if isinstance(lines, (list, tuple)):
1729 if isinstance(lines, (list, tuple)):
1730 lines = '\n'.join(lines)
1730 lines = '\n'.join(lines)
1731
1731
1732 if clean:
1732 if clean:
1733 lines = self._cleanup_ipy_script(lines)
1733 lines = self._cleanup_ipy_script(lines)
1734
1734
1735 # We must start with a clean buffer, in case this is run from an
1735 # We must start with a clean buffer, in case this is run from an
1736 # interactive IPython session (via a magic, for example).
1736 # interactive IPython session (via a magic, for example).
1737 self.resetbuffer()
1737 self.resetbuffer()
1738 lines = lines.splitlines()
1738 lines = lines.splitlines()
1739 more = 0
1739 more = 0
1740
1740
1741 with nested(self.builtin_trap, self.display_trap):
1741 with nested(self.builtin_trap, self.display_trap):
1742 for line in lines:
1742 for line in lines:
1743 # skip blank lines so we don't mess up the prompt counter, but do
1743 # skip blank lines so we don't mess up the prompt counter, but do
1744 # NOT skip even a blank line if we are in a code block (more is
1744 # NOT skip even a blank line if we are in a code block (more is
1745 # true)
1745 # true)
1746
1746
1747 if line or more:
1747 if line or more:
1748 # push to raw history, so hist line numbers stay in sync
1748 # push to raw history, so hist line numbers stay in sync
1749 self.input_hist_raw.append("# " + line + "\n")
1749 self.input_hist_raw.append("# " + line + "\n")
1750 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1750 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1751 more = self.push_line(prefiltered)
1751 more = self.push_line(prefiltered)
1752 # IPython's runsource returns None if there was an error
1752 # IPython's runsource returns None if there was an error
1753 # compiling the code. This allows us to stop processing right
1753 # compiling the code. This allows us to stop processing right
1754 # away, so the user gets the error message at the right place.
1754 # away, so the user gets the error message at the right place.
1755 if more is None:
1755 if more is None:
1756 break
1756 break
1757 else:
1757 else:
1758 self.input_hist_raw.append("\n")
1758 self.input_hist_raw.append("\n")
1759 # final newline in case the input didn't have it, so that the code
1759 # final newline in case the input didn't have it, so that the code
1760 # actually does get executed
1760 # actually does get executed
1761 if more:
1761 if more:
1762 self.push_line('\n')
1762 self.push_line('\n')
1763
1763
1764 def runsource(self, source, filename='<input>', symbol='single'):
1764 def runsource(self, source, filename='<input>', symbol='single'):
1765 """Compile and run some source in the interpreter.
1765 """Compile and run some source in the interpreter.
1766
1766
1767 Arguments are as for compile_command().
1767 Arguments are as for compile_command().
1768
1768
1769 One several things can happen:
1769 One several things can happen:
1770
1770
1771 1) The input is incorrect; compile_command() raised an
1771 1) The input is incorrect; compile_command() raised an
1772 exception (SyntaxError or OverflowError). A syntax traceback
1772 exception (SyntaxError or OverflowError). A syntax traceback
1773 will be printed by calling the showsyntaxerror() method.
1773 will be printed by calling the showsyntaxerror() method.
1774
1774
1775 2) The input is incomplete, and more input is required;
1775 2) The input is incomplete, and more input is required;
1776 compile_command() returned None. Nothing happens.
1776 compile_command() returned None. Nothing happens.
1777
1777
1778 3) The input is complete; compile_command() returned a code
1778 3) The input is complete; compile_command() returned a code
1779 object. The code is executed by calling self.runcode() (which
1779 object. The code is executed by calling self.runcode() (which
1780 also handles run-time exceptions, except for SystemExit).
1780 also handles run-time exceptions, except for SystemExit).
1781
1781
1782 The return value is:
1782 The return value is:
1783
1783
1784 - True in case 2
1784 - True in case 2
1785
1785
1786 - False in the other cases, unless an exception is raised, where
1786 - False in the other cases, unless an exception is raised, where
1787 None is returned instead. This can be used by external callers to
1787 None is returned instead. This can be used by external callers to
1788 know whether to continue feeding input or not.
1788 know whether to continue feeding input or not.
1789
1789
1790 The return value can be used to decide whether to use sys.ps1 or
1790 The return value can be used to decide whether to use sys.ps1 or
1791 sys.ps2 to prompt the next line."""
1791 sys.ps2 to prompt the next line."""
1792
1792
1793 # if the source code has leading blanks, add 'if 1:\n' to it
1793 # if the source code has leading blanks, add 'if 1:\n' to it
1794 # this allows execution of indented pasted code. It is tempting
1794 # this allows execution of indented pasted code. It is tempting
1795 # to add '\n' at the end of source to run commands like ' a=1'
1795 # to add '\n' at the end of source to run commands like ' a=1'
1796 # directly, but this fails for more complicated scenarios
1796 # directly, but this fails for more complicated scenarios
1797 source=source.encode(self.stdin_encoding)
1797 source=source.encode(self.stdin_encoding)
1798 if source[:1] in [' ', '\t']:
1798 if source[:1] in [' ', '\t']:
1799 source = 'if 1:\n%s' % source
1799 source = 'if 1:\n%s' % source
1800
1800
1801 try:
1801 try:
1802 code = self.compile(source,filename,symbol)
1802 code = self.compile(source,filename,symbol)
1803 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1803 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1804 # Case 1
1804 # Case 1
1805 self.showsyntaxerror(filename)
1805 self.showsyntaxerror(filename)
1806 return None
1806 return None
1807
1807
1808 if code is None:
1808 if code is None:
1809 # Case 2
1809 # Case 2
1810 return True
1810 return True
1811
1811
1812 # Case 3
1812 # Case 3
1813 # We store the code object so that threaded shells and
1813 # We store the code object so that threaded shells and
1814 # custom exception handlers can access all this info if needed.
1814 # custom exception handlers can access all this info if needed.
1815 # The source corresponding to this can be obtained from the
1815 # The source corresponding to this can be obtained from the
1816 # buffer attribute as '\n'.join(self.buffer).
1816 # buffer attribute as '\n'.join(self.buffer).
1817 self.code_to_run = code
1817 self.code_to_run = code
1818 # now actually execute the code object
1818 # now actually execute the code object
1819 if self.runcode(code) == 0:
1819 if self.runcode(code) == 0:
1820 return False
1820 return False
1821 else:
1821 else:
1822 return None
1822 return None
1823
1823
1824 def runcode(self,code_obj):
1824 def runcode(self,code_obj):
1825 """Execute a code object.
1825 """Execute a code object.
1826
1826
1827 When an exception occurs, self.showtraceback() is called to display a
1827 When an exception occurs, self.showtraceback() is called to display a
1828 traceback.
1828 traceback.
1829
1829
1830 Return value: a flag indicating whether the code to be run completed
1830 Return value: a flag indicating whether the code to be run completed
1831 successfully:
1831 successfully:
1832
1832
1833 - 0: successful execution.
1833 - 0: successful execution.
1834 - 1: an error occurred.
1834 - 1: an error occurred.
1835 """
1835 """
1836
1836
1837 # Set our own excepthook in case the user code tries to call it
1837 # Set our own excepthook in case the user code tries to call it
1838 # directly, so that the IPython crash handler doesn't get triggered
1838 # directly, so that the IPython crash handler doesn't get triggered
1839 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1839 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1840
1840
1841 # we save the original sys.excepthook in the instance, in case config
1841 # we save the original sys.excepthook in the instance, in case config
1842 # code (such as magics) needs access to it.
1842 # code (such as magics) needs access to it.
1843 self.sys_excepthook = old_excepthook
1843 self.sys_excepthook = old_excepthook
1844 outflag = 1 # happens in more places, so it's easier as default
1844 outflag = 1 # happens in more places, so it's easier as default
1845 try:
1845 try:
1846 try:
1846 try:
1847 self.hooks.pre_runcode_hook()
1847 self.hooks.pre_runcode_hook()
1848 exec code_obj in self.user_global_ns, self.user_ns
1848 exec code_obj in self.user_global_ns, self.user_ns
1849 finally:
1849 finally:
1850 # Reset our crash handler in place
1850 # Reset our crash handler in place
1851 sys.excepthook = old_excepthook
1851 sys.excepthook = old_excepthook
1852 except SystemExit:
1852 except SystemExit:
1853 self.resetbuffer()
1853 self.resetbuffer()
1854 self.showtraceback(exception_only=True)
1854 self.showtraceback(exception_only=True)
1855 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1855 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1856 except self.custom_exceptions:
1856 except self.custom_exceptions:
1857 etype,value,tb = sys.exc_info()
1857 etype,value,tb = sys.exc_info()
1858 self.CustomTB(etype,value,tb)
1858 self.CustomTB(etype,value,tb)
1859 except:
1859 except:
1860 self.showtraceback()
1860 self.showtraceback()
1861 else:
1861 else:
1862 outflag = 0
1862 outflag = 0
1863 if softspace(sys.stdout, 0):
1863 if softspace(sys.stdout, 0):
1864 print
1864 print
1865 # Flush out code object which has been run (and source)
1865 # Flush out code object which has been run (and source)
1866 self.code_to_run = None
1866 self.code_to_run = None
1867 return outflag
1867 return outflag
1868
1868
1869 def push_line(self, line):
1869 def push_line(self, line):
1870 """Push a line to the interpreter.
1870 """Push a line to the interpreter.
1871
1871
1872 The line should not have a trailing newline; it may have
1872 The line should not have a trailing newline; it may have
1873 internal newlines. The line is appended to a buffer and the
1873 internal newlines. The line is appended to a buffer and the
1874 interpreter's runsource() method is called with the
1874 interpreter's runsource() method is called with the
1875 concatenated contents of the buffer as source. If this
1875 concatenated contents of the buffer as source. If this
1876 indicates that the command was executed or invalid, the buffer
1876 indicates that the command was executed or invalid, the buffer
1877 is reset; otherwise, the command is incomplete, and the buffer
1877 is reset; otherwise, the command is incomplete, and the buffer
1878 is left as it was after the line was appended. The return
1878 is left as it was after the line was appended. The return
1879 value is 1 if more input is required, 0 if the line was dealt
1879 value is 1 if more input is required, 0 if the line was dealt
1880 with in some way (this is the same as runsource()).
1880 with in some way (this is the same as runsource()).
1881 """
1881 """
1882
1882
1883 # autoindent management should be done here, and not in the
1883 # autoindent management should be done here, and not in the
1884 # interactive loop, since that one is only seen by keyboard input. We
1884 # interactive loop, since that one is only seen by keyboard input. We
1885 # need this done correctly even for code run via runlines (which uses
1885 # need this done correctly even for code run via runlines (which uses
1886 # push).
1886 # push).
1887
1887
1888 #print 'push line: <%s>' % line # dbg
1888 #print 'push line: <%s>' % line # dbg
1889 for subline in line.splitlines():
1889 for subline in line.splitlines():
1890 self._autoindent_update(subline)
1890 self._autoindent_update(subline)
1891 self.buffer.append(line)
1891 self.buffer.append(line)
1892 more = self.runsource('\n'.join(self.buffer), self.filename)
1892 more = self.runsource('\n'.join(self.buffer), self.filename)
1893 if not more:
1893 if not more:
1894 self.resetbuffer()
1894 self.resetbuffer()
1895 return more
1895 return more
1896
1896
1897 def resetbuffer(self):
1897 def resetbuffer(self):
1898 """Reset the input buffer."""
1898 """Reset the input buffer."""
1899 self.buffer[:] = []
1899 self.buffer[:] = []
1900
1900
1901 def _is_secondary_block_start(self, s):
1901 def _is_secondary_block_start(self, s):
1902 if not s.endswith(':'):
1902 if not s.endswith(':'):
1903 return False
1903 return False
1904 if (s.startswith('elif') or
1904 if (s.startswith('elif') or
1905 s.startswith('else') or
1905 s.startswith('else') or
1906 s.startswith('except') or
1906 s.startswith('except') or
1907 s.startswith('finally')):
1907 s.startswith('finally')):
1908 return True
1908 return True
1909
1909
1910 def _cleanup_ipy_script(self, script):
1910 def _cleanup_ipy_script(self, script):
1911 """Make a script safe for self.runlines()
1911 """Make a script safe for self.runlines()
1912
1912
1913 Currently, IPython is lines based, with blocks being detected by
1913 Currently, IPython is lines based, with blocks being detected by
1914 empty lines. This is a problem for block based scripts that may
1914 empty lines. This is a problem for block based scripts that may
1915 not have empty lines after blocks. This script adds those empty
1915 not have empty lines after blocks. This script adds those empty
1916 lines to make scripts safe for running in the current line based
1916 lines to make scripts safe for running in the current line based
1917 IPython.
1917 IPython.
1918 """
1918 """
1919 res = []
1919 res = []
1920 lines = script.splitlines()
1920 lines = script.splitlines()
1921 level = 0
1921 level = 0
1922
1922
1923 for l in lines:
1923 for l in lines:
1924 lstripped = l.lstrip()
1924 lstripped = l.lstrip()
1925 stripped = l.strip()
1925 stripped = l.strip()
1926 if not stripped:
1926 if not stripped:
1927 continue
1927 continue
1928 newlevel = len(l) - len(lstripped)
1928 newlevel = len(l) - len(lstripped)
1929 if level > 0 and newlevel == 0 and \
1929 if level > 0 and newlevel == 0 and \
1930 not self._is_secondary_block_start(stripped):
1930 not self._is_secondary_block_start(stripped):
1931 # add empty line
1931 # add empty line
1932 res.append('')
1932 res.append('')
1933 res.append(l)
1933 res.append(l)
1934 level = newlevel
1934 level = newlevel
1935
1935
1936 return '\n'.join(res) + '\n'
1936 return '\n'.join(res) + '\n'
1937
1937
1938 def _autoindent_update(self,line):
1938 def _autoindent_update(self,line):
1939 """Keep track of the indent level."""
1939 """Keep track of the indent level."""
1940
1940
1941 #debugx('line')
1941 #debugx('line')
1942 #debugx('self.indent_current_nsp')
1942 #debugx('self.indent_current_nsp')
1943 if self.autoindent:
1943 if self.autoindent:
1944 if line:
1944 if line:
1945 inisp = num_ini_spaces(line)
1945 inisp = num_ini_spaces(line)
1946 if inisp < self.indent_current_nsp:
1946 if inisp < self.indent_current_nsp:
1947 self.indent_current_nsp = inisp
1947 self.indent_current_nsp = inisp
1948
1948
1949 if line[-1] == ':':
1949 if line[-1] == ':':
1950 self.indent_current_nsp += 4
1950 self.indent_current_nsp += 4
1951 elif dedent_re.match(line):
1951 elif dedent_re.match(line):
1952 self.indent_current_nsp -= 4
1952 self.indent_current_nsp -= 4
1953 else:
1953 else:
1954 self.indent_current_nsp = 0
1954 self.indent_current_nsp = 0
1955
1955
1956 #-------------------------------------------------------------------------
1956 #-------------------------------------------------------------------------
1957 # Things related to GUI support and pylab
1957 # Things related to GUI support and pylab
1958 #-------------------------------------------------------------------------
1958 #-------------------------------------------------------------------------
1959
1959
1960 def enable_pylab(self, gui=None):
1960 def enable_pylab(self, gui=None):
1961 raise NotImplementedError('Implement enable_pylab in a subclass')
1961 raise NotImplementedError('Implement enable_pylab in a subclass')
1962
1962
1963 #-------------------------------------------------------------------------
1963 #-------------------------------------------------------------------------
1964 # Utilities
1964 # Utilities
1965 #-------------------------------------------------------------------------
1965 #-------------------------------------------------------------------------
1966
1966
1967 def getoutput(self, cmd):
1967 def getoutput(self, cmd):
1968 return getoutput(self.var_expand(cmd,depth=2),
1968 return getoutput(self.var_expand(cmd,depth=2),
1969 header=self.system_header,
1969 header=self.system_header,
1970 verbose=self.system_verbose)
1970 verbose=self.system_verbose)
1971
1971
1972 def getoutputerror(self, cmd):
1972 def getoutputerror(self, cmd):
1973 return getoutputerror(self.var_expand(cmd,depth=2),
1973 return getoutputerror(self.var_expand(cmd,depth=2),
1974 header=self.system_header,
1974 header=self.system_header,
1975 verbose=self.system_verbose)
1975 verbose=self.system_verbose)
1976
1976
1977 def var_expand(self,cmd,depth=0):
1977 def var_expand(self,cmd,depth=0):
1978 """Expand python variables in a string.
1978 """Expand python variables in a string.
1979
1979
1980 The depth argument indicates how many frames above the caller should
1980 The depth argument indicates how many frames above the caller should
1981 be walked to look for the local namespace where to expand variables.
1981 be walked to look for the local namespace where to expand variables.
1982
1982
1983 The global namespace for expansion is always the user's interactive
1983 The global namespace for expansion is always the user's interactive
1984 namespace.
1984 namespace.
1985 """
1985 """
1986
1986
1987 return str(ItplNS(cmd,
1987 return str(ItplNS(cmd,
1988 self.user_ns, # globals
1988 self.user_ns, # globals
1989 # Skip our own frame in searching for locals:
1989 # Skip our own frame in searching for locals:
1990 sys._getframe(depth+1).f_locals # locals
1990 sys._getframe(depth+1).f_locals # locals
1991 ))
1991 ))
1992
1992
1993 def mktempfile(self,data=None):
1993 def mktempfile(self,data=None):
1994 """Make a new tempfile and return its filename.
1994 """Make a new tempfile and return its filename.
1995
1995
1996 This makes a call to tempfile.mktemp, but it registers the created
1996 This makes a call to tempfile.mktemp, but it registers the created
1997 filename internally so ipython cleans it up at exit time.
1997 filename internally so ipython cleans it up at exit time.
1998
1998
1999 Optional inputs:
1999 Optional inputs:
2000
2000
2001 - data(None): if data is given, it gets written out to the temp file
2001 - data(None): if data is given, it gets written out to the temp file
2002 immediately, and the file is closed again."""
2002 immediately, and the file is closed again."""
2003
2003
2004 filename = tempfile.mktemp('.py','ipython_edit_')
2004 filename = tempfile.mktemp('.py','ipython_edit_')
2005 self.tempfiles.append(filename)
2005 self.tempfiles.append(filename)
2006
2006
2007 if data:
2007 if data:
2008 tmp_file = open(filename,'w')
2008 tmp_file = open(filename,'w')
2009 tmp_file.write(data)
2009 tmp_file.write(data)
2010 tmp_file.close()
2010 tmp_file.close()
2011 return filename
2011 return filename
2012
2012
2013 # TODO: This should be removed when Term is refactored.
2013 # TODO: This should be removed when Term is refactored.
2014 def write(self,data):
2014 def write(self,data):
2015 """Write a string to the default output"""
2015 """Write a string to the default output"""
2016 IPython.utils.io.Term.cout.write(data)
2016 IPython.utils.io.Term.cout.write(data)
2017
2017
2018 # TODO: This should be removed when Term is refactored.
2018 # TODO: This should be removed when Term is refactored.
2019 def write_err(self,data):
2019 def write_err(self,data):
2020 """Write a string to the default error output"""
2020 """Write a string to the default error output"""
2021 IPython.utils.io.Term.cerr.write(data)
2021 IPython.utils.io.Term.cerr.write(data)
2022
2022
2023 def ask_yes_no(self,prompt,default=True):
2023 def ask_yes_no(self,prompt,default=True):
2024 if self.quiet:
2024 if self.quiet:
2025 return True
2025 return True
2026 return ask_yes_no(prompt,default)
2026 return ask_yes_no(prompt,default)
2027
2027
2028 #-------------------------------------------------------------------------
2028 #-------------------------------------------------------------------------
2029 # Things related to IPython exiting
2029 # Things related to IPython exiting
2030 #-------------------------------------------------------------------------
2030 #-------------------------------------------------------------------------
2031
2031
2032 def atexit_operations(self):
2032 def atexit_operations(self):
2033 """This will be executed at the time of exit.
2033 """This will be executed at the time of exit.
2034
2034
2035 Saving of persistent data should be performed here.
2035 Saving of persistent data should be performed here.
2036 """
2036 """
2037 self.savehist()
2037 self.savehist()
2038
2038
2039 # Cleanup all tempfiles left around
2039 # Cleanup all tempfiles left around
2040 for tfile in self.tempfiles:
2040 for tfile in self.tempfiles:
2041 try:
2041 try:
2042 os.unlink(tfile)
2042 os.unlink(tfile)
2043 except OSError:
2043 except OSError:
2044 pass
2044 pass
2045
2045
2046 # Clear all user namespaces to release all references cleanly.
2046 # Clear all user namespaces to release all references cleanly.
2047 self.reset()
2047 self.reset()
2048
2048
2049 # Run user hooks
2049 # Run user hooks
2050 self.hooks.shutdown_hook()
2050 self.hooks.shutdown_hook()
2051
2051
2052 def cleanup(self):
2052 def cleanup(self):
2053 self.restore_sys_module_state()
2053 self.restore_sys_module_state()
2054
2054
2055
2055
2056 class InteractiveShellABC(object):
2056 class InteractiveShellABC(object):
2057 """An abstract base class for InteractiveShell."""
2057 """An abstract base class for InteractiveShell."""
2058 __metaclass__ = abc.ABCMeta
2058 __metaclass__ = abc.ABCMeta
2059
2059
2060 InteractiveShellABC.register(InteractiveShell)
2060 InteractiveShellABC.register(InteractiveShell)
@@ -1,263 +1,263 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Logger class for IPython's logging facilities.
3 Logger class for IPython's logging facilities.
4 """
4 """
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
15 # Modules and globals
16
16
17 # Python standard modules
17 # Python standard modules
18 import glob
18 import glob
19 import os
19 import os
20 import time
20 import time
21
21
22 #****************************************************************************
22 #****************************************************************************
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
23 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
24 # ipython and does input cache management. Finish cleanup later...
24 # ipython and does input cache management. Finish cleanup later...
25
25
26 class Logger(object):
26 class Logger(object):
27 """A Logfile class with different policies for file creation"""
27 """A Logfile class with different policies for file creation"""
28
28
29 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
29 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
30
30
31 self._i00,self._i,self._ii,self._iii = '','','',''
31 self._i00,self._i,self._ii,self._iii = '','','',''
32
32
33 # this is the full ipython instance, we need some attributes from it
33 # this is the full ipython instance, we need some attributes from it
34 # which won't exist until later. What a mess, clean up later...
34 # which won't exist until later. What a mess, clean up later...
35 self.shell = shell
35 self.shell = shell
36
36
37 self.logfname = logfname
37 self.logfname = logfname
38 self.loghead = loghead
38 self.loghead = loghead
39 self.logmode = logmode
39 self.logmode = logmode
40 self.logfile = None
40 self.logfile = None
41
41
42 # Whether to log raw or processed input
42 # Whether to log raw or processed input
43 self.log_raw_input = False
43 self.log_raw_input = False
44
44
45 # whether to also log output
45 # whether to also log output
46 self.log_output = False
46 self.log_output = False
47
47
48 # whether to put timestamps before each log entry
48 # whether to put timestamps before each log entry
49 self.timestamp = False
49 self.timestamp = False
50
50
51 # activity control flags
51 # activity control flags
52 self.log_active = False
52 self.log_active = False
53
53
54 # logmode is a validated property
54 # logmode is a validated property
55 def _set_mode(self,mode):
55 def _set_mode(self,mode):
56 if mode not in ['append','backup','global','over','rotate']:
56 if mode not in ['append','backup','global','over','rotate']:
57 raise ValueError,'invalid log mode %s given' % mode
57 raise ValueError,'invalid log mode %s given' % mode
58 self._logmode = mode
58 self._logmode = mode
59
59
60 def _get_mode(self):
60 def _get_mode(self):
61 return self._logmode
61 return self._logmode
62
62
63 logmode = property(_get_mode,_set_mode)
63 logmode = property(_get_mode,_set_mode)
64
64
65 def logstart(self,logfname=None,loghead=None,logmode=None,
65 def logstart(self,logfname=None,loghead=None,logmode=None,
66 log_output=False,timestamp=False,log_raw_input=False):
66 log_output=False,timestamp=False,log_raw_input=False):
67 """Generate a new log-file with a default header.
67 """Generate a new log-file with a default header.
68
68
69 Raises RuntimeError if the log has already been started"""
69 Raises RuntimeError if the log has already been started"""
70
70
71 if self.logfile is not None:
71 if self.logfile is not None:
72 raise RuntimeError('Log file is already active: %s' %
72 raise RuntimeError('Log file is already active: %s' %
73 self.logfname)
73 self.logfname)
74
74
75 self.log_active = True
75 self.log_active = True
76
76
77 # The parameters can override constructor defaults
77 # The parameters can override constructor defaults
78 if logfname is not None: self.logfname = logfname
78 if logfname is not None: self.logfname = logfname
79 if loghead is not None: self.loghead = loghead
79 if loghead is not None: self.loghead = loghead
80 if logmode is not None: self.logmode = logmode
80 if logmode is not None: self.logmode = logmode
81
81
82 # Parameters not part of the constructor
82 # Parameters not part of the constructor
83 self.timestamp = timestamp
83 self.timestamp = timestamp
84 self.log_output = log_output
84 self.log_output = log_output
85 self.log_raw_input = log_raw_input
85 self.log_raw_input = log_raw_input
86
86
87 # init depending on the log mode requested
87 # init depending on the log mode requested
88 isfile = os.path.isfile
88 isfile = os.path.isfile
89 logmode = self.logmode
89 logmode = self.logmode
90
90
91 if logmode == 'append':
91 if logmode == 'append':
92 self.logfile = open(self.logfname,'a')
92 self.logfile = open(self.logfname,'a')
93
93
94 elif logmode == 'backup':
94 elif logmode == 'backup':
95 if isfile(self.logfname):
95 if isfile(self.logfname):
96 backup_logname = self.logfname+'~'
96 backup_logname = self.logfname+'~'
97 # Manually remove any old backup, since os.rename may fail
97 # Manually remove any old backup, since os.rename may fail
98 # under Windows.
98 # under Windows.
99 if isfile(backup_logname):
99 if isfile(backup_logname):
100 os.remove(backup_logname)
100 os.remove(backup_logname)
101 os.rename(self.logfname,backup_logname)
101 os.rename(self.logfname,backup_logname)
102 self.logfile = open(self.logfname,'w')
102 self.logfile = open(self.logfname,'w')
103
103
104 elif logmode == 'global':
104 elif logmode == 'global':
105 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
105 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 self.logfile = open(self.logfname, 'a')
106 self.logfile = open(self.logfname, 'a')
107
107
108 elif logmode == 'over':
108 elif logmode == 'over':
109 if isfile(self.logfname):
109 if isfile(self.logfname):
110 os.remove(self.logfname)
110 os.remove(self.logfname)
111 self.logfile = open(self.logfname,'w')
111 self.logfile = open(self.logfname,'w')
112
112
113 elif logmode == 'rotate':
113 elif logmode == 'rotate':
114 if isfile(self.logfname):
114 if isfile(self.logfname):
115 if isfile(self.logfname+'.001~'):
115 if isfile(self.logfname+'.001~'):
116 old = glob.glob(self.logfname+'.*~')
116 old = glob.glob(self.logfname+'.*~')
117 old.sort()
117 old.sort()
118 old.reverse()
118 old.reverse()
119 for f in old:
119 for f in old:
120 root, ext = os.path.splitext(f)
120 root, ext = os.path.splitext(f)
121 num = int(ext[1:-1])+1
121 num = int(ext[1:-1])+1
122 os.rename(f, root+'.'+`num`.zfill(3)+'~')
122 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 os.rename(self.logfname, self.logfname+'.001~')
123 os.rename(self.logfname, self.logfname+'.001~')
124 self.logfile = open(self.logfname,'w')
124 self.logfile = open(self.logfname,'w')
125
125
126 if logmode != 'append':
126 if logmode != 'append':
127 self.logfile.write(self.loghead)
127 self.logfile.write(self.loghead)
128
128
129 self.logfile.flush()
129 self.logfile.flush()
130
130
131 def switch_log(self,val):
131 def switch_log(self,val):
132 """Switch logging on/off. val should be ONLY a boolean."""
132 """Switch logging on/off. val should be ONLY a boolean."""
133
133
134 if val not in [False,True,0,1]:
134 if val not in [False,True,0,1]:
135 raise ValueError, \
135 raise ValueError, \
136 'Call switch_log ONLY with a boolean argument, not with:',val
136 'Call switch_log ONLY with a boolean argument, not with:',val
137
137
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
138 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139
139
140 if self.logfile is None:
140 if self.logfile is None:
141 print """
141 print """
142 Logging hasn't been started yet (use logstart for that).
142 Logging hasn't been started yet (use logstart for that).
143
143
144 %logon/%logoff are for temporarily starting and stopping logging for a logfile
144 %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
145 which already exists. But you must first start the logging process with
146 %logstart (optionally giving a logfile name)."""
146 %logstart (optionally giving a logfile name)."""
147
147
148 else:
148 else:
149 if self.log_active == val:
149 if self.log_active == val:
150 print 'Logging is already',label[val]
150 print 'Logging is already',label[val]
151 else:
151 else:
152 print 'Switching logging',label[val]
152 print 'Switching logging',label[val]
153 self.log_active = not self.log_active
153 self.log_active = not self.log_active
154 self.log_active_out = self.log_active
154 self.log_active_out = self.log_active
155
155
156 def logstate(self):
156 def logstate(self):
157 """Print a status message about the logger."""
157 """Print a status message about the logger."""
158 if self.logfile is None:
158 if self.logfile is None:
159 print 'Logging has not been activated.'
159 print 'Logging has not been activated.'
160 else:
160 else:
161 state = self.log_active and 'active' or 'temporarily suspended'
161 state = self.log_active and 'active' or 'temporarily suspended'
162 print 'Filename :',self.logfname
162 print 'Filename :',self.logfname
163 print 'Mode :',self.logmode
163 print 'Mode :',self.logmode
164 print 'Output logging :',self.log_output
164 print 'Output logging :',self.log_output
165 print 'Raw input log :',self.log_raw_input
165 print 'Raw input log :',self.log_raw_input
166 print 'Timestamping :',self.timestamp
166 print 'Timestamping :',self.timestamp
167 print 'State :',state
167 print 'State :',state
168
168
169 def log(self,line_ori,line_mod,continuation=None):
169 def log(self,line_ori,line_mod,continuation=None):
170 """Write the line to a log and create input cache variables _i*.
170 """Write the line to a log and create input cache variables _i*.
171
171
172 Inputs:
172 Inputs:
173
173
174 - line_ori: unmodified input line from the user. This is not
174 - line_ori: unmodified input line from the user. This is not
175 necessarily valid Python.
175 necessarily valid Python.
176
176
177 - line_mod: possibly modified input, such as the transformations made
177 - line_mod: possibly modified input, such as the transformations made
178 by input prefilters or input handlers of various kinds. This should
178 by input prefilters or input handlers of various kinds. This should
179 always be valid Python.
179 always be valid Python.
180
180
181 - continuation: if True, indicates this is part of multi-line input."""
181 - continuation: if True, indicates this is part of multi-line input."""
182
182
183 # update the auto _i tables
183 # update the auto _i tables
184 #print '***logging line',line_mod # dbg
184 #print '***logging line',line_mod # dbg
185 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
185 #print '***cache_count', self.shell.displayhook.prompt_count # dbg
186 try:
186 try:
187 input_hist = self.shell.user_ns['_ih']
187 input_hist = self.shell.user_ns['_ih']
188 except:
188 except:
189 #print 'userns:',self.shell.user_ns.keys() # dbg
189 #print 'userns:',self.shell.user_ns.keys() # dbg
190 return
190 return
191
191
192 out_cache = self.shell.outputcache
192 out_cache = self.shell.displayhook
193
193
194 # add blank lines if the input cache fell out of sync.
194 # add blank lines if the input cache fell out of sync.
195 if out_cache.do_full_cache and \
195 if out_cache.do_full_cache and \
196 out_cache.prompt_count +1 > len(input_hist):
196 out_cache.prompt_count +1 > len(input_hist):
197 input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
197 input_hist.extend(['\n'] * (out_cache.prompt_count - len(input_hist)))
198
198
199 if not continuation and line_mod:
199 if not continuation and line_mod:
200 self._iii = self._ii
200 self._iii = self._ii
201 self._ii = self._i
201 self._ii = self._i
202 self._i = self._i00
202 self._i = self._i00
203 # put back the final \n of every input line
203 # put back the final \n of every input line
204 self._i00 = line_mod+'\n'
204 self._i00 = line_mod+'\n'
205 #print 'Logging input:<%s>' % line_mod # dbg
205 #print 'Logging input:<%s>' % line_mod # dbg
206 input_hist.append(self._i00)
206 input_hist.append(self._i00)
207 #print '---[%s]' % (len(input_hist)-1,) # dbg
207 #print '---[%s]' % (len(input_hist)-1,) # dbg
208
208
209 # hackish access to top-level namespace to create _i1,_i2... dynamically
209 # hackish access to top-level namespace to create _i1,_i2... dynamically
210 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
210 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
211 if self.shell.outputcache.do_full_cache:
211 if self.shell.displayhook.do_full_cache:
212 in_num = self.shell.outputcache.prompt_count
212 in_num = self.shell.displayhook.prompt_count
213
213
214 # but if the opposite is true (a macro can produce multiple inputs
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
215 # with no output display called), then bring the output counter in
216 # sync:
216 # sync:
217 last_num = len(input_hist)-1
217 last_num = len(input_hist)-1
218 if in_num != last_num:
218 if in_num != last_num:
219 in_num = self.shell.outputcache.prompt_count = last_num
219 in_num = self.shell.displayhook.prompt_count = last_num
220 new_i = '_i%s' % in_num
220 new_i = '_i%s' % in_num
221 if continuation:
221 if continuation:
222 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
222 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
223 input_hist[in_num] = self._i00
223 input_hist[in_num] = self._i00
224 to_main[new_i] = self._i00
224 to_main[new_i] = self._i00
225 self.shell.user_ns.update(to_main)
225 self.shell.user_ns.update(to_main)
226
226
227 # Write the log line, but decide which one according to the
227 # Write the log line, but decide which one according to the
228 # log_raw_input flag, set when the log is started.
228 # log_raw_input flag, set when the log is started.
229 if self.log_raw_input:
229 if self.log_raw_input:
230 self.log_write(line_ori)
230 self.log_write(line_ori)
231 else:
231 else:
232 self.log_write(line_mod)
232 self.log_write(line_mod)
233
233
234 def log_write(self,data,kind='input'):
234 def log_write(self,data,kind='input'):
235 """Write data to the log file, if active"""
235 """Write data to the log file, if active"""
236
236
237 #print 'data: %r' % data # dbg
237 #print 'data: %r' % data # dbg
238 if self.log_active and data:
238 if self.log_active and data:
239 write = self.logfile.write
239 write = self.logfile.write
240 if kind=='input':
240 if kind=='input':
241 if self.timestamp:
241 if self.timestamp:
242 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
242 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
243 time.localtime()))
243 time.localtime()))
244 write('%s\n' % data)
244 write('%s\n' % data)
245 elif kind=='output' and self.log_output:
245 elif kind=='output' and self.log_output:
246 odata = '\n'.join(['#[Out]# %s' % s
246 odata = '\n'.join(['#[Out]# %s' % s
247 for s in data.split('\n')])
247 for s in data.split('\n')])
248 write('%s\n' % odata)
248 write('%s\n' % odata)
249 self.logfile.flush()
249 self.logfile.flush()
250
250
251 def logstop(self):
251 def logstop(self):
252 """Fully stop logging and close log file.
252 """Fully stop logging and close log file.
253
253
254 In order to start logging again, a new logstart() call needs to be
254 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
255 made, possibly (though not necessarily) with a new filename, mode and
256 other options."""
256 other options."""
257
257
258 self.logfile.close()
258 self.logfile.close()
259 self.logfile = None
259 self.logfile = None
260 self.log_active = False
260 self.log_active = False
261
261
262 # For backwards compatibility, in case anyone was using this.
262 # For backwards compatibility, in case anyone was using this.
263 close_log = logstop
263 close_log = logstop
@@ -1,3652 +1,3652 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
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import file_read, nlprint
61 from IPython.utils.io import file_read, nlprint
62 import IPython.utils.io
62 import IPython.utils.io
63 from IPython.utils.path import get_py_filename
63 from IPython.utils.path import get_py_filename
64 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.process import arg_split, abbrev_cwd
65 from IPython.utils.terminal import set_term_title
65 from IPython.utils.terminal import set_term_title
66 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.text import LSString, SList, StringTypes
67 from IPython.utils.timing import clock, clock2
67 from IPython.utils.timing import clock, clock2
68 from IPython.utils.warn import warn, error
68 from IPython.utils.warn import warn, error
69 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
70 import IPython.utils.generics
70 import IPython.utils.generics
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Utility functions
73 # Utility functions
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 def on_off(tag):
76 def on_off(tag):
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
78 return ['OFF','ON'][tag]
78 return ['OFF','ON'][tag]
79
79
80 class Bunch: pass
80 class Bunch: pass
81
81
82 def compress_dhist(dh):
82 def compress_dhist(dh):
83 head, tail = dh[:-10], dh[-10:]
83 head, tail = dh[:-10], dh[-10:]
84
84
85 newhead = []
85 newhead = []
86 done = set()
86 done = set()
87 for h in head:
87 for h in head:
88 if h in done:
88 if h in done:
89 continue
89 continue
90 newhead.append(h)
90 newhead.append(h)
91 done.add(h)
91 done.add(h)
92
92
93 return newhead + tail
93 return newhead + tail
94
94
95
95
96 #***************************************************************************
96 #***************************************************************************
97 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
98
98
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
106
106
107 class Magic:
107 class Magic:
108 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
109
109
110 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
113 vs. `%cd("../")`
114
114
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
117
117
118 # class globals
118 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121
121
122 #......................................................................
122 #......................................................................
123 # some utility functions
123 # some utility functions
124
124
125 def __init__(self,shell):
125 def __init__(self,shell):
126
126
127 self.options_table = {}
127 self.options_table = {}
128 if profile is None:
128 if profile is None:
129 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
130 self.shell = shell
131
131
132 # namespace for holding state we may need
132 # namespace for holding state we may need
133 self._magic_state = Bunch()
133 self._magic_state = Bunch()
134
134
135 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
136 error("""\
137 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
140
140
141 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
143
143
144 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
147
147
148 def lsmagic(self):
148 def lsmagic(self):
149 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
150
150
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
153
153
154 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155
155
156 # magics in class definition
156 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
168 out = []
169 for fn in set(magics):
169 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
171 out.sort()
171 out.sort()
172 return out
172 return out
173
173
174 def extract_input_slices(self,slices,raw=False):
174 def extract_input_slices(self,slices,raw=False):
175 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
176
176
177 Inputs:
177 Inputs:
178
178
179 - slices: the set of slices is given as a list of strings (like
179 - slices: the set of slices is given as a list of strings (like
180 ['1','4:8','9'], since this function is for use by magic functions
180 ['1','4:8','9'], since this function is for use by magic functions
181 which get their arguments as strings.
181 which get their arguments as strings.
182
182
183 Optional inputs:
183 Optional inputs:
184
184
185 - raw(False): by default, the processed input is used. If this is
185 - raw(False): by default, the processed input is used. If this is
186 true, the raw input history is used instead.
186 true, the raw input history is used instead.
187
187
188 Note that slices can be called with two notations:
188 Note that slices can be called with two notations:
189
189
190 N:M -> standard python form, means including items N...(M-1).
190 N:M -> standard python form, means including items N...(M-1).
191
191
192 N-M -> include items N..M (closed endpoint)."""
192 N-M -> include items N..M (closed endpoint)."""
193
193
194 if raw:
194 if raw:
195 hist = self.shell.input_hist_raw
195 hist = self.shell.input_hist_raw
196 else:
196 else:
197 hist = self.shell.input_hist
197 hist = self.shell.input_hist
198
198
199 cmds = []
199 cmds = []
200 for chunk in slices:
200 for chunk in slices:
201 if ':' in chunk:
201 if ':' in chunk:
202 ini,fin = map(int,chunk.split(':'))
202 ini,fin = map(int,chunk.split(':'))
203 elif '-' in chunk:
203 elif '-' in chunk:
204 ini,fin = map(int,chunk.split('-'))
204 ini,fin = map(int,chunk.split('-'))
205 fin += 1
205 fin += 1
206 else:
206 else:
207 ini = int(chunk)
207 ini = int(chunk)
208 fin = ini+1
208 fin = ini+1
209 cmds.append(hist[ini:fin])
209 cmds.append(hist[ini:fin])
210 return cmds
210 return cmds
211
211
212 def _ofind(self, oname, namespaces=None):
212 def _ofind(self, oname, namespaces=None):
213 """Find an object in the available namespaces.
213 """Find an object in the available namespaces.
214
214
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
216
216
217 Has special code to detect magic functions.
217 Has special code to detect magic functions.
218 """
218 """
219 oname = oname.strip()
219 oname = oname.strip()
220 alias_ns = None
220 alias_ns = None
221 if namespaces is None:
221 if namespaces is None:
222 # Namespaces to search in:
222 # Namespaces to search in:
223 # Put them in a list. The order is important so that we
223 # Put them in a list. The order is important so that we
224 # find things in the same order that Python finds them.
224 # find things in the same order that Python finds them.
225 namespaces = [ ('Interactive', self.shell.user_ns),
225 namespaces = [ ('Interactive', self.shell.user_ns),
226 ('IPython internal', self.shell.internal_ns),
226 ('IPython internal', self.shell.internal_ns),
227 ('Python builtin', __builtin__.__dict__),
227 ('Python builtin', __builtin__.__dict__),
228 ('Alias', self.shell.alias_manager.alias_table),
228 ('Alias', self.shell.alias_manager.alias_table),
229 ]
229 ]
230 alias_ns = self.shell.alias_manager.alias_table
230 alias_ns = self.shell.alias_manager.alias_table
231
231
232 # initialize results to 'null'
232 # initialize results to 'null'
233 found = False; obj = None; ospace = None; ds = None;
233 found = False; obj = None; ospace = None; ds = None;
234 ismagic = False; isalias = False; parent = None
234 ismagic = False; isalias = False; parent = None
235
235
236 # We need to special-case 'print', which as of python2.6 registers as a
236 # We need to special-case 'print', which as of python2.6 registers as a
237 # function but should only be treated as one if print_function was
237 # function but should only be treated as one if print_function was
238 # loaded with a future import. In this case, just bail.
238 # loaded with a future import. In this case, just bail.
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
243
243
244 # Look for the given name by splitting it in parts. If the head is
244 # Look for the given name by splitting it in parts. If the head is
245 # found, then we look for all the remaining parts as members, and only
245 # found, then we look for all the remaining parts as members, and only
246 # declare success if we can find them all.
246 # declare success if we can find them all.
247 oname_parts = oname.split('.')
247 oname_parts = oname.split('.')
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
249 for nsname,ns in namespaces:
249 for nsname,ns in namespaces:
250 try:
250 try:
251 obj = ns[oname_head]
251 obj = ns[oname_head]
252 except KeyError:
252 except KeyError:
253 continue
253 continue
254 else:
254 else:
255 #print 'oname_rest:', oname_rest # dbg
255 #print 'oname_rest:', oname_rest # dbg
256 for part in oname_rest:
256 for part in oname_rest:
257 try:
257 try:
258 parent = obj
258 parent = obj
259 obj = getattr(obj,part)
259 obj = getattr(obj,part)
260 except:
260 except:
261 # Blanket except b/c some badly implemented objects
261 # Blanket except b/c some badly implemented objects
262 # allow __getattr__ to raise exceptions other than
262 # allow __getattr__ to raise exceptions other than
263 # AttributeError, which then crashes IPython.
263 # AttributeError, which then crashes IPython.
264 break
264 break
265 else:
265 else:
266 # If we finish the for loop (no break), we got all members
266 # If we finish the for loop (no break), we got all members
267 found = True
267 found = True
268 ospace = nsname
268 ospace = nsname
269 if ns == alias_ns:
269 if ns == alias_ns:
270 isalias = True
270 isalias = True
271 break # namespace loop
271 break # namespace loop
272
272
273 # Try to see if it's magic
273 # Try to see if it's magic
274 if not found:
274 if not found:
275 if oname.startswith(ESC_MAGIC):
275 if oname.startswith(ESC_MAGIC):
276 oname = oname[1:]
276 oname = oname[1:]
277 obj = getattr(self,'magic_'+oname,None)
277 obj = getattr(self,'magic_'+oname,None)
278 if obj is not None:
278 if obj is not None:
279 found = True
279 found = True
280 ospace = 'IPython internal'
280 ospace = 'IPython internal'
281 ismagic = True
281 ismagic = True
282
282
283 # Last try: special-case some literals like '', [], {}, etc:
283 # Last try: special-case some literals like '', [], {}, etc:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
285 obj = eval(oname_head)
285 obj = eval(oname_head)
286 found = True
286 found = True
287 ospace = 'Interactive'
287 ospace = 'Interactive'
288
288
289 return {'found':found, 'obj':obj, 'namespace':ospace,
289 return {'found':found, 'obj':obj, 'namespace':ospace,
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
291
291
292 def arg_err(self,func):
292 def arg_err(self,func):
293 """Print docstring if incorrect arguments were passed"""
293 """Print docstring if incorrect arguments were passed"""
294 print 'Error in arguments:'
294 print 'Error in arguments:'
295 print oinspect.getdoc(func)
295 print oinspect.getdoc(func)
296
296
297 def format_latex(self,strng):
297 def format_latex(self,strng):
298 """Format a string for latex inclusion."""
298 """Format a string for latex inclusion."""
299
299
300 # Characters that need to be escaped for latex:
300 # Characters that need to be escaped for latex:
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
302 # Magic command names as headers:
302 # Magic command names as headers:
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
304 re.MULTILINE)
304 re.MULTILINE)
305 # Magic commands
305 # Magic commands
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
307 re.MULTILINE)
307 re.MULTILINE)
308 # Paragraph continue
308 # Paragraph continue
309 par_re = re.compile(r'\\$',re.MULTILINE)
309 par_re = re.compile(r'\\$',re.MULTILINE)
310
310
311 # The "\n" symbol
311 # The "\n" symbol
312 newline_re = re.compile(r'\\n')
312 newline_re = re.compile(r'\\n')
313
313
314 # Now build the string for output:
314 # Now build the string for output:
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
317 strng)
317 strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
319 strng = par_re.sub(r'\\\\',strng)
319 strng = par_re.sub(r'\\\\',strng)
320 strng = escape_re.sub(r'\\\1',strng)
320 strng = escape_re.sub(r'\\\1',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
322 return strng
322 return strng
323
323
324 def format_screen(self,strng):
324 def format_screen(self,strng):
325 """Format a string for screen printing.
325 """Format a string for screen printing.
326
326
327 This removes some latex-type format codes."""
327 This removes some latex-type format codes."""
328 # Paragraph continue
328 # Paragraph continue
329 par_re = re.compile(r'\\$',re.MULTILINE)
329 par_re = re.compile(r'\\$',re.MULTILINE)
330 strng = par_re.sub('',strng)
330 strng = par_re.sub('',strng)
331 return strng
331 return strng
332
332
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
334 """Parse options passed to an argument string.
334 """Parse options passed to an argument string.
335
335
336 The interface is similar to that of getopt(), but it returns back a
336 The interface is similar to that of getopt(), but it returns back a
337 Struct with the options as keys and the stripped argument string still
337 Struct with the options as keys and the stripped argument string still
338 as a string.
338 as a string.
339
339
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
341 This allows us to easily expand variables, glob files, quote
341 This allows us to easily expand variables, glob files, quote
342 arguments, etc.
342 arguments, etc.
343
343
344 Options:
344 Options:
345 -mode: default 'string'. If given as 'list', the argument string is
345 -mode: default 'string'. If given as 'list', the argument string is
346 returned as a list (split on whitespace) instead of a string.
346 returned as a list (split on whitespace) instead of a string.
347
347
348 -list_all: put all option values in lists. Normally only options
348 -list_all: put all option values in lists. Normally only options
349 appearing more than once are put in a list.
349 appearing more than once are put in a list.
350
350
351 -posix (True): whether to split the input line in POSIX mode or not,
351 -posix (True): whether to split the input line in POSIX mode or not,
352 as per the conventions outlined in the shlex module from the
352 as per the conventions outlined in the shlex module from the
353 standard library."""
353 standard library."""
354
354
355 # inject default options at the beginning of the input line
355 # inject default options at the beginning of the input line
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
358
358
359 mode = kw.get('mode','string')
359 mode = kw.get('mode','string')
360 if mode not in ['string','list']:
360 if mode not in ['string','list']:
361 raise ValueError,'incorrect mode given: %s' % mode
361 raise ValueError,'incorrect mode given: %s' % mode
362 # Get options
362 # Get options
363 list_all = kw.get('list_all',0)
363 list_all = kw.get('list_all',0)
364 posix = kw.get('posix', os.name == 'posix')
364 posix = kw.get('posix', os.name == 'posix')
365
365
366 # Check if we have more than one argument to warrant extra processing:
366 # Check if we have more than one argument to warrant extra processing:
367 odict = {} # Dictionary with options
367 odict = {} # Dictionary with options
368 args = arg_str.split()
368 args = arg_str.split()
369 if len(args) >= 1:
369 if len(args) >= 1:
370 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # If the list of inputs only has 0 or 1 thing in it, there's no
371 # need to look for options
371 # need to look for options
372 argv = arg_split(arg_str,posix)
372 argv = arg_split(arg_str,posix)
373 # Do regular option processing
373 # Do regular option processing
374 try:
374 try:
375 opts,args = getopt(argv,opt_str,*long_opts)
375 opts,args = getopt(argv,opt_str,*long_opts)
376 except GetoptError,e:
376 except GetoptError,e:
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
378 " ".join(long_opts)))
378 " ".join(long_opts)))
379 for o,a in opts:
379 for o,a in opts:
380 if o.startswith('--'):
380 if o.startswith('--'):
381 o = o[2:]
381 o = o[2:]
382 else:
382 else:
383 o = o[1:]
383 o = o[1:]
384 try:
384 try:
385 odict[o].append(a)
385 odict[o].append(a)
386 except AttributeError:
386 except AttributeError:
387 odict[o] = [odict[o],a]
387 odict[o] = [odict[o],a]
388 except KeyError:
388 except KeyError:
389 if list_all:
389 if list_all:
390 odict[o] = [a]
390 odict[o] = [a]
391 else:
391 else:
392 odict[o] = a
392 odict[o] = a
393
393
394 # Prepare opts,args for return
394 # Prepare opts,args for return
395 opts = Struct(odict)
395 opts = Struct(odict)
396 if mode == 'string':
396 if mode == 'string':
397 args = ' '.join(args)
397 args = ' '.join(args)
398
398
399 return opts,args
399 return opts,args
400
400
401 #......................................................................
401 #......................................................................
402 # And now the actual magic functions
402 # And now the actual magic functions
403
403
404 # Functions for IPython shell work (vars,funcs, config, etc)
404 # Functions for IPython shell work (vars,funcs, config, etc)
405 def magic_lsmagic(self, parameter_s = ''):
405 def magic_lsmagic(self, parameter_s = ''):
406 """List currently available magic functions."""
406 """List currently available magic functions."""
407 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
408 print 'Available magic functions:\n'+mesc+\
408 print 'Available magic functions:\n'+mesc+\
409 (' '+mesc).join(self.lsmagic())
409 (' '+mesc).join(self.lsmagic())
410 print '\n' + Magic.auto_status[self.shell.automagic]
410 print '\n' + Magic.auto_status[self.shell.automagic]
411 return None
411 return None
412
412
413 def magic_magic(self, parameter_s = ''):
413 def magic_magic(self, parameter_s = ''):
414 """Print information about the magic function system.
414 """Print information about the magic function system.
415
415
416 Supported formats: -latex, -brief, -rest
416 Supported formats: -latex, -brief, -rest
417 """
417 """
418
418
419 mode = ''
419 mode = ''
420 try:
420 try:
421 if parameter_s.split()[0] == '-latex':
421 if parameter_s.split()[0] == '-latex':
422 mode = 'latex'
422 mode = 'latex'
423 if parameter_s.split()[0] == '-brief':
423 if parameter_s.split()[0] == '-brief':
424 mode = 'brief'
424 mode = 'brief'
425 if parameter_s.split()[0] == '-rest':
425 if parameter_s.split()[0] == '-rest':
426 mode = 'rest'
426 mode = 'rest'
427 rest_docs = []
427 rest_docs = []
428 except:
428 except:
429 pass
429 pass
430
430
431 magic_docs = []
431 magic_docs = []
432 for fname in self.lsmagic():
432 for fname in self.lsmagic():
433 mname = 'magic_' + fname
433 mname = 'magic_' + fname
434 for space in (Magic,self,self.__class__):
434 for space in (Magic,self,self.__class__):
435 try:
435 try:
436 fn = space.__dict__[mname]
436 fn = space.__dict__[mname]
437 except KeyError:
437 except KeyError:
438 pass
438 pass
439 else:
439 else:
440 break
440 break
441 if mode == 'brief':
441 if mode == 'brief':
442 # only first line
442 # only first line
443 if fn.__doc__:
443 if fn.__doc__:
444 fndoc = fn.__doc__.split('\n',1)[0]
444 fndoc = fn.__doc__.split('\n',1)[0]
445 else:
445 else:
446 fndoc = 'No documentation'
446 fndoc = 'No documentation'
447 else:
447 else:
448 if fn.__doc__:
448 if fn.__doc__:
449 fndoc = fn.__doc__.rstrip()
449 fndoc = fn.__doc__.rstrip()
450 else:
450 else:
451 fndoc = 'No documentation'
451 fndoc = 'No documentation'
452
452
453
453
454 if mode == 'rest':
454 if mode == 'rest':
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
456 fname,fndoc))
456 fname,fndoc))
457
457
458 else:
458 else:
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
460 fname,fndoc))
460 fname,fndoc))
461
461
462 magic_docs = ''.join(magic_docs)
462 magic_docs = ''.join(magic_docs)
463
463
464 if mode == 'rest':
464 if mode == 'rest':
465 return "".join(rest_docs)
465 return "".join(rest_docs)
466
466
467 if mode == 'latex':
467 if mode == 'latex':
468 print self.format_latex(magic_docs)
468 print self.format_latex(magic_docs)
469 return
469 return
470 else:
470 else:
471 magic_docs = self.format_screen(magic_docs)
471 magic_docs = self.format_screen(magic_docs)
472 if mode == 'brief':
472 if mode == 'brief':
473 return magic_docs
473 return magic_docs
474
474
475 outmsg = """
475 outmsg = """
476 IPython's 'magic' functions
476 IPython's 'magic' functions
477 ===========================
477 ===========================
478
478
479 The magic function system provides a series of functions which allow you to
479 The magic function system provides a series of functions which allow you to
480 control the behavior of IPython itself, plus a lot of system-type
480 control the behavior of IPython itself, plus a lot of system-type
481 features. All these functions are prefixed with a % character, but parameters
481 features. All these functions are prefixed with a % character, but parameters
482 are given without parentheses or quotes.
482 are given without parentheses or quotes.
483
483
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
485 %automagic function), you don't need to type in the % explicitly. By default,
485 %automagic function), you don't need to type in the % explicitly. By default,
486 IPython ships with automagic on, so you should only rarely need the % escape.
486 IPython ships with automagic on, so you should only rarely need the % escape.
487
487
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
489 to 'mydir', if it exists.
489 to 'mydir', if it exists.
490
490
491 You can define your own magic functions to extend the system. See the supplied
491 You can define your own magic functions to extend the system. See the supplied
492 ipythonrc and example-magic.py files for details (in your ipython
492 ipythonrc and example-magic.py files for details (in your ipython
493 configuration directory, typically $HOME/.ipython/).
493 configuration directory, typically $HOME/.ipython/).
494
494
495 You can also define your own aliased names for magic functions. In your
495 You can also define your own aliased names for magic functions. In your
496 ipythonrc file, placing a line like:
496 ipythonrc file, placing a line like:
497
497
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
499
499
500 will define %pf as a new name for %profile.
500 will define %pf as a new name for %profile.
501
501
502 You can also call magics in code using the magic() function, which IPython
502 You can also call magics in code using the magic() function, which IPython
503 automatically adds to the builtin namespace. Type 'magic?' for details.
503 automatically adds to the builtin namespace. Type 'magic?' for details.
504
504
505 For a list of the available magic functions, use %lsmagic. For a description
505 For a list of the available magic functions, use %lsmagic. For a description
506 of any of them, type %magic_name?, e.g. '%cd?'.
506 of any of them, type %magic_name?, e.g. '%cd?'.
507
507
508 Currently the magic system has the following functions:\n"""
508 Currently the magic system has the following functions:\n"""
509
509
510 mesc = ESC_MAGIC
510 mesc = ESC_MAGIC
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
512 "\n\n%s%s\n\n%s" % (outmsg,
512 "\n\n%s%s\n\n%s" % (outmsg,
513 magic_docs,mesc,mesc,
513 magic_docs,mesc,mesc,
514 (' '+mesc).join(self.lsmagic()),
514 (' '+mesc).join(self.lsmagic()),
515 Magic.auto_status[self.shell.automagic] ) )
515 Magic.auto_status[self.shell.automagic] ) )
516
516
517 page(outmsg,screen_lines=self.shell.usable_screen_length)
517 page(outmsg,screen_lines=self.shell.usable_screen_length)
518
518
519
519
520 def magic_autoindent(self, parameter_s = ''):
520 def magic_autoindent(self, parameter_s = ''):
521 """Toggle autoindent on/off (if available)."""
521 """Toggle autoindent on/off (if available)."""
522
522
523 self.shell.set_autoindent()
523 self.shell.set_autoindent()
524 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
525
525
526
526
527 def magic_automagic(self, parameter_s = ''):
527 def magic_automagic(self, parameter_s = ''):
528 """Make magic functions callable without having to type the initial %.
528 """Make magic functions callable without having to type the initial %.
529
529
530 Without argumentsl toggles on/off (when off, you must call it as
530 Without argumentsl toggles on/off (when off, you must call it as
531 %automagic, of course). With arguments it sets the value, and you can
531 %automagic, of course). With arguments it sets the value, and you can
532 use any of (case insensitive):
532 use any of (case insensitive):
533
533
534 - on,1,True: to activate
534 - on,1,True: to activate
535
535
536 - off,0,False: to deactivate.
536 - off,0,False: to deactivate.
537
537
538 Note that magic functions have lowest priority, so if there's a
538 Note that magic functions have lowest priority, so if there's a
539 variable whose name collides with that of a magic fn, automagic won't
539 variable whose name collides with that of a magic fn, automagic won't
540 work for that function (you get the variable instead). However, if you
540 work for that function (you get the variable instead). However, if you
541 delete the variable (del var), the previously shadowed magic function
541 delete the variable (del var), the previously shadowed magic function
542 becomes visible to automagic again."""
542 becomes visible to automagic again."""
543
543
544 arg = parameter_s.lower()
544 arg = parameter_s.lower()
545 if parameter_s in ('on','1','true'):
545 if parameter_s in ('on','1','true'):
546 self.shell.automagic = True
546 self.shell.automagic = True
547 elif parameter_s in ('off','0','false'):
547 elif parameter_s in ('off','0','false'):
548 self.shell.automagic = False
548 self.shell.automagic = False
549 else:
549 else:
550 self.shell.automagic = not self.shell.automagic
550 self.shell.automagic = not self.shell.automagic
551 print '\n' + Magic.auto_status[self.shell.automagic]
551 print '\n' + Magic.auto_status[self.shell.automagic]
552
552
553 @testdec.skip_doctest
553 @testdec.skip_doctest
554 def magic_autocall(self, parameter_s = ''):
554 def magic_autocall(self, parameter_s = ''):
555 """Make functions callable without having to type parentheses.
555 """Make functions callable without having to type parentheses.
556
556
557 Usage:
557 Usage:
558
558
559 %autocall [mode]
559 %autocall [mode]
560
560
561 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
562 value is toggled on and off (remembering the previous state).
562 value is toggled on and off (remembering the previous state).
563
563
564 In more detail, these values mean:
564 In more detail, these values mean:
565
565
566 0 -> fully disabled
566 0 -> fully disabled
567
567
568 1 -> active, but do not apply if there are no arguments on the line.
568 1 -> active, but do not apply if there are no arguments on the line.
569
569
570 In this mode, you get:
570 In this mode, you get:
571
571
572 In [1]: callable
572 In [1]: callable
573 Out[1]: <built-in function callable>
573 Out[1]: <built-in function callable>
574
574
575 In [2]: callable 'hello'
575 In [2]: callable 'hello'
576 ------> callable('hello')
576 ------> callable('hello')
577 Out[2]: False
577 Out[2]: False
578
578
579 2 -> Active always. Even if no arguments are present, the callable
579 2 -> Active always. Even if no arguments are present, the callable
580 object is called:
580 object is called:
581
581
582 In [2]: float
582 In [2]: float
583 ------> float()
583 ------> float()
584 Out[2]: 0.0
584 Out[2]: 0.0
585
585
586 Note that even with autocall off, you can still use '/' at the start of
586 Note that even with autocall off, you can still use '/' at the start of
587 a line to treat the first argument on the command line as a function
587 a line to treat the first argument on the command line as a function
588 and add parentheses to it:
588 and add parentheses to it:
589
589
590 In [8]: /str 43
590 In [8]: /str 43
591 ------> str(43)
591 ------> str(43)
592 Out[8]: '43'
592 Out[8]: '43'
593
593
594 # all-random (note for auto-testing)
594 # all-random (note for auto-testing)
595 """
595 """
596
596
597 if parameter_s:
597 if parameter_s:
598 arg = int(parameter_s)
598 arg = int(parameter_s)
599 else:
599 else:
600 arg = 'toggle'
600 arg = 'toggle'
601
601
602 if not arg in (0,1,2,'toggle'):
602 if not arg in (0,1,2,'toggle'):
603 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 error('Valid modes: (0->Off, 1->Smart, 2->Full')
604 return
604 return
605
605
606 if arg in (0,1,2):
606 if arg in (0,1,2):
607 self.shell.autocall = arg
607 self.shell.autocall = arg
608 else: # toggle
608 else: # toggle
609 if self.shell.autocall:
609 if self.shell.autocall:
610 self._magic_state.autocall_save = self.shell.autocall
610 self._magic_state.autocall_save = self.shell.autocall
611 self.shell.autocall = 0
611 self.shell.autocall = 0
612 else:
612 else:
613 try:
613 try:
614 self.shell.autocall = self._magic_state.autocall_save
614 self.shell.autocall = self._magic_state.autocall_save
615 except AttributeError:
615 except AttributeError:
616 self.shell.autocall = self._magic_state.autocall_save = 1
616 self.shell.autocall = self._magic_state.autocall_save = 1
617
617
618 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
619
619
620 def magic_system_verbose(self, parameter_s = ''):
620 def magic_system_verbose(self, parameter_s = ''):
621 """Set verbose printing of system calls.
621 """Set verbose printing of system calls.
622
622
623 If called without an argument, act as a toggle"""
623 If called without an argument, act as a toggle"""
624
624
625 if parameter_s:
625 if parameter_s:
626 val = bool(eval(parameter_s))
626 val = bool(eval(parameter_s))
627 else:
627 else:
628 val = None
628 val = None
629
629
630 if self.shell.system_verbose:
630 if self.shell.system_verbose:
631 self.shell.system_verbose = False
631 self.shell.system_verbose = False
632 else:
632 else:
633 self.shell.system_verbose = True
633 self.shell.system_verbose = True
634 print "System verbose printing is:",\
634 print "System verbose printing is:",\
635 ['OFF','ON'][self.shell.system_verbose]
635 ['OFF','ON'][self.shell.system_verbose]
636
636
637
637
638 def magic_page(self, parameter_s=''):
638 def magic_page(self, parameter_s=''):
639 """Pretty print the object and display it through a pager.
639 """Pretty print the object and display it through a pager.
640
640
641 %page [options] OBJECT
641 %page [options] OBJECT
642
642
643 If no object is given, use _ (last output).
643 If no object is given, use _ (last output).
644
644
645 Options:
645 Options:
646
646
647 -r: page str(object), don't pretty-print it."""
647 -r: page str(object), don't pretty-print it."""
648
648
649 # After a function contributed by Olivier Aubert, slightly modified.
649 # After a function contributed by Olivier Aubert, slightly modified.
650
650
651 # Process options/args
651 # Process options/args
652 opts,args = self.parse_options(parameter_s,'r')
652 opts,args = self.parse_options(parameter_s,'r')
653 raw = 'r' in opts
653 raw = 'r' in opts
654
654
655 oname = args and args or '_'
655 oname = args and args or '_'
656 info = self._ofind(oname)
656 info = self._ofind(oname)
657 if info['found']:
657 if info['found']:
658 txt = (raw and str or pformat)( info['obj'] )
658 txt = (raw and str or pformat)( info['obj'] )
659 page(txt)
659 page(txt)
660 else:
660 else:
661 print 'Object `%s` not found' % oname
661 print 'Object `%s` not found' % oname
662
662
663 def magic_profile(self, parameter_s=''):
663 def magic_profile(self, parameter_s=''):
664 """Print your currently active IPython profile."""
664 """Print your currently active IPython profile."""
665 if self.shell.profile:
665 if self.shell.profile:
666 printpl('Current IPython profile: $self.shell.profile.')
666 printpl('Current IPython profile: $self.shell.profile.')
667 else:
667 else:
668 print 'No profile active.'
668 print 'No profile active.'
669
669
670 def magic_pinfo(self, parameter_s='', namespaces=None):
670 def magic_pinfo(self, parameter_s='', namespaces=None):
671 """Provide detailed information about an object.
671 """Provide detailed information about an object.
672
672
673 '%pinfo object' is just a synonym for object? or ?object."""
673 '%pinfo object' is just a synonym for object? or ?object."""
674
674
675 #print 'pinfo par: <%s>' % parameter_s # dbg
675 #print 'pinfo par: <%s>' % parameter_s # dbg
676
676
677
677
678 # detail_level: 0 -> obj? , 1 -> obj??
678 # detail_level: 0 -> obj? , 1 -> obj??
679 detail_level = 0
679 detail_level = 0
680 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # We need to detect if we got called as 'pinfo pinfo foo', which can
681 # happen if the user types 'pinfo foo?' at the cmd line.
681 # happen if the user types 'pinfo foo?' at the cmd line.
682 pinfo,qmark1,oname,qmark2 = \
682 pinfo,qmark1,oname,qmark2 = \
683 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
684 if pinfo or qmark1 or qmark2:
684 if pinfo or qmark1 or qmark2:
685 detail_level = 1
685 detail_level = 1
686 if "*" in oname:
686 if "*" in oname:
687 self.magic_psearch(oname)
687 self.magic_psearch(oname)
688 else:
688 else:
689 self._inspect('pinfo', oname, detail_level=detail_level,
689 self._inspect('pinfo', oname, detail_level=detail_level,
690 namespaces=namespaces)
690 namespaces=namespaces)
691
691
692 def magic_pdef(self, parameter_s='', namespaces=None):
692 def magic_pdef(self, parameter_s='', namespaces=None):
693 """Print the definition header for any callable object.
693 """Print the definition header for any callable object.
694
694
695 If the object is a class, print the constructor information."""
695 If the object is a class, print the constructor information."""
696 self._inspect('pdef',parameter_s, namespaces)
696 self._inspect('pdef',parameter_s, namespaces)
697
697
698 def magic_pdoc(self, parameter_s='', namespaces=None):
698 def magic_pdoc(self, parameter_s='', namespaces=None):
699 """Print the docstring for an object.
699 """Print the docstring for an object.
700
700
701 If the given object is a class, it will print both the class and the
701 If the given object is a class, it will print both the class and the
702 constructor docstrings."""
702 constructor docstrings."""
703 self._inspect('pdoc',parameter_s, namespaces)
703 self._inspect('pdoc',parameter_s, namespaces)
704
704
705 def magic_psource(self, parameter_s='', namespaces=None):
705 def magic_psource(self, parameter_s='', namespaces=None):
706 """Print (or run through pager) the source code for an object."""
706 """Print (or run through pager) the source code for an object."""
707 self._inspect('psource',parameter_s, namespaces)
707 self._inspect('psource',parameter_s, namespaces)
708
708
709 def magic_pfile(self, parameter_s=''):
709 def magic_pfile(self, parameter_s=''):
710 """Print (or run through pager) the file where an object is defined.
710 """Print (or run through pager) the file where an object is defined.
711
711
712 The file opens at the line where the object definition begins. IPython
712 The file opens at the line where the object definition begins. IPython
713 will honor the environment variable PAGER if set, and otherwise will
713 will honor the environment variable PAGER if set, and otherwise will
714 do its best to print the file in a convenient form.
714 do its best to print the file in a convenient form.
715
715
716 If the given argument is not an object currently defined, IPython will
716 If the given argument is not an object currently defined, IPython will
717 try to interpret it as a filename (automatically adding a .py extension
717 try to interpret it as a filename (automatically adding a .py extension
718 if needed). You can thus use %pfile as a syntax highlighting code
718 if needed). You can thus use %pfile as a syntax highlighting code
719 viewer."""
719 viewer."""
720
720
721 # first interpret argument as an object name
721 # first interpret argument as an object name
722 out = self._inspect('pfile',parameter_s)
722 out = self._inspect('pfile',parameter_s)
723 # if not, try the input as a filename
723 # if not, try the input as a filename
724 if out == 'not found':
724 if out == 'not found':
725 try:
725 try:
726 filename = get_py_filename(parameter_s)
726 filename = get_py_filename(parameter_s)
727 except IOError,msg:
727 except IOError,msg:
728 print msg
728 print msg
729 return
729 return
730 page(self.shell.inspector.format(file(filename).read()))
730 page(self.shell.inspector.format(file(filename).read()))
731
731
732 def _inspect(self,meth,oname,namespaces=None,**kw):
732 def _inspect(self,meth,oname,namespaces=None,**kw):
733 """Generic interface to the inspector system.
733 """Generic interface to the inspector system.
734
734
735 This function is meant to be called by pdef, pdoc & friends."""
735 This function is meant to be called by pdef, pdoc & friends."""
736
736
737 #oname = oname.strip()
737 #oname = oname.strip()
738 #print '1- oname: <%r>' % oname # dbg
738 #print '1- oname: <%r>' % oname # dbg
739 try:
739 try:
740 oname = oname.strip().encode('ascii')
740 oname = oname.strip().encode('ascii')
741 #print '2- oname: <%r>' % oname # dbg
741 #print '2- oname: <%r>' % oname # dbg
742 except UnicodeEncodeError:
742 except UnicodeEncodeError:
743 print 'Python identifiers can only contain ascii characters.'
743 print 'Python identifiers can only contain ascii characters.'
744 return 'not found'
744 return 'not found'
745
745
746 info = Struct(self._ofind(oname, namespaces))
746 info = Struct(self._ofind(oname, namespaces))
747
747
748 if info.found:
748 if info.found:
749 try:
749 try:
750 IPython.utils.generics.inspect_object(info.obj)
750 IPython.utils.generics.inspect_object(info.obj)
751 return
751 return
752 except TryNext:
752 except TryNext:
753 pass
753 pass
754 # Get the docstring of the class property if it exists.
754 # Get the docstring of the class property if it exists.
755 path = oname.split('.')
755 path = oname.split('.')
756 root = '.'.join(path[:-1])
756 root = '.'.join(path[:-1])
757 if info.parent is not None:
757 if info.parent is not None:
758 try:
758 try:
759 target = getattr(info.parent, '__class__')
759 target = getattr(info.parent, '__class__')
760 # The object belongs to a class instance.
760 # The object belongs to a class instance.
761 try:
761 try:
762 target = getattr(target, path[-1])
762 target = getattr(target, path[-1])
763 # The class defines the object.
763 # The class defines the object.
764 if isinstance(target, property):
764 if isinstance(target, property):
765 oname = root + '.__class__.' + path[-1]
765 oname = root + '.__class__.' + path[-1]
766 info = Struct(self._ofind(oname))
766 info = Struct(self._ofind(oname))
767 except AttributeError: pass
767 except AttributeError: pass
768 except AttributeError: pass
768 except AttributeError: pass
769
769
770 pmethod = getattr(self.shell.inspector,meth)
770 pmethod = getattr(self.shell.inspector,meth)
771 formatter = info.ismagic and self.format_screen or None
771 formatter = info.ismagic and self.format_screen or None
772 if meth == 'pdoc':
772 if meth == 'pdoc':
773 pmethod(info.obj,oname,formatter)
773 pmethod(info.obj,oname,formatter)
774 elif meth == 'pinfo':
774 elif meth == 'pinfo':
775 pmethod(info.obj,oname,formatter,info,**kw)
775 pmethod(info.obj,oname,formatter,info,**kw)
776 else:
776 else:
777 pmethod(info.obj,oname)
777 pmethod(info.obj,oname)
778 else:
778 else:
779 print 'Object `%s` not found.' % oname
779 print 'Object `%s` not found.' % oname
780 return 'not found' # so callers can take other action
780 return 'not found' # so callers can take other action
781
781
782 def magic_psearch(self, parameter_s=''):
782 def magic_psearch(self, parameter_s=''):
783 """Search for object in namespaces by wildcard.
783 """Search for object in namespaces by wildcard.
784
784
785 %psearch [options] PATTERN [OBJECT TYPE]
785 %psearch [options] PATTERN [OBJECT TYPE]
786
786
787 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 Note: ? can be used as a synonym for %psearch, at the beginning or at
788 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
789 rest of the command line must be unchanged (options come first), so
789 rest of the command line must be unchanged (options come first), so
790 for example the following forms are equivalent
790 for example the following forms are equivalent
791
791
792 %psearch -i a* function
792 %psearch -i a* function
793 -i a* function?
793 -i a* function?
794 ?-i a* function
794 ?-i a* function
795
795
796 Arguments:
796 Arguments:
797
797
798 PATTERN
798 PATTERN
799
799
800 where PATTERN is a string containing * as a wildcard similar to its
800 where PATTERN is a string containing * as a wildcard similar to its
801 use in a shell. The pattern is matched in all namespaces on the
801 use in a shell. The pattern is matched in all namespaces on the
802 search path. By default objects starting with a single _ are not
802 search path. By default objects starting with a single _ are not
803 matched, many IPython generated objects have a single
803 matched, many IPython generated objects have a single
804 underscore. The default is case insensitive matching. Matching is
804 underscore. The default is case insensitive matching. Matching is
805 also done on the attributes of objects and not only on the objects
805 also done on the attributes of objects and not only on the objects
806 in a module.
806 in a module.
807
807
808 [OBJECT TYPE]
808 [OBJECT TYPE]
809
809
810 Is the name of a python type from the types module. The name is
810 Is the name of a python type from the types module. The name is
811 given in lowercase without the ending type, ex. StringType is
811 given in lowercase without the ending type, ex. StringType is
812 written string. By adding a type here only objects matching the
812 written string. By adding a type here only objects matching the
813 given type are matched. Using all here makes the pattern match all
813 given type are matched. Using all here makes the pattern match all
814 types (this is the default).
814 types (this is the default).
815
815
816 Options:
816 Options:
817
817
818 -a: makes the pattern match even objects whose names start with a
818 -a: makes the pattern match even objects whose names start with a
819 single underscore. These names are normally ommitted from the
819 single underscore. These names are normally ommitted from the
820 search.
820 search.
821
821
822 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 -i/-c: make the pattern case insensitive/sensitive. If neither of
823 these options is given, the default is read from your ipythonrc
823 these options is given, the default is read from your ipythonrc
824 file. The option name which sets this value is
824 file. The option name which sets this value is
825 'wildcards_case_sensitive'. If this option is not specified in your
825 'wildcards_case_sensitive'. If this option is not specified in your
826 ipythonrc file, IPython's internal default is to do a case sensitive
826 ipythonrc file, IPython's internal default is to do a case sensitive
827 search.
827 search.
828
828
829 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
830 specifiy can be searched in any of the following namespaces:
830 specifiy can be searched in any of the following namespaces:
831 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin', 'user', 'user_global','internal', 'alias', where
832 'builtin' and 'user' are the search defaults. Note that you should
832 'builtin' and 'user' are the search defaults. Note that you should
833 not use quotes when specifying namespaces.
833 not use quotes when specifying namespaces.
834
834
835 'Builtin' contains the python module builtin, 'user' contains all
835 'Builtin' contains the python module builtin, 'user' contains all
836 user data, 'alias' only contain the shell aliases and no python
836 user data, 'alias' only contain the shell aliases and no python
837 objects, 'internal' contains objects used by IPython. The
837 objects, 'internal' contains objects used by IPython. The
838 'user_global' namespace is only used by embedded IPython instances,
838 'user_global' namespace is only used by embedded IPython instances,
839 and it contains module-level globals. You can add namespaces to the
839 and it contains module-level globals. You can add namespaces to the
840 search with -s or exclude them with -e (these options can be given
840 search with -s or exclude them with -e (these options can be given
841 more than once).
841 more than once).
842
842
843 Examples:
843 Examples:
844
844
845 %psearch a* -> objects beginning with an a
845 %psearch a* -> objects beginning with an a
846 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
847 %psearch a* function -> all functions beginning with an a
847 %psearch a* function -> all functions beginning with an a
848 %psearch re.e* -> objects beginning with an e in module re
848 %psearch re.e* -> objects beginning with an e in module re
849 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.e* -> objects that start with e in modules starting in r
850 %psearch r*.* string -> all strings in modules beginning with r
850 %psearch r*.* string -> all strings in modules beginning with r
851
851
852 Case sensitve search:
852 Case sensitve search:
853
853
854 %psearch -c a* list all object beginning with lower case a
854 %psearch -c a* list all object beginning with lower case a
855
855
856 Show objects beginning with a single _:
856 Show objects beginning with a single _:
857
857
858 %psearch -a _* list objects beginning with a single underscore"""
858 %psearch -a _* list objects beginning with a single underscore"""
859 try:
859 try:
860 parameter_s = parameter_s.encode('ascii')
860 parameter_s = parameter_s.encode('ascii')
861 except UnicodeEncodeError:
861 except UnicodeEncodeError:
862 print 'Python identifiers can only contain ascii characters.'
862 print 'Python identifiers can only contain ascii characters.'
863 return
863 return
864
864
865 # default namespaces to be searched
865 # default namespaces to be searched
866 def_search = ['user','builtin']
866 def_search = ['user','builtin']
867
867
868 # Process options/args
868 # Process options/args
869 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
870 opt = opts.get
870 opt = opts.get
871 shell = self.shell
871 shell = self.shell
872 psearch = shell.inspector.psearch
872 psearch = shell.inspector.psearch
873
873
874 # select case options
874 # select case options
875 if opts.has_key('i'):
875 if opts.has_key('i'):
876 ignore_case = True
876 ignore_case = True
877 elif opts.has_key('c'):
877 elif opts.has_key('c'):
878 ignore_case = False
878 ignore_case = False
879 else:
879 else:
880 ignore_case = not shell.wildcards_case_sensitive
880 ignore_case = not shell.wildcards_case_sensitive
881
881
882 # Build list of namespaces to search from user options
882 # Build list of namespaces to search from user options
883 def_search.extend(opt('s',[]))
883 def_search.extend(opt('s',[]))
884 ns_exclude = ns_exclude=opt('e',[])
884 ns_exclude = ns_exclude=opt('e',[])
885 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885 ns_search = [nm for nm in def_search if nm not in ns_exclude]
886
886
887 # Call the actual search
887 # Call the actual search
888 try:
888 try:
889 psearch(args,shell.ns_table,ns_search,
889 psearch(args,shell.ns_table,ns_search,
890 show_all=opt('a'),ignore_case=ignore_case)
890 show_all=opt('a'),ignore_case=ignore_case)
891 except:
891 except:
892 shell.showtraceback()
892 shell.showtraceback()
893
893
894 def magic_who_ls(self, parameter_s=''):
894 def magic_who_ls(self, parameter_s=''):
895 """Return a sorted list of all interactive variables.
895 """Return a sorted list of all interactive variables.
896
896
897 If arguments are given, only variables of types matching these
897 If arguments are given, only variables of types matching these
898 arguments are returned."""
898 arguments are returned."""
899
899
900 user_ns = self.shell.user_ns
900 user_ns = self.shell.user_ns
901 internal_ns = self.shell.internal_ns
901 internal_ns = self.shell.internal_ns
902 user_ns_hidden = self.shell.user_ns_hidden
902 user_ns_hidden = self.shell.user_ns_hidden
903 out = [ i for i in user_ns
903 out = [ i for i in user_ns
904 if not i.startswith('_') \
904 if not i.startswith('_') \
905 and not (i in internal_ns or i in user_ns_hidden) ]
905 and not (i in internal_ns or i in user_ns_hidden) ]
906
906
907 typelist = parameter_s.split()
907 typelist = parameter_s.split()
908 if typelist:
908 if typelist:
909 typeset = set(typelist)
909 typeset = set(typelist)
910 out = [i for i in out if type(i).__name__ in typeset]
910 out = [i for i in out if type(i).__name__ in typeset]
911
911
912 out.sort()
912 out.sort()
913 return out
913 return out
914
914
915 def magic_who(self, parameter_s=''):
915 def magic_who(self, parameter_s=''):
916 """Print all interactive variables, with some minimal formatting.
916 """Print all interactive variables, with some minimal formatting.
917
917
918 If any arguments are given, only variables whose type matches one of
918 If any arguments are given, only variables whose type matches one of
919 these are printed. For example:
919 these are printed. For example:
920
920
921 %who function str
921 %who function str
922
922
923 will only list functions and strings, excluding all other types of
923 will only list functions and strings, excluding all other types of
924 variables. To find the proper type names, simply use type(var) at a
924 variables. To find the proper type names, simply use type(var) at a
925 command line to see how python prints type names. For example:
925 command line to see how python prints type names. For example:
926
926
927 In [1]: type('hello')\\
927 In [1]: type('hello')\\
928 Out[1]: <type 'str'>
928 Out[1]: <type 'str'>
929
929
930 indicates that the type name for strings is 'str'.
930 indicates that the type name for strings is 'str'.
931
931
932 %who always excludes executed names loaded through your configuration
932 %who always excludes executed names loaded through your configuration
933 file and things which are internal to IPython.
933 file and things which are internal to IPython.
934
934
935 This is deliberate, as typically you may load many modules and the
935 This is deliberate, as typically you may load many modules and the
936 purpose of %who is to show you only what you've manually defined."""
936 purpose of %who is to show you only what you've manually defined."""
937
937
938 varlist = self.magic_who_ls(parameter_s)
938 varlist = self.magic_who_ls(parameter_s)
939 if not varlist:
939 if not varlist:
940 if parameter_s:
940 if parameter_s:
941 print 'No variables match your requested type.'
941 print 'No variables match your requested type.'
942 else:
942 else:
943 print 'Interactive namespace is empty.'
943 print 'Interactive namespace is empty.'
944 return
944 return
945
945
946 # if we have variables, move on...
946 # if we have variables, move on...
947 count = 0
947 count = 0
948 for i in varlist:
948 for i in varlist:
949 print i+'\t',
949 print i+'\t',
950 count += 1
950 count += 1
951 if count > 8:
951 if count > 8:
952 count = 0
952 count = 0
953 print
953 print
954 print
954 print
955
955
956 def magic_whos(self, parameter_s=''):
956 def magic_whos(self, parameter_s=''):
957 """Like %who, but gives some extra information about each variable.
957 """Like %who, but gives some extra information about each variable.
958
958
959 The same type filtering of %who can be applied here.
959 The same type filtering of %who can be applied here.
960
960
961 For all variables, the type is printed. Additionally it prints:
961 For all variables, the type is printed. Additionally it prints:
962
962
963 - For {},[],(): their length.
963 - For {},[],(): their length.
964
964
965 - For numpy and Numeric arrays, a summary with shape, number of
965 - For numpy and Numeric arrays, a summary with shape, number of
966 elements, typecode and size in memory.
966 elements, typecode and size in memory.
967
967
968 - Everything else: a string representation, snipping their middle if
968 - Everything else: a string representation, snipping their middle if
969 too long."""
969 too long."""
970
970
971 varnames = self.magic_who_ls(parameter_s)
971 varnames = self.magic_who_ls(parameter_s)
972 if not varnames:
972 if not varnames:
973 if parameter_s:
973 if parameter_s:
974 print 'No variables match your requested type.'
974 print 'No variables match your requested type.'
975 else:
975 else:
976 print 'Interactive namespace is empty.'
976 print 'Interactive namespace is empty.'
977 return
977 return
978
978
979 # if we have variables, move on...
979 # if we have variables, move on...
980
980
981 # for these types, show len() instead of data:
981 # for these types, show len() instead of data:
982 seq_types = [types.DictType,types.ListType,types.TupleType]
982 seq_types = [types.DictType,types.ListType,types.TupleType]
983
983
984 # for numpy/Numeric arrays, display summary info
984 # for numpy/Numeric arrays, display summary info
985 try:
985 try:
986 import numpy
986 import numpy
987 except ImportError:
987 except ImportError:
988 ndarray_type = None
988 ndarray_type = None
989 else:
989 else:
990 ndarray_type = numpy.ndarray.__name__
990 ndarray_type = numpy.ndarray.__name__
991 try:
991 try:
992 import Numeric
992 import Numeric
993 except ImportError:
993 except ImportError:
994 array_type = None
994 array_type = None
995 else:
995 else:
996 array_type = Numeric.ArrayType.__name__
996 array_type = Numeric.ArrayType.__name__
997
997
998 # Find all variable names and types so we can figure out column sizes
998 # Find all variable names and types so we can figure out column sizes
999 def get_vars(i):
999 def get_vars(i):
1000 return self.shell.user_ns[i]
1000 return self.shell.user_ns[i]
1001
1001
1002 # some types are well known and can be shorter
1002 # some types are well known and can be shorter
1003 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1004 def type_name(v):
1004 def type_name(v):
1005 tn = type(v).__name__
1005 tn = type(v).__name__
1006 return abbrevs.get(tn,tn)
1006 return abbrevs.get(tn,tn)
1007
1007
1008 varlist = map(get_vars,varnames)
1008 varlist = map(get_vars,varnames)
1009
1009
1010 typelist = []
1010 typelist = []
1011 for vv in varlist:
1011 for vv in varlist:
1012 tt = type_name(vv)
1012 tt = type_name(vv)
1013
1013
1014 if tt=='instance':
1014 if tt=='instance':
1015 typelist.append( abbrevs.get(str(vv.__class__),
1015 typelist.append( abbrevs.get(str(vv.__class__),
1016 str(vv.__class__)))
1016 str(vv.__class__)))
1017 else:
1017 else:
1018 typelist.append(tt)
1018 typelist.append(tt)
1019
1019
1020 # column labels and # of spaces as separator
1020 # column labels and # of spaces as separator
1021 varlabel = 'Variable'
1021 varlabel = 'Variable'
1022 typelabel = 'Type'
1022 typelabel = 'Type'
1023 datalabel = 'Data/Info'
1023 datalabel = 'Data/Info'
1024 colsep = 3
1024 colsep = 3
1025 # variable format strings
1025 # variable format strings
1026 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1027 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1028 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 aformat = "%s: %s elems, type `%s`, %s bytes"
1029 # find the size of the columns to format the output nicely
1029 # find the size of the columns to format the output nicely
1030 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1031 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1032 # table header
1032 # table header
1033 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1034 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1035 # and the table itself
1035 # and the table itself
1036 kb = 1024
1036 kb = 1024
1037 Mb = 1048576 # kb**2
1037 Mb = 1048576 # kb**2
1038 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 for vname,var,vtype in zip(varnames,varlist,typelist):
1039 print itpl(vformat),
1039 print itpl(vformat),
1040 if vtype in seq_types:
1040 if vtype in seq_types:
1041 print len(var)
1041 print len(var)
1042 elif vtype in [array_type,ndarray_type]:
1042 elif vtype in [array_type,ndarray_type]:
1043 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1044 if vtype==ndarray_type:
1044 if vtype==ndarray_type:
1045 # numpy
1045 # numpy
1046 vsize = var.size
1046 vsize = var.size
1047 vbytes = vsize*var.itemsize
1047 vbytes = vsize*var.itemsize
1048 vdtype = var.dtype
1048 vdtype = var.dtype
1049 else:
1049 else:
1050 # Numeric
1050 # Numeric
1051 vsize = Numeric.size(var)
1051 vsize = Numeric.size(var)
1052 vbytes = vsize*var.itemsize()
1052 vbytes = vsize*var.itemsize()
1053 vdtype = var.typecode()
1053 vdtype = var.typecode()
1054
1054
1055 if vbytes < 100000:
1055 if vbytes < 100000:
1056 print aformat % (vshape,vsize,vdtype,vbytes)
1056 print aformat % (vshape,vsize,vdtype,vbytes)
1057 else:
1057 else:
1058 print aformat % (vshape,vsize,vdtype,vbytes),
1058 print aformat % (vshape,vsize,vdtype,vbytes),
1059 if vbytes < Mb:
1059 if vbytes < Mb:
1060 print '(%s kb)' % (vbytes/kb,)
1060 print '(%s kb)' % (vbytes/kb,)
1061 else:
1061 else:
1062 print '(%s Mb)' % (vbytes/Mb,)
1062 print '(%s Mb)' % (vbytes/Mb,)
1063 else:
1063 else:
1064 try:
1064 try:
1065 vstr = str(var)
1065 vstr = str(var)
1066 except UnicodeEncodeError:
1066 except UnicodeEncodeError:
1067 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 vstr = unicode(var).encode(sys.getdefaultencoding(),
1068 'backslashreplace')
1068 'backslashreplace')
1069 vstr = vstr.replace('\n','\\n')
1069 vstr = vstr.replace('\n','\\n')
1070 if len(vstr) < 50:
1070 if len(vstr) < 50:
1071 print vstr
1071 print vstr
1072 else:
1072 else:
1073 printpl(vfmt_short)
1073 printpl(vfmt_short)
1074
1074
1075 def magic_reset(self, parameter_s=''):
1075 def magic_reset(self, parameter_s=''):
1076 """Resets the namespace by removing all names defined by the user.
1076 """Resets the namespace by removing all names defined by the user.
1077
1077
1078 Input/Output history are left around in case you need them.
1078 Input/Output history are left around in case you need them.
1079
1079
1080 Parameters
1080 Parameters
1081 ----------
1081 ----------
1082 -y : force reset without asking for confirmation.
1082 -y : force reset without asking for confirmation.
1083
1083
1084 Examples
1084 Examples
1085 --------
1085 --------
1086 In [6]: a = 1
1086 In [6]: a = 1
1087
1087
1088 In [7]: a
1088 In [7]: a
1089 Out[7]: 1
1089 Out[7]: 1
1090
1090
1091 In [8]: 'a' in _ip.user_ns
1091 In [8]: 'a' in _ip.user_ns
1092 Out[8]: True
1092 Out[8]: True
1093
1093
1094 In [9]: %reset -f
1094 In [9]: %reset -f
1095
1095
1096 In [10]: 'a' in _ip.user_ns
1096 In [10]: 'a' in _ip.user_ns
1097 Out[10]: False
1097 Out[10]: False
1098 """
1098 """
1099
1099
1100 if parameter_s == '-f':
1100 if parameter_s == '-f':
1101 ans = True
1101 ans = True
1102 else:
1102 else:
1103 ans = self.shell.ask_yes_no(
1103 ans = self.shell.ask_yes_no(
1104 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1105 if not ans:
1105 if not ans:
1106 print 'Nothing done.'
1106 print 'Nothing done.'
1107 return
1107 return
1108 user_ns = self.shell.user_ns
1108 user_ns = self.shell.user_ns
1109 for i in self.magic_who_ls():
1109 for i in self.magic_who_ls():
1110 del(user_ns[i])
1110 del(user_ns[i])
1111
1111
1112 # Also flush the private list of module references kept for script
1112 # Also flush the private list of module references kept for script
1113 # execution protection
1113 # execution protection
1114 self.shell.clear_main_mod_cache()
1114 self.shell.clear_main_mod_cache()
1115
1115
1116 def magic_reset_selective(self, parameter_s=''):
1116 def magic_reset_selective(self, parameter_s=''):
1117 """Resets the namespace by removing names defined by the user.
1117 """Resets the namespace by removing names defined by the user.
1118
1118
1119 Input/Output history are left around in case you need them.
1119 Input/Output history are left around in case you need them.
1120
1120
1121 %reset_selective [-f] regex
1121 %reset_selective [-f] regex
1122
1122
1123 No action is taken if regex is not included
1123 No action is taken if regex is not included
1124
1124
1125 Options
1125 Options
1126 -f : force reset without asking for confirmation.
1126 -f : force reset without asking for confirmation.
1127
1127
1128 Examples
1128 Examples
1129 --------
1129 --------
1130
1130
1131 We first fully reset the namespace so your output looks identical to
1131 We first fully reset the namespace so your output looks identical to
1132 this example for pedagogical reasons; in practice you do not need a
1132 this example for pedagogical reasons; in practice you do not need a
1133 full reset.
1133 full reset.
1134
1134
1135 In [1]: %reset -f
1135 In [1]: %reset -f
1136
1136
1137 Now, with a clean namespace we can make a few variables and use
1137 Now, with a clean namespace we can make a few variables and use
1138 %reset_selective to only delete names that match our regexp:
1138 %reset_selective to only delete names that match our regexp:
1139
1139
1140 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1141
1141
1142 In [3]: who_ls
1142 In [3]: who_ls
1143 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1144
1144
1145 In [4]: %reset_selective -f b[2-3]m
1145 In [4]: %reset_selective -f b[2-3]m
1146
1146
1147 In [5]: who_ls
1147 In [5]: who_ls
1148 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1149
1149
1150 In [6]: %reset_selective -f d
1150 In [6]: %reset_selective -f d
1151
1151
1152 In [7]: who_ls
1152 In [7]: who_ls
1153 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1154
1154
1155 In [8]: %reset_selective -f c
1155 In [8]: %reset_selective -f c
1156
1156
1157 In [9]: who_ls
1157 In [9]: who_ls
1158 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1159
1159
1160 In [10]: %reset_selective -f b
1160 In [10]: %reset_selective -f b
1161
1161
1162 In [11]: who_ls
1162 In [11]: who_ls
1163 Out[11]: ['a']
1163 Out[11]: ['a']
1164 """
1164 """
1165
1165
1166 opts, regex = self.parse_options(parameter_s,'f')
1166 opts, regex = self.parse_options(parameter_s,'f')
1167
1167
1168 if opts.has_key('f'):
1168 if opts.has_key('f'):
1169 ans = True
1169 ans = True
1170 else:
1170 else:
1171 ans = self.shell.ask_yes_no(
1171 ans = self.shell.ask_yes_no(
1172 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1173 if not ans:
1173 if not ans:
1174 print 'Nothing done.'
1174 print 'Nothing done.'
1175 return
1175 return
1176 user_ns = self.shell.user_ns
1176 user_ns = self.shell.user_ns
1177 if not regex:
1177 if not regex:
1178 print 'No regex pattern specified. Nothing done.'
1178 print 'No regex pattern specified. Nothing done.'
1179 return
1179 return
1180 else:
1180 else:
1181 try:
1181 try:
1182 m = re.compile(regex)
1182 m = re.compile(regex)
1183 except TypeError:
1183 except TypeError:
1184 raise TypeError('regex must be a string or compiled pattern')
1184 raise TypeError('regex must be a string or compiled pattern')
1185 for i in self.magic_who_ls():
1185 for i in self.magic_who_ls():
1186 if m.search(i):
1186 if m.search(i):
1187 del(user_ns[i])
1187 del(user_ns[i])
1188
1188
1189 def magic_logstart(self,parameter_s=''):
1189 def magic_logstart(self,parameter_s=''):
1190 """Start logging anywhere in a session.
1190 """Start logging anywhere in a session.
1191
1191
1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1193
1193
1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1195 current directory, in 'rotate' mode (see below).
1195 current directory, in 'rotate' mode (see below).
1196
1196
1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1198 history up to that point and then continues logging.
1198 history up to that point and then continues logging.
1199
1199
1200 %logstart takes a second optional parameter: logging mode. This can be one
1200 %logstart takes a second optional parameter: logging mode. This can be one
1201 of (note that the modes are given unquoted):\\
1201 of (note that the modes are given unquoted):\\
1202 append: well, that says it.\\
1202 append: well, that says it.\\
1203 backup: rename (if exists) to name~ and start name.\\
1203 backup: rename (if exists) to name~ and start name.\\
1204 global: single logfile in your home dir, appended to.\\
1204 global: single logfile in your home dir, appended to.\\
1205 over : overwrite existing log.\\
1205 over : overwrite existing log.\\
1206 rotate: create rotating logs name.1~, name.2~, etc.
1206 rotate: create rotating logs name.1~, name.2~, etc.
1207
1207
1208 Options:
1208 Options:
1209
1209
1210 -o: log also IPython's output. In this mode, all commands which
1210 -o: log also IPython's output. In this mode, all commands which
1211 generate an Out[NN] prompt are recorded to the logfile, right after
1211 generate an Out[NN] prompt are recorded to the logfile, right after
1212 their corresponding input line. The output lines are always
1212 their corresponding input line. The output lines are always
1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1214 Python code.
1214 Python code.
1215
1215
1216 Since this marker is always the same, filtering only the output from
1216 Since this marker is always the same, filtering only the output from
1217 a log is very easy, using for example a simple awk call:
1217 a log is very easy, using for example a simple awk call:
1218
1218
1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1220
1220
1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1222 input, so that user lines are logged in their final form, converted
1222 input, so that user lines are logged in their final form, converted
1223 into valid Python. For example, %Exit is logged as
1223 into valid Python. For example, %Exit is logged as
1224 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1225 exactly as typed, with no transformations applied.
1225 exactly as typed, with no transformations applied.
1226
1226
1227 -t: put timestamps before each input line logged (these are put in
1227 -t: put timestamps before each input line logged (these are put in
1228 comments)."""
1228 comments)."""
1229
1229
1230 opts,par = self.parse_options(parameter_s,'ort')
1230 opts,par = self.parse_options(parameter_s,'ort')
1231 log_output = 'o' in opts
1231 log_output = 'o' in opts
1232 log_raw_input = 'r' in opts
1232 log_raw_input = 'r' in opts
1233 timestamp = 't' in opts
1233 timestamp = 't' in opts
1234
1234
1235 logger = self.shell.logger
1235 logger = self.shell.logger
1236
1236
1237 # if no args are given, the defaults set in the logger constructor by
1237 # if no args are given, the defaults set in the logger constructor by
1238 # ipytohn remain valid
1238 # ipytohn remain valid
1239 if par:
1239 if par:
1240 try:
1240 try:
1241 logfname,logmode = par.split()
1241 logfname,logmode = par.split()
1242 except:
1242 except:
1243 logfname = par
1243 logfname = par
1244 logmode = 'backup'
1244 logmode = 'backup'
1245 else:
1245 else:
1246 logfname = logger.logfname
1246 logfname = logger.logfname
1247 logmode = logger.logmode
1247 logmode = logger.logmode
1248 # put logfname into rc struct as if it had been called on the command
1248 # put logfname into rc struct as if it had been called on the command
1249 # line, so it ends up saved in the log header Save it in case we need
1249 # line, so it ends up saved in the log header Save it in case we need
1250 # to restore it...
1250 # to restore it...
1251 old_logfile = self.shell.logfile
1251 old_logfile = self.shell.logfile
1252 if logfname:
1252 if logfname:
1253 logfname = os.path.expanduser(logfname)
1253 logfname = os.path.expanduser(logfname)
1254 self.shell.logfile = logfname
1254 self.shell.logfile = logfname
1255
1255
1256 loghead = '# IPython log file\n\n'
1256 loghead = '# IPython log file\n\n'
1257 try:
1257 try:
1258 started = logger.logstart(logfname,loghead,logmode,
1258 started = logger.logstart(logfname,loghead,logmode,
1259 log_output,timestamp,log_raw_input)
1259 log_output,timestamp,log_raw_input)
1260 except:
1260 except:
1261 self.shell.logfile = old_logfile
1261 self.shell.logfile = old_logfile
1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1263 else:
1263 else:
1264 # log input history up to this point, optionally interleaving
1264 # log input history up to this point, optionally interleaving
1265 # output if requested
1265 # output if requested
1266
1266
1267 if timestamp:
1267 if timestamp:
1268 # disable timestamping for the previous history, since we've
1268 # disable timestamping for the previous history, since we've
1269 # lost those already (no time machine here).
1269 # lost those already (no time machine here).
1270 logger.timestamp = False
1270 logger.timestamp = False
1271
1271
1272 if log_raw_input:
1272 if log_raw_input:
1273 input_hist = self.shell.input_hist_raw
1273 input_hist = self.shell.input_hist_raw
1274 else:
1274 else:
1275 input_hist = self.shell.input_hist
1275 input_hist = self.shell.input_hist
1276
1276
1277 if log_output:
1277 if log_output:
1278 log_write = logger.log_write
1278 log_write = logger.log_write
1279 output_hist = self.shell.output_hist
1279 output_hist = self.shell.output_hist
1280 for n in range(1,len(input_hist)-1):
1280 for n in range(1,len(input_hist)-1):
1281 log_write(input_hist[n].rstrip())
1281 log_write(input_hist[n].rstrip())
1282 if n in output_hist:
1282 if n in output_hist:
1283 log_write(repr(output_hist[n]),'output')
1283 log_write(repr(output_hist[n]),'output')
1284 else:
1284 else:
1285 logger.log_write(input_hist[1:])
1285 logger.log_write(input_hist[1:])
1286 if timestamp:
1286 if timestamp:
1287 # re-enable timestamping
1287 # re-enable timestamping
1288 logger.timestamp = True
1288 logger.timestamp = True
1289
1289
1290 print ('Activating auto-logging. '
1290 print ('Activating auto-logging. '
1291 'Current session state plus future input saved.')
1291 'Current session state plus future input saved.')
1292 logger.logstate()
1292 logger.logstate()
1293
1293
1294 def magic_logstop(self,parameter_s=''):
1294 def magic_logstop(self,parameter_s=''):
1295 """Fully stop logging and close log file.
1295 """Fully stop logging and close log file.
1296
1296
1297 In order to start logging again, a new %logstart call needs to be made,
1297 In order to start logging again, a new %logstart call needs to be made,
1298 possibly (though not necessarily) with a new filename, mode and other
1298 possibly (though not necessarily) with a new filename, mode and other
1299 options."""
1299 options."""
1300 self.logger.logstop()
1300 self.logger.logstop()
1301
1301
1302 def magic_logoff(self,parameter_s=''):
1302 def magic_logoff(self,parameter_s=''):
1303 """Temporarily stop logging.
1303 """Temporarily stop logging.
1304
1304
1305 You must have previously started logging."""
1305 You must have previously started logging."""
1306 self.shell.logger.switch_log(0)
1306 self.shell.logger.switch_log(0)
1307
1307
1308 def magic_logon(self,parameter_s=''):
1308 def magic_logon(self,parameter_s=''):
1309 """Restart logging.
1309 """Restart logging.
1310
1310
1311 This function is for restarting logging which you've temporarily
1311 This function is for restarting logging which you've temporarily
1312 stopped with %logoff. For starting logging for the first time, you
1312 stopped with %logoff. For starting logging for the first time, you
1313 must use the %logstart function, which allows you to specify an
1313 must use the %logstart function, which allows you to specify an
1314 optional log filename."""
1314 optional log filename."""
1315
1315
1316 self.shell.logger.switch_log(1)
1316 self.shell.logger.switch_log(1)
1317
1317
1318 def magic_logstate(self,parameter_s=''):
1318 def magic_logstate(self,parameter_s=''):
1319 """Print the status of the logging system."""
1319 """Print the status of the logging system."""
1320
1320
1321 self.shell.logger.logstate()
1321 self.shell.logger.logstate()
1322
1322
1323 def magic_pdb(self, parameter_s=''):
1323 def magic_pdb(self, parameter_s=''):
1324 """Control the automatic calling of the pdb interactive debugger.
1324 """Control the automatic calling of the pdb interactive debugger.
1325
1325
1326 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1327 argument it works as a toggle.
1327 argument it works as a toggle.
1328
1328
1329 When an exception is triggered, IPython can optionally call the
1329 When an exception is triggered, IPython can optionally call the
1330 interactive pdb debugger after the traceback printout. %pdb toggles
1330 interactive pdb debugger after the traceback printout. %pdb toggles
1331 this feature on and off.
1331 this feature on and off.
1332
1332
1333 The initial state of this feature is set in your ipythonrc
1333 The initial state of this feature is set in your ipythonrc
1334 configuration file (the variable is called 'pdb').
1334 configuration file (the variable is called 'pdb').
1335
1335
1336 If you want to just activate the debugger AFTER an exception has fired,
1336 If you want to just activate the debugger AFTER an exception has fired,
1337 without having to type '%pdb on' and rerunning your code, you can use
1337 without having to type '%pdb on' and rerunning your code, you can use
1338 the %debug magic."""
1338 the %debug magic."""
1339
1339
1340 par = parameter_s.strip().lower()
1340 par = parameter_s.strip().lower()
1341
1341
1342 if par:
1342 if par:
1343 try:
1343 try:
1344 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1345 except KeyError:
1345 except KeyError:
1346 print ('Incorrect argument. Use on/1, off/0, '
1346 print ('Incorrect argument. Use on/1, off/0, '
1347 'or nothing for a toggle.')
1347 'or nothing for a toggle.')
1348 return
1348 return
1349 else:
1349 else:
1350 # toggle
1350 # toggle
1351 new_pdb = not self.shell.call_pdb
1351 new_pdb = not self.shell.call_pdb
1352
1352
1353 # set on the shell
1353 # set on the shell
1354 self.shell.call_pdb = new_pdb
1354 self.shell.call_pdb = new_pdb
1355 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1356
1356
1357 def magic_debug(self, parameter_s=''):
1357 def magic_debug(self, parameter_s=''):
1358 """Activate the interactive debugger in post-mortem mode.
1358 """Activate the interactive debugger in post-mortem mode.
1359
1359
1360 If an exception has just occurred, this lets you inspect its stack
1360 If an exception has just occurred, this lets you inspect its stack
1361 frames interactively. Note that this will always work only on the last
1361 frames interactively. Note that this will always work only on the last
1362 traceback that occurred, so you must call this quickly after an
1362 traceback that occurred, so you must call this quickly after an
1363 exception that you wish to inspect has fired, because if another one
1363 exception that you wish to inspect has fired, because if another one
1364 occurs, it clobbers the previous one.
1364 occurs, it clobbers the previous one.
1365
1365
1366 If you want IPython to automatically do this on every exception, see
1366 If you want IPython to automatically do this on every exception, see
1367 the %pdb magic for more details.
1367 the %pdb magic for more details.
1368 """
1368 """
1369 self.shell.debugger(force=True)
1369 self.shell.debugger(force=True)
1370
1370
1371 @testdec.skip_doctest
1371 @testdec.skip_doctest
1372 def magic_prun(self, parameter_s ='',user_mode=1,
1372 def magic_prun(self, parameter_s ='',user_mode=1,
1373 opts=None,arg_lst=None,prog_ns=None):
1373 opts=None,arg_lst=None,prog_ns=None):
1374
1374
1375 """Run a statement through the python code profiler.
1375 """Run a statement through the python code profiler.
1376
1376
1377 Usage:
1377 Usage:
1378 %prun [options] statement
1378 %prun [options] statement
1379
1379
1380 The given statement (which doesn't require quote marks) is run via the
1380 The given statement (which doesn't require quote marks) is run via the
1381 python profiler in a manner similar to the profile.run() function.
1381 python profiler in a manner similar to the profile.run() function.
1382 Namespaces are internally managed to work correctly; profile.run
1382 Namespaces are internally managed to work correctly; profile.run
1383 cannot be used in IPython because it makes certain assumptions about
1383 cannot be used in IPython because it makes certain assumptions about
1384 namespaces which do not hold under IPython.
1384 namespaces which do not hold under IPython.
1385
1385
1386 Options:
1386 Options:
1387
1387
1388 -l <limit>: you can place restrictions on what or how much of the
1388 -l <limit>: you can place restrictions on what or how much of the
1389 profile gets printed. The limit value can be:
1389 profile gets printed. The limit value can be:
1390
1390
1391 * A string: only information for function names containing this string
1391 * A string: only information for function names containing this string
1392 is printed.
1392 is printed.
1393
1393
1394 * An integer: only these many lines are printed.
1394 * An integer: only these many lines are printed.
1395
1395
1396 * A float (between 0 and 1): this fraction of the report is printed
1396 * A float (between 0 and 1): this fraction of the report is printed
1397 (for example, use a limit of 0.4 to see the topmost 40% only).
1397 (for example, use a limit of 0.4 to see the topmost 40% only).
1398
1398
1399 You can combine several limits with repeated use of the option. For
1399 You can combine several limits with repeated use of the option. For
1400 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1401 information about class constructors.
1401 information about class constructors.
1402
1402
1403 -r: return the pstats.Stats object generated by the profiling. This
1403 -r: return the pstats.Stats object generated by the profiling. This
1404 object has all the information about the profile in it, and you can
1404 object has all the information about the profile in it, and you can
1405 later use it for further analysis or in other functions.
1405 later use it for further analysis or in other functions.
1406
1406
1407 -s <key>: sort profile by given key. You can provide more than one key
1407 -s <key>: sort profile by given key. You can provide more than one key
1408 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 by using the option several times: '-s key1 -s key2 -s key3...'. The
1409 default sorting key is 'time'.
1409 default sorting key is 'time'.
1410
1410
1411 The following is copied verbatim from the profile documentation
1411 The following is copied verbatim from the profile documentation
1412 referenced below:
1412 referenced below:
1413
1413
1414 When more than one key is provided, additional keys are used as
1414 When more than one key is provided, additional keys are used as
1415 secondary criteria when the there is equality in all keys selected
1415 secondary criteria when the there is equality in all keys selected
1416 before them.
1416 before them.
1417
1417
1418 Abbreviations can be used for any key names, as long as the
1418 Abbreviations can be used for any key names, as long as the
1419 abbreviation is unambiguous. The following are the keys currently
1419 abbreviation is unambiguous. The following are the keys currently
1420 defined:
1420 defined:
1421
1421
1422 Valid Arg Meaning
1422 Valid Arg Meaning
1423 "calls" call count
1423 "calls" call count
1424 "cumulative" cumulative time
1424 "cumulative" cumulative time
1425 "file" file name
1425 "file" file name
1426 "module" file name
1426 "module" file name
1427 "pcalls" primitive call count
1427 "pcalls" primitive call count
1428 "line" line number
1428 "line" line number
1429 "name" function name
1429 "name" function name
1430 "nfl" name/file/line
1430 "nfl" name/file/line
1431 "stdname" standard name
1431 "stdname" standard name
1432 "time" internal time
1432 "time" internal time
1433
1433
1434 Note that all sorts on statistics are in descending order (placing
1434 Note that all sorts on statistics are in descending order (placing
1435 most time consuming items first), where as name, file, and line number
1435 most time consuming items first), where as name, file, and line number
1436 searches are in ascending order (i.e., alphabetical). The subtle
1436 searches are in ascending order (i.e., alphabetical). The subtle
1437 distinction between "nfl" and "stdname" is that the standard name is a
1437 distinction between "nfl" and "stdname" is that the standard name is a
1438 sort of the name as printed, which means that the embedded line
1438 sort of the name as printed, which means that the embedded line
1439 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 numbers get compared in an odd way. For example, lines 3, 20, and 40
1440 would (if the file names were the same) appear in the string order
1440 would (if the file names were the same) appear in the string order
1441 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1442 line numbers. In fact, sort_stats("nfl") is the same as
1442 line numbers. In fact, sort_stats("nfl") is the same as
1443 sort_stats("name", "file", "line").
1443 sort_stats("name", "file", "line").
1444
1444
1445 -T <filename>: save profile results as shown on screen to a text
1445 -T <filename>: save profile results as shown on screen to a text
1446 file. The profile is still shown on screen.
1446 file. The profile is still shown on screen.
1447
1447
1448 -D <filename>: save (via dump_stats) profile statistics to given
1448 -D <filename>: save (via dump_stats) profile statistics to given
1449 filename. This data is in a format understod by the pstats module, and
1449 filename. This data is in a format understod by the pstats module, and
1450 is generated by a call to the dump_stats() method of profile
1450 is generated by a call to the dump_stats() method of profile
1451 objects. The profile is still shown on screen.
1451 objects. The profile is still shown on screen.
1452
1452
1453 If you want to run complete programs under the profiler's control, use
1453 If you want to run complete programs under the profiler's control, use
1454 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1455 contains profiler specific options as described here.
1455 contains profiler specific options as described here.
1456
1456
1457 You can read the complete documentation for the profile module with::
1457 You can read the complete documentation for the profile module with::
1458
1458
1459 In [1]: import profile; profile.help()
1459 In [1]: import profile; profile.help()
1460 """
1460 """
1461
1461
1462 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1463 # protect user quote marks
1463 # protect user quote marks
1464 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1465
1465
1466 if user_mode: # regular user call
1466 if user_mode: # regular user call
1467 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1468 list_all=1)
1468 list_all=1)
1469 namespace = self.shell.user_ns
1469 namespace = self.shell.user_ns
1470 else: # called to run a program by %run -p
1470 else: # called to run a program by %run -p
1471 try:
1471 try:
1472 filename = get_py_filename(arg_lst[0])
1472 filename = get_py_filename(arg_lst[0])
1473 except IOError,msg:
1473 except IOError,msg:
1474 error(msg)
1474 error(msg)
1475 return
1475 return
1476
1476
1477 arg_str = 'execfile(filename,prog_ns)'
1477 arg_str = 'execfile(filename,prog_ns)'
1478 namespace = locals()
1478 namespace = locals()
1479
1479
1480 opts.merge(opts_def)
1480 opts.merge(opts_def)
1481
1481
1482 prof = profile.Profile()
1482 prof = profile.Profile()
1483 try:
1483 try:
1484 prof = prof.runctx(arg_str,namespace,namespace)
1484 prof = prof.runctx(arg_str,namespace,namespace)
1485 sys_exit = ''
1485 sys_exit = ''
1486 except SystemExit:
1486 except SystemExit:
1487 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487 sys_exit = """*** SystemExit exception caught in code being profiled."""
1488
1488
1489 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1490
1490
1491 lims = opts.l
1491 lims = opts.l
1492 if lims:
1492 if lims:
1493 lims = [] # rebuild lims with ints/floats/strings
1493 lims = [] # rebuild lims with ints/floats/strings
1494 for lim in opts.l:
1494 for lim in opts.l:
1495 try:
1495 try:
1496 lims.append(int(lim))
1496 lims.append(int(lim))
1497 except ValueError:
1497 except ValueError:
1498 try:
1498 try:
1499 lims.append(float(lim))
1499 lims.append(float(lim))
1500 except ValueError:
1500 except ValueError:
1501 lims.append(lim)
1501 lims.append(lim)
1502
1502
1503 # Trap output.
1503 # Trap output.
1504 stdout_trap = StringIO()
1504 stdout_trap = StringIO()
1505
1505
1506 if hasattr(stats,'stream'):
1506 if hasattr(stats,'stream'):
1507 # In newer versions of python, the stats object has a 'stream'
1507 # In newer versions of python, the stats object has a 'stream'
1508 # attribute to write into.
1508 # attribute to write into.
1509 stats.stream = stdout_trap
1509 stats.stream = stdout_trap
1510 stats.print_stats(*lims)
1510 stats.print_stats(*lims)
1511 else:
1511 else:
1512 # For older versions, we manually redirect stdout during printing
1512 # For older versions, we manually redirect stdout during printing
1513 sys_stdout = sys.stdout
1513 sys_stdout = sys.stdout
1514 try:
1514 try:
1515 sys.stdout = stdout_trap
1515 sys.stdout = stdout_trap
1516 stats.print_stats(*lims)
1516 stats.print_stats(*lims)
1517 finally:
1517 finally:
1518 sys.stdout = sys_stdout
1518 sys.stdout = sys_stdout
1519
1519
1520 output = stdout_trap.getvalue()
1520 output = stdout_trap.getvalue()
1521 output = output.rstrip()
1521 output = output.rstrip()
1522
1522
1523 page(output,screen_lines=self.shell.usable_screen_length)
1523 page(output,screen_lines=self.shell.usable_screen_length)
1524 print sys_exit,
1524 print sys_exit,
1525
1525
1526 dump_file = opts.D[0]
1526 dump_file = opts.D[0]
1527 text_file = opts.T[0]
1527 text_file = opts.T[0]
1528 if dump_file:
1528 if dump_file:
1529 prof.dump_stats(dump_file)
1529 prof.dump_stats(dump_file)
1530 print '\n*** Profile stats marshalled to file',\
1530 print '\n*** Profile stats marshalled to file',\
1531 `dump_file`+'.',sys_exit
1531 `dump_file`+'.',sys_exit
1532 if text_file:
1532 if text_file:
1533 pfile = file(text_file,'w')
1533 pfile = file(text_file,'w')
1534 pfile.write(output)
1534 pfile.write(output)
1535 pfile.close()
1535 pfile.close()
1536 print '\n*** Profile printout saved to text file',\
1536 print '\n*** Profile printout saved to text file',\
1537 `text_file`+'.',sys_exit
1537 `text_file`+'.',sys_exit
1538
1538
1539 if opts.has_key('r'):
1539 if opts.has_key('r'):
1540 return stats
1540 return stats
1541 else:
1541 else:
1542 return None
1542 return None
1543
1543
1544 @testdec.skip_doctest
1544 @testdec.skip_doctest
1545 def magic_run(self, parameter_s ='',runner=None,
1545 def magic_run(self, parameter_s ='',runner=None,
1546 file_finder=get_py_filename):
1546 file_finder=get_py_filename):
1547 """Run the named file inside IPython as a program.
1547 """Run the named file inside IPython as a program.
1548
1548
1549 Usage:\\
1549 Usage:\\
1550 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1551
1551
1552 Parameters after the filename are passed as command-line arguments to
1552 Parameters after the filename are passed as command-line arguments to
1553 the program (put in sys.argv). Then, control returns to IPython's
1553 the program (put in sys.argv). Then, control returns to IPython's
1554 prompt.
1554 prompt.
1555
1555
1556 This is similar to running at a system prompt:\\
1556 This is similar to running at a system prompt:\\
1557 $ python file args\\
1557 $ python file args\\
1558 but with the advantage of giving you IPython's tracebacks, and of
1558 but with the advantage of giving you IPython's tracebacks, and of
1559 loading all variables into your interactive namespace for further use
1559 loading all variables into your interactive namespace for further use
1560 (unless -p is used, see below).
1560 (unless -p is used, see below).
1561
1561
1562 The file is executed in a namespace initially consisting only of
1562 The file is executed in a namespace initially consisting only of
1563 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 __name__=='__main__' and sys.argv constructed as indicated. It thus
1564 sees its environment as if it were being run as a stand-alone program
1564 sees its environment as if it were being run as a stand-alone program
1565 (except for sharing global objects such as previously imported
1565 (except for sharing global objects such as previously imported
1566 modules). But after execution, the IPython interactive namespace gets
1566 modules). But after execution, the IPython interactive namespace gets
1567 updated with all variables defined in the program (except for __name__
1567 updated with all variables defined in the program (except for __name__
1568 and sys.argv). This allows for very convenient loading of code for
1568 and sys.argv). This allows for very convenient loading of code for
1569 interactive work, while giving each program a 'clean sheet' to run in.
1569 interactive work, while giving each program a 'clean sheet' to run in.
1570
1570
1571 Options:
1571 Options:
1572
1572
1573 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 -n: __name__ is NOT set to '__main__', but to the running file's name
1574 without extension (as python does under import). This allows running
1574 without extension (as python does under import). This allows running
1575 scripts and reloading the definitions in them without calling code
1575 scripts and reloading the definitions in them without calling code
1576 protected by an ' if __name__ == "__main__" ' clause.
1576 protected by an ' if __name__ == "__main__" ' clause.
1577
1577
1578 -i: run the file in IPython's namespace instead of an empty one. This
1578 -i: run the file in IPython's namespace instead of an empty one. This
1579 is useful if you are experimenting with code written in a text editor
1579 is useful if you are experimenting with code written in a text editor
1580 which depends on variables defined interactively.
1580 which depends on variables defined interactively.
1581
1581
1582 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1583 being run. This is particularly useful if IPython is being used to
1583 being run. This is particularly useful if IPython is being used to
1584 run unittests, which always exit with a sys.exit() call. In such
1584 run unittests, which always exit with a sys.exit() call. In such
1585 cases you are interested in the output of the test results, not in
1585 cases you are interested in the output of the test results, not in
1586 seeing a traceback of the unittest module.
1586 seeing a traceback of the unittest module.
1587
1587
1588 -t: print timing information at the end of the run. IPython will give
1588 -t: print timing information at the end of the run. IPython will give
1589 you an estimated CPU time consumption for your script, which under
1589 you an estimated CPU time consumption for your script, which under
1590 Unix uses the resource module to avoid the wraparound problems of
1590 Unix uses the resource module to avoid the wraparound problems of
1591 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 time.clock(). Under Unix, an estimate of time spent on system tasks
1592 is also given (for Windows platforms this is reported as 0.0).
1592 is also given (for Windows platforms this is reported as 0.0).
1593
1593
1594 If -t is given, an additional -N<N> option can be given, where <N>
1594 If -t is given, an additional -N<N> option can be given, where <N>
1595 must be an integer indicating how many times you want the script to
1595 must be an integer indicating how many times you want the script to
1596 run. The final timing report will include total and per run results.
1596 run. The final timing report will include total and per run results.
1597
1597
1598 For example (testing the script uniq_stable.py):
1598 For example (testing the script uniq_stable.py):
1599
1599
1600 In [1]: run -t uniq_stable
1600 In [1]: run -t uniq_stable
1601
1601
1602 IPython CPU timings (estimated):\\
1602 IPython CPU timings (estimated):\\
1603 User : 0.19597 s.\\
1603 User : 0.19597 s.\\
1604 System: 0.0 s.\\
1604 System: 0.0 s.\\
1605
1605
1606 In [2]: run -t -N5 uniq_stable
1606 In [2]: run -t -N5 uniq_stable
1607
1607
1608 IPython CPU timings (estimated):\\
1608 IPython CPU timings (estimated):\\
1609 Total runs performed: 5\\
1609 Total runs performed: 5\\
1610 Times : Total Per run\\
1610 Times : Total Per run\\
1611 User : 0.910862 s, 0.1821724 s.\\
1611 User : 0.910862 s, 0.1821724 s.\\
1612 System: 0.0 s, 0.0 s.
1612 System: 0.0 s, 0.0 s.
1613
1613
1614 -d: run your program under the control of pdb, the Python debugger.
1614 -d: run your program under the control of pdb, the Python debugger.
1615 This allows you to execute your program step by step, watch variables,
1615 This allows you to execute your program step by step, watch variables,
1616 etc. Internally, what IPython does is similar to calling:
1616 etc. Internally, what IPython does is similar to calling:
1617
1617
1618 pdb.run('execfile("YOURFILENAME")')
1618 pdb.run('execfile("YOURFILENAME")')
1619
1619
1620 with a breakpoint set on line 1 of your file. You can change the line
1620 with a breakpoint set on line 1 of your file. You can change the line
1621 number for this automatic breakpoint to be <N> by using the -bN option
1621 number for this automatic breakpoint to be <N> by using the -bN option
1622 (where N must be an integer). For example:
1622 (where N must be an integer). For example:
1623
1623
1624 %run -d -b40 myscript
1624 %run -d -b40 myscript
1625
1625
1626 will set the first breakpoint at line 40 in myscript.py. Note that
1626 will set the first breakpoint at line 40 in myscript.py. Note that
1627 the first breakpoint must be set on a line which actually does
1627 the first breakpoint must be set on a line which actually does
1628 something (not a comment or docstring) for it to stop execution.
1628 something (not a comment or docstring) for it to stop execution.
1629
1629
1630 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1631 first enter 'c' (without qoutes) to start execution up to the first
1631 first enter 'c' (without qoutes) to start execution up to the first
1632 breakpoint.
1632 breakpoint.
1633
1633
1634 Entering 'help' gives information about the use of the debugger. You
1634 Entering 'help' gives information about the use of the debugger. You
1635 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 can easily see pdb's full documentation with "import pdb;pdb.help()"
1636 at a prompt.
1636 at a prompt.
1637
1637
1638 -p: run program under the control of the Python profiler module (which
1638 -p: run program under the control of the Python profiler module (which
1639 prints a detailed report of execution times, function calls, etc).
1639 prints a detailed report of execution times, function calls, etc).
1640
1640
1641 You can pass other options after -p which affect the behavior of the
1641 You can pass other options after -p which affect the behavior of the
1642 profiler itself. See the docs for %prun for details.
1642 profiler itself. See the docs for %prun for details.
1643
1643
1644 In this mode, the program's variables do NOT propagate back to the
1644 In this mode, the program's variables do NOT propagate back to the
1645 IPython interactive namespace (because they remain in the namespace
1645 IPython interactive namespace (because they remain in the namespace
1646 where the profiler executes them).
1646 where the profiler executes them).
1647
1647
1648 Internally this triggers a call to %prun, see its documentation for
1648 Internally this triggers a call to %prun, see its documentation for
1649 details on the options available specifically for profiling.
1649 details on the options available specifically for profiling.
1650
1650
1651 There is one special usage for which the text above doesn't apply:
1651 There is one special usage for which the text above doesn't apply:
1652 if the filename ends with .ipy, the file is run as ipython script,
1652 if the filename ends with .ipy, the file is run as ipython script,
1653 just as if the commands were written on IPython prompt.
1653 just as if the commands were written on IPython prompt.
1654 """
1654 """
1655
1655
1656 # get arguments and set sys.argv for program to be run.
1656 # get arguments and set sys.argv for program to be run.
1657 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1658 mode='list',list_all=1)
1658 mode='list',list_all=1)
1659
1659
1660 try:
1660 try:
1661 filename = file_finder(arg_lst[0])
1661 filename = file_finder(arg_lst[0])
1662 except IndexError:
1662 except IndexError:
1663 warn('you must provide at least a filename.')
1663 warn('you must provide at least a filename.')
1664 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1665 return
1665 return
1666 except IOError,msg:
1666 except IOError,msg:
1667 error(msg)
1667 error(msg)
1668 return
1668 return
1669
1669
1670 if filename.lower().endswith('.ipy'):
1670 if filename.lower().endswith('.ipy'):
1671 self.shell.safe_execfile_ipy(filename)
1671 self.shell.safe_execfile_ipy(filename)
1672 return
1672 return
1673
1673
1674 # Control the response to exit() calls made by the script being run
1674 # Control the response to exit() calls made by the script being run
1675 exit_ignore = opts.has_key('e')
1675 exit_ignore = opts.has_key('e')
1676
1676
1677 # Make sure that the running script gets a proper sys.argv as if it
1677 # Make sure that the running script gets a proper sys.argv as if it
1678 # were run from a system shell.
1678 # were run from a system shell.
1679 save_argv = sys.argv # save it for later restoring
1679 save_argv = sys.argv # save it for later restoring
1680 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1681
1681
1682 if opts.has_key('i'):
1682 if opts.has_key('i'):
1683 # Run in user's interactive namespace
1683 # Run in user's interactive namespace
1684 prog_ns = self.shell.user_ns
1684 prog_ns = self.shell.user_ns
1685 __name__save = self.shell.user_ns['__name__']
1685 __name__save = self.shell.user_ns['__name__']
1686 prog_ns['__name__'] = '__main__'
1686 prog_ns['__name__'] = '__main__'
1687 main_mod = self.shell.new_main_mod(prog_ns)
1687 main_mod = self.shell.new_main_mod(prog_ns)
1688 else:
1688 else:
1689 # Run in a fresh, empty namespace
1689 # Run in a fresh, empty namespace
1690 if opts.has_key('n'):
1690 if opts.has_key('n'):
1691 name = os.path.splitext(os.path.basename(filename))[0]
1691 name = os.path.splitext(os.path.basename(filename))[0]
1692 else:
1692 else:
1693 name = '__main__'
1693 name = '__main__'
1694
1694
1695 main_mod = self.shell.new_main_mod()
1695 main_mod = self.shell.new_main_mod()
1696 prog_ns = main_mod.__dict__
1696 prog_ns = main_mod.__dict__
1697 prog_ns['__name__'] = name
1697 prog_ns['__name__'] = name
1698
1698
1699 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1700 # set the __file__ global in the script's namespace
1700 # set the __file__ global in the script's namespace
1701 prog_ns['__file__'] = filename
1701 prog_ns['__file__'] = filename
1702
1702
1703 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1704 # that, if we overwrite __main__, we replace it at the end
1704 # that, if we overwrite __main__, we replace it at the end
1705 main_mod_name = prog_ns['__name__']
1705 main_mod_name = prog_ns['__name__']
1706
1706
1707 if main_mod_name == '__main__':
1707 if main_mod_name == '__main__':
1708 restore_main = sys.modules['__main__']
1708 restore_main = sys.modules['__main__']
1709 else:
1709 else:
1710 restore_main = False
1710 restore_main = False
1711
1711
1712 # This needs to be undone at the end to prevent holding references to
1712 # This needs to be undone at the end to prevent holding references to
1713 # every single object ever created.
1713 # every single object ever created.
1714 sys.modules[main_mod_name] = main_mod
1714 sys.modules[main_mod_name] = main_mod
1715
1715
1716 stats = None
1716 stats = None
1717 try:
1717 try:
1718 self.shell.savehist()
1718 self.shell.savehist()
1719
1719
1720 if opts.has_key('p'):
1720 if opts.has_key('p'):
1721 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1722 else:
1722 else:
1723 if opts.has_key('d'):
1723 if opts.has_key('d'):
1724 deb = debugger.Pdb(self.shell.colors)
1724 deb = debugger.Pdb(self.shell.colors)
1725 # reset Breakpoint state, which is moronically kept
1725 # reset Breakpoint state, which is moronically kept
1726 # in a class
1726 # in a class
1727 bdb.Breakpoint.next = 1
1727 bdb.Breakpoint.next = 1
1728 bdb.Breakpoint.bplist = {}
1728 bdb.Breakpoint.bplist = {}
1729 bdb.Breakpoint.bpbynumber = [None]
1729 bdb.Breakpoint.bpbynumber = [None]
1730 # Set an initial breakpoint to stop execution
1730 # Set an initial breakpoint to stop execution
1731 maxtries = 10
1731 maxtries = 10
1732 bp = int(opts.get('b',[1])[0])
1732 bp = int(opts.get('b',[1])[0])
1733 checkline = deb.checkline(filename,bp)
1733 checkline = deb.checkline(filename,bp)
1734 if not checkline:
1734 if not checkline:
1735 for bp in range(bp+1,bp+maxtries+1):
1735 for bp in range(bp+1,bp+maxtries+1):
1736 if deb.checkline(filename,bp):
1736 if deb.checkline(filename,bp):
1737 break
1737 break
1738 else:
1738 else:
1739 msg = ("\nI failed to find a valid line to set "
1739 msg = ("\nI failed to find a valid line to set "
1740 "a breakpoint\n"
1740 "a breakpoint\n"
1741 "after trying up to line: %s.\n"
1741 "after trying up to line: %s.\n"
1742 "Please set a valid breakpoint manually "
1742 "Please set a valid breakpoint manually "
1743 "with the -b option." % bp)
1743 "with the -b option." % bp)
1744 error(msg)
1744 error(msg)
1745 return
1745 return
1746 # if we find a good linenumber, set the breakpoint
1746 # if we find a good linenumber, set the breakpoint
1747 deb.do_break('%s:%s' % (filename,bp))
1747 deb.do_break('%s:%s' % (filename,bp))
1748 # Start file run
1748 # Start file run
1749 print "NOTE: Enter 'c' at the",
1749 print "NOTE: Enter 'c' at the",
1750 print "%s prompt to start your script." % deb.prompt
1750 print "%s prompt to start your script." % deb.prompt
1751 try:
1751 try:
1752 deb.run('execfile("%s")' % filename,prog_ns)
1752 deb.run('execfile("%s")' % filename,prog_ns)
1753
1753
1754 except:
1754 except:
1755 etype, value, tb = sys.exc_info()
1755 etype, value, tb = sys.exc_info()
1756 # Skip three frames in the traceback: the %run one,
1756 # Skip three frames in the traceback: the %run one,
1757 # one inside bdb.py, and the command-line typed by the
1757 # one inside bdb.py, and the command-line typed by the
1758 # user (run by exec in pdb itself).
1758 # user (run by exec in pdb itself).
1759 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1760 else:
1760 else:
1761 if runner is None:
1761 if runner is None:
1762 runner = self.shell.safe_execfile
1762 runner = self.shell.safe_execfile
1763 if opts.has_key('t'):
1763 if opts.has_key('t'):
1764 # timed execution
1764 # timed execution
1765 try:
1765 try:
1766 nruns = int(opts['N'][0])
1766 nruns = int(opts['N'][0])
1767 if nruns < 1:
1767 if nruns < 1:
1768 error('Number of runs must be >=1')
1768 error('Number of runs must be >=1')
1769 return
1769 return
1770 except (KeyError):
1770 except (KeyError):
1771 nruns = 1
1771 nruns = 1
1772 if nruns == 1:
1772 if nruns == 1:
1773 t0 = clock2()
1773 t0 = clock2()
1774 runner(filename,prog_ns,prog_ns,
1774 runner(filename,prog_ns,prog_ns,
1775 exit_ignore=exit_ignore)
1775 exit_ignore=exit_ignore)
1776 t1 = clock2()
1776 t1 = clock2()
1777 t_usr = t1[0]-t0[0]
1777 t_usr = t1[0]-t0[0]
1778 t_sys = t1[1]-t0[1]
1778 t_sys = t1[1]-t0[1]
1779 print "\nIPython CPU timings (estimated):"
1779 print "\nIPython CPU timings (estimated):"
1780 print " User : %10s s." % t_usr
1780 print " User : %10s s." % t_usr
1781 print " System: %10s s." % t_sys
1781 print " System: %10s s." % t_sys
1782 else:
1782 else:
1783 runs = range(nruns)
1783 runs = range(nruns)
1784 t0 = clock2()
1784 t0 = clock2()
1785 for nr in runs:
1785 for nr in runs:
1786 runner(filename,prog_ns,prog_ns,
1786 runner(filename,prog_ns,prog_ns,
1787 exit_ignore=exit_ignore)
1787 exit_ignore=exit_ignore)
1788 t1 = clock2()
1788 t1 = clock2()
1789 t_usr = t1[0]-t0[0]
1789 t_usr = t1[0]-t0[0]
1790 t_sys = t1[1]-t0[1]
1790 t_sys = t1[1]-t0[1]
1791 print "\nIPython CPU timings (estimated):"
1791 print "\nIPython CPU timings (estimated):"
1792 print "Total runs performed:",nruns
1792 print "Total runs performed:",nruns
1793 print " Times : %10s %10s" % ('Total','Per run')
1793 print " Times : %10s %10s" % ('Total','Per run')
1794 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1795 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1796
1796
1797 else:
1797 else:
1798 # regular execution
1798 # regular execution
1799 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1800
1800
1801 if opts.has_key('i'):
1801 if opts.has_key('i'):
1802 self.shell.user_ns['__name__'] = __name__save
1802 self.shell.user_ns['__name__'] = __name__save
1803 else:
1803 else:
1804 # The shell MUST hold a reference to prog_ns so after %run
1804 # The shell MUST hold a reference to prog_ns so after %run
1805 # exits, the python deletion mechanism doesn't zero it out
1805 # exits, the python deletion mechanism doesn't zero it out
1806 # (leaving dangling references).
1806 # (leaving dangling references).
1807 self.shell.cache_main_mod(prog_ns,filename)
1807 self.shell.cache_main_mod(prog_ns,filename)
1808 # update IPython interactive namespace
1808 # update IPython interactive namespace
1809
1809
1810 # Some forms of read errors on the file may mean the
1810 # Some forms of read errors on the file may mean the
1811 # __name__ key was never set; using pop we don't have to
1811 # __name__ key was never set; using pop we don't have to
1812 # worry about a possible KeyError.
1812 # worry about a possible KeyError.
1813 prog_ns.pop('__name__', None)
1813 prog_ns.pop('__name__', None)
1814
1814
1815 self.shell.user_ns.update(prog_ns)
1815 self.shell.user_ns.update(prog_ns)
1816 finally:
1816 finally:
1817 # It's a bit of a mystery why, but __builtins__ can change from
1817 # It's a bit of a mystery why, but __builtins__ can change from
1818 # being a module to becoming a dict missing some key data after
1818 # being a module to becoming a dict missing some key data after
1819 # %run. As best I can see, this is NOT something IPython is doing
1819 # %run. As best I can see, this is NOT something IPython is doing
1820 # at all, and similar problems have been reported before:
1820 # at all, and similar problems have been reported before:
1821 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1822 # Since this seems to be done by the interpreter itself, the best
1822 # Since this seems to be done by the interpreter itself, the best
1823 # we can do is to at least restore __builtins__ for the user on
1823 # we can do is to at least restore __builtins__ for the user on
1824 # exit.
1824 # exit.
1825 self.shell.user_ns['__builtins__'] = __builtin__
1825 self.shell.user_ns['__builtins__'] = __builtin__
1826
1826
1827 # Ensure key global structures are restored
1827 # Ensure key global structures are restored
1828 sys.argv = save_argv
1828 sys.argv = save_argv
1829 if restore_main:
1829 if restore_main:
1830 sys.modules['__main__'] = restore_main
1830 sys.modules['__main__'] = restore_main
1831 else:
1831 else:
1832 # Remove from sys.modules the reference to main_mod we'd
1832 # Remove from sys.modules the reference to main_mod we'd
1833 # added. Otherwise it will trap references to objects
1833 # added. Otherwise it will trap references to objects
1834 # contained therein.
1834 # contained therein.
1835 del sys.modules[main_mod_name]
1835 del sys.modules[main_mod_name]
1836
1836
1837 self.shell.reloadhist()
1837 self.shell.reloadhist()
1838
1838
1839 return stats
1839 return stats
1840
1840
1841 @testdec.skip_doctest
1841 @testdec.skip_doctest
1842 def magic_timeit(self, parameter_s =''):
1842 def magic_timeit(self, parameter_s =''):
1843 """Time execution of a Python statement or expression
1843 """Time execution of a Python statement or expression
1844
1844
1845 Usage:\\
1845 Usage:\\
1846 %timeit [-n<N> -r<R> [-t|-c]] statement
1846 %timeit [-n<N> -r<R> [-t|-c]] statement
1847
1847
1848 Time execution of a Python statement or expression using the timeit
1848 Time execution of a Python statement or expression using the timeit
1849 module.
1849 module.
1850
1850
1851 Options:
1851 Options:
1852 -n<N>: execute the given statement <N> times in a loop. If this value
1852 -n<N>: execute the given statement <N> times in a loop. If this value
1853 is not given, a fitting value is chosen.
1853 is not given, a fitting value is chosen.
1854
1854
1855 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 -r<R>: repeat the loop iteration <R> times and take the best result.
1856 Default: 3
1856 Default: 3
1857
1857
1858 -t: use time.time to measure the time, which is the default on Unix.
1858 -t: use time.time to measure the time, which is the default on Unix.
1859 This function measures wall time.
1859 This function measures wall time.
1860
1860
1861 -c: use time.clock to measure the time, which is the default on
1861 -c: use time.clock to measure the time, which is the default on
1862 Windows and measures wall time. On Unix, resource.getrusage is used
1862 Windows and measures wall time. On Unix, resource.getrusage is used
1863 instead and returns the CPU user time.
1863 instead and returns the CPU user time.
1864
1864
1865 -p<P>: use a precision of <P> digits to display the timing result.
1865 -p<P>: use a precision of <P> digits to display the timing result.
1866 Default: 3
1866 Default: 3
1867
1867
1868
1868
1869 Examples:
1869 Examples:
1870
1870
1871 In [1]: %timeit pass
1871 In [1]: %timeit pass
1872 10000000 loops, best of 3: 53.3 ns per loop
1872 10000000 loops, best of 3: 53.3 ns per loop
1873
1873
1874 In [2]: u = None
1874 In [2]: u = None
1875
1875
1876 In [3]: %timeit u is None
1876 In [3]: %timeit u is None
1877 10000000 loops, best of 3: 184 ns per loop
1877 10000000 loops, best of 3: 184 ns per loop
1878
1878
1879 In [4]: %timeit -r 4 u == None
1879 In [4]: %timeit -r 4 u == None
1880 1000000 loops, best of 4: 242 ns per loop
1880 1000000 loops, best of 4: 242 ns per loop
1881
1881
1882 In [5]: import time
1882 In [5]: import time
1883
1883
1884 In [6]: %timeit -n1 time.sleep(2)
1884 In [6]: %timeit -n1 time.sleep(2)
1885 1 loops, best of 3: 2 s per loop
1885 1 loops, best of 3: 2 s per loop
1886
1886
1887
1887
1888 The times reported by %timeit will be slightly higher than those
1888 The times reported by %timeit will be slightly higher than those
1889 reported by the timeit.py script when variables are accessed. This is
1889 reported by the timeit.py script when variables are accessed. This is
1890 due to the fact that %timeit executes the statement in the namespace
1890 due to the fact that %timeit executes the statement in the namespace
1891 of the shell, compared with timeit.py, which uses a single setup
1891 of the shell, compared with timeit.py, which uses a single setup
1892 statement to import function or create variables. Generally, the bias
1892 statement to import function or create variables. Generally, the bias
1893 does not matter as long as results from timeit.py are not mixed with
1893 does not matter as long as results from timeit.py are not mixed with
1894 those from %timeit."""
1894 those from %timeit."""
1895
1895
1896 import timeit
1896 import timeit
1897 import math
1897 import math
1898
1898
1899 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1900 # certain terminals. Until we figure out a robust way of
1900 # certain terminals. Until we figure out a robust way of
1901 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 # auto-detecting if the terminal can deal with it, use plain 'us' for
1902 # microseconds. I am really NOT happy about disabling the proper
1902 # microseconds. I am really NOT happy about disabling the proper
1903 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 # 'micro' prefix, but crashing is worse... If anyone knows what the
1904 # right solution for this is, I'm all ears...
1904 # right solution for this is, I'm all ears...
1905 #
1905 #
1906 # Note: using
1906 # Note: using
1907 #
1907 #
1908 # s = u'\xb5'
1908 # s = u'\xb5'
1909 # s.encode(sys.getdefaultencoding())
1909 # s.encode(sys.getdefaultencoding())
1910 #
1910 #
1911 # is not sufficient, as I've seen terminals where that fails but
1911 # is not sufficient, as I've seen terminals where that fails but
1912 # print s
1912 # print s
1913 #
1913 #
1914 # succeeds
1914 # succeeds
1915 #
1915 #
1916 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1917
1917
1918 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 #units = [u"s", u"ms",u'\xb5',"ns"]
1919 units = [u"s", u"ms",u'us',"ns"]
1919 units = [u"s", u"ms",u'us',"ns"]
1920
1920
1921 scaling = [1, 1e3, 1e6, 1e9]
1921 scaling = [1, 1e3, 1e6, 1e9]
1922
1922
1923 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1924 posix=False)
1924 posix=False)
1925 if stmt == "":
1925 if stmt == "":
1926 return
1926 return
1927 timefunc = timeit.default_timer
1927 timefunc = timeit.default_timer
1928 number = int(getattr(opts, "n", 0))
1928 number = int(getattr(opts, "n", 0))
1929 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 repeat = int(getattr(opts, "r", timeit.default_repeat))
1930 precision = int(getattr(opts, "p", 3))
1930 precision = int(getattr(opts, "p", 3))
1931 if hasattr(opts, "t"):
1931 if hasattr(opts, "t"):
1932 timefunc = time.time
1932 timefunc = time.time
1933 if hasattr(opts, "c"):
1933 if hasattr(opts, "c"):
1934 timefunc = clock
1934 timefunc = clock
1935
1935
1936 timer = timeit.Timer(timer=timefunc)
1936 timer = timeit.Timer(timer=timefunc)
1937 # this code has tight coupling to the inner workings of timeit.Timer,
1937 # this code has tight coupling to the inner workings of timeit.Timer,
1938 # but is there a better way to achieve that the code stmt has access
1938 # but is there a better way to achieve that the code stmt has access
1939 # to the shell namespace?
1939 # to the shell namespace?
1940
1940
1941 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1942 'setup': "pass"}
1942 'setup': "pass"}
1943 # Track compilation time so it can be reported if too long
1943 # Track compilation time so it can be reported if too long
1944 # Minimum time above which compilation time will be reported
1944 # Minimum time above which compilation time will be reported
1945 tc_min = 0.1
1945 tc_min = 0.1
1946
1946
1947 t0 = clock()
1947 t0 = clock()
1948 code = compile(src, "<magic-timeit>", "exec")
1948 code = compile(src, "<magic-timeit>", "exec")
1949 tc = clock()-t0
1949 tc = clock()-t0
1950
1950
1951 ns = {}
1951 ns = {}
1952 exec code in self.shell.user_ns, ns
1952 exec code in self.shell.user_ns, ns
1953 timer.inner = ns["inner"]
1953 timer.inner = ns["inner"]
1954
1954
1955 if number == 0:
1955 if number == 0:
1956 # determine number so that 0.2 <= total time < 2.0
1956 # determine number so that 0.2 <= total time < 2.0
1957 number = 1
1957 number = 1
1958 for i in range(1, 10):
1958 for i in range(1, 10):
1959 if timer.timeit(number) >= 0.2:
1959 if timer.timeit(number) >= 0.2:
1960 break
1960 break
1961 number *= 10
1961 number *= 10
1962
1962
1963 best = min(timer.repeat(repeat, number)) / number
1963 best = min(timer.repeat(repeat, number)) / number
1964
1964
1965 if best > 0.0 and best < 1000.0:
1965 if best > 0.0 and best < 1000.0:
1966 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1967 elif best >= 1000.0:
1967 elif best >= 1000.0:
1968 order = 0
1968 order = 0
1969 else:
1969 else:
1970 order = 3
1970 order = 3
1971 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1972 precision,
1972 precision,
1973 best * scaling[order],
1973 best * scaling[order],
1974 units[order])
1974 units[order])
1975 if tc > tc_min:
1975 if tc > tc_min:
1976 print "Compiler time: %.2f s" % tc
1976 print "Compiler time: %.2f s" % tc
1977
1977
1978 @testdec.skip_doctest
1978 @testdec.skip_doctest
1979 def magic_time(self,parameter_s = ''):
1979 def magic_time(self,parameter_s = ''):
1980 """Time execution of a Python statement or expression.
1980 """Time execution of a Python statement or expression.
1981
1981
1982 The CPU and wall clock times are printed, and the value of the
1982 The CPU and wall clock times are printed, and the value of the
1983 expression (if any) is returned. Note that under Win32, system time
1983 expression (if any) is returned. Note that under Win32, system time
1984 is always reported as 0, since it can not be measured.
1984 is always reported as 0, since it can not be measured.
1985
1985
1986 This function provides very basic timing functionality. In Python
1986 This function provides very basic timing functionality. In Python
1987 2.3, the timeit module offers more control and sophistication, so this
1987 2.3, the timeit module offers more control and sophistication, so this
1988 could be rewritten to use it (patches welcome).
1988 could be rewritten to use it (patches welcome).
1989
1989
1990 Some examples:
1990 Some examples:
1991
1991
1992 In [1]: time 2**128
1992 In [1]: time 2**128
1993 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1994 Wall time: 0.00
1994 Wall time: 0.00
1995 Out[1]: 340282366920938463463374607431768211456L
1995 Out[1]: 340282366920938463463374607431768211456L
1996
1996
1997 In [2]: n = 1000000
1997 In [2]: n = 1000000
1998
1998
1999 In [3]: time sum(range(n))
1999 In [3]: time sum(range(n))
2000 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2001 Wall time: 1.37
2001 Wall time: 1.37
2002 Out[3]: 499999500000L
2002 Out[3]: 499999500000L
2003
2003
2004 In [4]: time print 'hello world'
2004 In [4]: time print 'hello world'
2005 hello world
2005 hello world
2006 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2007 Wall time: 0.00
2007 Wall time: 0.00
2008
2008
2009 Note that the time needed by Python to compile the given expression
2009 Note that the time needed by Python to compile the given expression
2010 will be reported if it is more than 0.1s. In this example, the
2010 will be reported if it is more than 0.1s. In this example, the
2011 actual exponentiation is done by Python at compilation time, so while
2011 actual exponentiation is done by Python at compilation time, so while
2012 the expression can take a noticeable amount of time to compute, that
2012 the expression can take a noticeable amount of time to compute, that
2013 time is purely due to the compilation:
2013 time is purely due to the compilation:
2014
2014
2015 In [5]: time 3**9999;
2015 In [5]: time 3**9999;
2016 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2017 Wall time: 0.00 s
2017 Wall time: 0.00 s
2018
2018
2019 In [6]: time 3**999999;
2019 In [6]: time 3**999999;
2020 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2021 Wall time: 0.00 s
2021 Wall time: 0.00 s
2022 Compiler : 0.78 s
2022 Compiler : 0.78 s
2023 """
2023 """
2024
2024
2025 # fail immediately if the given expression can't be compiled
2025 # fail immediately if the given expression can't be compiled
2026
2026
2027 expr = self.shell.prefilter(parameter_s,False)
2027 expr = self.shell.prefilter(parameter_s,False)
2028
2028
2029 # Minimum time above which compilation time will be reported
2029 # Minimum time above which compilation time will be reported
2030 tc_min = 0.1
2030 tc_min = 0.1
2031
2031
2032 try:
2032 try:
2033 mode = 'eval'
2033 mode = 'eval'
2034 t0 = clock()
2034 t0 = clock()
2035 code = compile(expr,'<timed eval>',mode)
2035 code = compile(expr,'<timed eval>',mode)
2036 tc = clock()-t0
2036 tc = clock()-t0
2037 except SyntaxError:
2037 except SyntaxError:
2038 mode = 'exec'
2038 mode = 'exec'
2039 t0 = clock()
2039 t0 = clock()
2040 code = compile(expr,'<timed exec>',mode)
2040 code = compile(expr,'<timed exec>',mode)
2041 tc = clock()-t0
2041 tc = clock()-t0
2042 # skew measurement as little as possible
2042 # skew measurement as little as possible
2043 glob = self.shell.user_ns
2043 glob = self.shell.user_ns
2044 clk = clock2
2044 clk = clock2
2045 wtime = time.time
2045 wtime = time.time
2046 # time execution
2046 # time execution
2047 wall_st = wtime()
2047 wall_st = wtime()
2048 if mode=='eval':
2048 if mode=='eval':
2049 st = clk()
2049 st = clk()
2050 out = eval(code,glob)
2050 out = eval(code,glob)
2051 end = clk()
2051 end = clk()
2052 else:
2052 else:
2053 st = clk()
2053 st = clk()
2054 exec code in glob
2054 exec code in glob
2055 end = clk()
2055 end = clk()
2056 out = None
2056 out = None
2057 wall_end = wtime()
2057 wall_end = wtime()
2058 # Compute actual times and report
2058 # Compute actual times and report
2059 wall_time = wall_end-wall_st
2059 wall_time = wall_end-wall_st
2060 cpu_user = end[0]-st[0]
2060 cpu_user = end[0]-st[0]
2061 cpu_sys = end[1]-st[1]
2061 cpu_sys = end[1]-st[1]
2062 cpu_tot = cpu_user+cpu_sys
2062 cpu_tot = cpu_user+cpu_sys
2063 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2064 (cpu_user,cpu_sys,cpu_tot)
2064 (cpu_user,cpu_sys,cpu_tot)
2065 print "Wall time: %.2f s" % wall_time
2065 print "Wall time: %.2f s" % wall_time
2066 if tc > tc_min:
2066 if tc > tc_min:
2067 print "Compiler : %.2f s" % tc
2067 print "Compiler : %.2f s" % tc
2068 return out
2068 return out
2069
2069
2070 @testdec.skip_doctest
2070 @testdec.skip_doctest
2071 def magic_macro(self,parameter_s = ''):
2071 def magic_macro(self,parameter_s = ''):
2072 """Define a set of input lines as a macro for future re-execution.
2072 """Define a set of input lines as a macro for future re-execution.
2073
2073
2074 Usage:\\
2074 Usage:\\
2075 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2076
2076
2077 Options:
2077 Options:
2078
2078
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2080 so that magics are loaded in their transformed version to valid
2080 so that magics are loaded in their transformed version to valid
2081 Python. If this option is given, the raw input as typed as the
2081 Python. If this option is given, the raw input as typed as the
2082 command line is used instead.
2082 command line is used instead.
2083
2083
2084 This will define a global variable called `name` which is a string
2084 This will define a global variable called `name` which is a string
2085 made of joining the slices and lines you specify (n1,n2,... numbers
2085 made of joining the slices and lines you specify (n1,n2,... numbers
2086 above) from your input history into a single string. This variable
2086 above) from your input history into a single string. This variable
2087 acts like an automatic function which re-executes those lines as if
2087 acts like an automatic function which re-executes those lines as if
2088 you had typed them. You just type 'name' at the prompt and the code
2088 you had typed them. You just type 'name' at the prompt and the code
2089 executes.
2089 executes.
2090
2090
2091 The notation for indicating number ranges is: n1-n2 means 'use line
2091 The notation for indicating number ranges is: n1-n2 means 'use line
2092 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2093 using the lines numbered 5,6 and 7.
2093 using the lines numbered 5,6 and 7.
2094
2094
2095 Note: as a 'hidden' feature, you can also use traditional python slice
2095 Note: as a 'hidden' feature, you can also use traditional python slice
2096 notation, where N:M means numbers N through M-1.
2096 notation, where N:M means numbers N through M-1.
2097
2097
2098 For example, if your history contains (%hist prints it):
2098 For example, if your history contains (%hist prints it):
2099
2099
2100 44: x=1
2100 44: x=1
2101 45: y=3
2101 45: y=3
2102 46: z=x+y
2102 46: z=x+y
2103 47: print x
2103 47: print x
2104 48: a=5
2104 48: a=5
2105 49: print 'x',x,'y',y
2105 49: print 'x',x,'y',y
2106
2106
2107 you can create a macro with lines 44 through 47 (included) and line 49
2107 you can create a macro with lines 44 through 47 (included) and line 49
2108 called my_macro with:
2108 called my_macro with:
2109
2109
2110 In [55]: %macro my_macro 44-47 49
2110 In [55]: %macro my_macro 44-47 49
2111
2111
2112 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 Now, typing `my_macro` (without quotes) will re-execute all this code
2113 in one pass.
2113 in one pass.
2114
2114
2115 You don't need to give the line-numbers in order, and any given line
2115 You don't need to give the line-numbers in order, and any given line
2116 number can appear multiple times. You can assemble macros with any
2116 number can appear multiple times. You can assemble macros with any
2117 lines from your input history in any order.
2117 lines from your input history in any order.
2118
2118
2119 The macro is a simple object which holds its value in an attribute,
2119 The macro is a simple object which holds its value in an attribute,
2120 but IPython's display system checks for macros and executes them as
2120 but IPython's display system checks for macros and executes them as
2121 code instead of printing them when you type their name.
2121 code instead of printing them when you type their name.
2122
2122
2123 You can view a macro's contents by explicitly printing it with:
2123 You can view a macro's contents by explicitly printing it with:
2124
2124
2125 'print macro_name'.
2125 'print macro_name'.
2126
2126
2127 For one-off cases which DON'T contain magic function calls in them you
2127 For one-off cases which DON'T contain magic function calls in them you
2128 can obtain similar results by explicitly executing slices from your
2128 can obtain similar results by explicitly executing slices from your
2129 input history with:
2129 input history with:
2130
2130
2131 In [60]: exec In[44:48]+In[49]"""
2131 In [60]: exec In[44:48]+In[49]"""
2132
2132
2133 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 opts,args = self.parse_options(parameter_s,'r',mode='list')
2134 if not args:
2134 if not args:
2135 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2136 macs.sort()
2136 macs.sort()
2137 return macs
2137 return macs
2138 if len(args) == 1:
2138 if len(args) == 1:
2139 raise UsageError(
2139 raise UsageError(
2140 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2141 name,ranges = args[0], args[1:]
2141 name,ranges = args[0], args[1:]
2142
2142
2143 #print 'rng',ranges # dbg
2143 #print 'rng',ranges # dbg
2144 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2145 macro = Macro(lines)
2145 macro = Macro(lines)
2146 self.shell.define_macro(name, macro)
2146 self.shell.define_macro(name, macro)
2147 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2148 print 'Macro contents:'
2148 print 'Macro contents:'
2149 print macro,
2149 print macro,
2150
2150
2151 def magic_save(self,parameter_s = ''):
2151 def magic_save(self,parameter_s = ''):
2152 """Save a set of lines to a given filename.
2152 """Save a set of lines to a given filename.
2153
2153
2154 Usage:\\
2154 Usage:\\
2155 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2156
2156
2157 Options:
2157 Options:
2158
2158
2159 -r: use 'raw' input. By default, the 'processed' history is used,
2159 -r: use 'raw' input. By default, the 'processed' history is used,
2160 so that magics are loaded in their transformed version to valid
2160 so that magics are loaded in their transformed version to valid
2161 Python. If this option is given, the raw input as typed as the
2161 Python. If this option is given, the raw input as typed as the
2162 command line is used instead.
2162 command line is used instead.
2163
2163
2164 This function uses the same syntax as %macro for line extraction, but
2164 This function uses the same syntax as %macro for line extraction, but
2165 instead of creating a macro it saves the resulting string to the
2165 instead of creating a macro it saves the resulting string to the
2166 filename you specify.
2166 filename you specify.
2167
2167
2168 It adds a '.py' extension to the file if you don't do so yourself, and
2168 It adds a '.py' extension to the file if you don't do so yourself, and
2169 it asks for confirmation before overwriting existing files."""
2169 it asks for confirmation before overwriting existing files."""
2170
2170
2171 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 opts,args = self.parse_options(parameter_s,'r',mode='list')
2172 fname,ranges = args[0], args[1:]
2172 fname,ranges = args[0], args[1:]
2173 if not fname.endswith('.py'):
2173 if not fname.endswith('.py'):
2174 fname += '.py'
2174 fname += '.py'
2175 if os.path.isfile(fname):
2175 if os.path.isfile(fname):
2176 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2177 if ans.lower() not in ['y','yes']:
2177 if ans.lower() not in ['y','yes']:
2178 print 'Operation cancelled.'
2178 print 'Operation cancelled.'
2179 return
2179 return
2180 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2181 f = file(fname,'w')
2181 f = file(fname,'w')
2182 f.write(cmds)
2182 f.write(cmds)
2183 f.close()
2183 f.close()
2184 print 'The following commands were written to file `%s`:' % fname
2184 print 'The following commands were written to file `%s`:' % fname
2185 print cmds
2185 print cmds
2186
2186
2187 def _edit_macro(self,mname,macro):
2187 def _edit_macro(self,mname,macro):
2188 """open an editor with the macro data in a file"""
2188 """open an editor with the macro data in a file"""
2189 filename = self.shell.mktempfile(macro.value)
2189 filename = self.shell.mktempfile(macro.value)
2190 self.shell.hooks.editor(filename)
2190 self.shell.hooks.editor(filename)
2191
2191
2192 # and make a new macro object, to replace the old one
2192 # and make a new macro object, to replace the old one
2193 mfile = open(filename)
2193 mfile = open(filename)
2194 mvalue = mfile.read()
2194 mvalue = mfile.read()
2195 mfile.close()
2195 mfile.close()
2196 self.shell.user_ns[mname] = Macro(mvalue)
2196 self.shell.user_ns[mname] = Macro(mvalue)
2197
2197
2198 def magic_ed(self,parameter_s=''):
2198 def magic_ed(self,parameter_s=''):
2199 """Alias to %edit."""
2199 """Alias to %edit."""
2200 return self.magic_edit(parameter_s)
2200 return self.magic_edit(parameter_s)
2201
2201
2202 @testdec.skip_doctest
2202 @testdec.skip_doctest
2203 def magic_edit(self,parameter_s='',last_call=['','']):
2203 def magic_edit(self,parameter_s='',last_call=['','']):
2204 """Bring up an editor and execute the resulting code.
2204 """Bring up an editor and execute the resulting code.
2205
2205
2206 Usage:
2206 Usage:
2207 %edit [options] [args]
2207 %edit [options] [args]
2208
2208
2209 %edit runs IPython's editor hook. The default version of this hook is
2209 %edit runs IPython's editor hook. The default version of this hook is
2210 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 set to call the __IPYTHON__.rc.editor command. This is read from your
2211 environment variable $EDITOR. If this isn't found, it will default to
2211 environment variable $EDITOR. If this isn't found, it will default to
2212 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 vi under Linux/Unix and to notepad under Windows. See the end of this
2213 docstring for how to change the editor hook.
2213 docstring for how to change the editor hook.
2214
2214
2215 You can also set the value of this editor via the command line option
2215 You can also set the value of this editor via the command line option
2216 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 '-editor' or in your ipythonrc file. This is useful if you wish to use
2217 specifically for IPython an editor different from your typical default
2217 specifically for IPython an editor different from your typical default
2218 (and for Windows users who typically don't set environment variables).
2218 (and for Windows users who typically don't set environment variables).
2219
2219
2220 This command allows you to conveniently edit multi-line code right in
2220 This command allows you to conveniently edit multi-line code right in
2221 your IPython session.
2221 your IPython session.
2222
2222
2223 If called without arguments, %edit opens up an empty editor with a
2223 If called without arguments, %edit opens up an empty editor with a
2224 temporary file and will execute the contents of this file when you
2224 temporary file and will execute the contents of this file when you
2225 close it (don't forget to save it!).
2225 close it (don't forget to save it!).
2226
2226
2227
2227
2228 Options:
2228 Options:
2229
2229
2230 -n <number>: open the editor at a specified line number. By default,
2230 -n <number>: open the editor at a specified line number. By default,
2231 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 the IPython editor hook uses the unix syntax 'editor +N filename', but
2232 you can configure this by providing your own modified hook if your
2232 you can configure this by providing your own modified hook if your
2233 favorite editor supports line-number specifications with a different
2233 favorite editor supports line-number specifications with a different
2234 syntax.
2234 syntax.
2235
2235
2236 -p: this will call the editor with the same data as the previous time
2236 -p: this will call the editor with the same data as the previous time
2237 it was used, regardless of how long ago (in your current session) it
2237 it was used, regardless of how long ago (in your current session) it
2238 was.
2238 was.
2239
2239
2240 -r: use 'raw' input. This option only applies to input taken from the
2240 -r: use 'raw' input. This option only applies to input taken from the
2241 user's history. By default, the 'processed' history is used, so that
2241 user's history. By default, the 'processed' history is used, so that
2242 magics are loaded in their transformed version to valid Python. If
2242 magics are loaded in their transformed version to valid Python. If
2243 this option is given, the raw input as typed as the command line is
2243 this option is given, the raw input as typed as the command line is
2244 used instead. When you exit the editor, it will be executed by
2244 used instead. When you exit the editor, it will be executed by
2245 IPython's own processor.
2245 IPython's own processor.
2246
2246
2247 -x: do not execute the edited code immediately upon exit. This is
2247 -x: do not execute the edited code immediately upon exit. This is
2248 mainly useful if you are editing programs which need to be called with
2248 mainly useful if you are editing programs which need to be called with
2249 command line arguments, which you can then do using %run.
2249 command line arguments, which you can then do using %run.
2250
2250
2251
2251
2252 Arguments:
2252 Arguments:
2253
2253
2254 If arguments are given, the following possibilites exist:
2254 If arguments are given, the following possibilites exist:
2255
2255
2256 - The arguments are numbers or pairs of colon-separated numbers (like
2256 - The arguments are numbers or pairs of colon-separated numbers (like
2257 1 4:8 9). These are interpreted as lines of previous input to be
2257 1 4:8 9). These are interpreted as lines of previous input to be
2258 loaded into the editor. The syntax is the same of the %macro command.
2258 loaded into the editor. The syntax is the same of the %macro command.
2259
2259
2260 - If the argument doesn't start with a number, it is evaluated as a
2260 - If the argument doesn't start with a number, it is evaluated as a
2261 variable and its contents loaded into the editor. You can thus edit
2261 variable and its contents loaded into the editor. You can thus edit
2262 any string which contains python code (including the result of
2262 any string which contains python code (including the result of
2263 previous edits).
2263 previous edits).
2264
2264
2265 - If the argument is the name of an object (other than a string),
2265 - If the argument is the name of an object (other than a string),
2266 IPython will try to locate the file where it was defined and open the
2266 IPython will try to locate the file where it was defined and open the
2267 editor at the point where it is defined. You can use `%edit function`
2267 editor at the point where it is defined. You can use `%edit function`
2268 to load an editor exactly at the point where 'function' is defined,
2268 to load an editor exactly at the point where 'function' is defined,
2269 edit it and have the file be executed automatically.
2269 edit it and have the file be executed automatically.
2270
2270
2271 If the object is a macro (see %macro for details), this opens up your
2271 If the object is a macro (see %macro for details), this opens up your
2272 specified editor with a temporary file containing the macro's data.
2272 specified editor with a temporary file containing the macro's data.
2273 Upon exit, the macro is reloaded with the contents of the file.
2273 Upon exit, the macro is reloaded with the contents of the file.
2274
2274
2275 Note: opening at an exact line is only supported under Unix, and some
2275 Note: opening at an exact line is only supported under Unix, and some
2276 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2277 '+NUMBER' parameter necessary for this feature. Good editors like
2277 '+NUMBER' parameter necessary for this feature. Good editors like
2278 (X)Emacs, vi, jed, pico and joe all do.
2278 (X)Emacs, vi, jed, pico and joe all do.
2279
2279
2280 - If the argument is not found as a variable, IPython will look for a
2280 - If the argument is not found as a variable, IPython will look for a
2281 file with that name (adding .py if necessary) and load it into the
2281 file with that name (adding .py if necessary) and load it into the
2282 editor. It will execute its contents with execfile() when you exit,
2282 editor. It will execute its contents with execfile() when you exit,
2283 loading any code in the file into your interactive namespace.
2283 loading any code in the file into your interactive namespace.
2284
2284
2285 After executing your code, %edit will return as output the code you
2285 After executing your code, %edit will return as output the code you
2286 typed in the editor (except when it was an existing file). This way
2286 typed in the editor (except when it was an existing file). This way
2287 you can reload the code in further invocations of %edit as a variable,
2287 you can reload the code in further invocations of %edit as a variable,
2288 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2289 the output.
2289 the output.
2290
2290
2291 Note that %edit is also available through the alias %ed.
2291 Note that %edit is also available through the alias %ed.
2292
2292
2293 This is an example of creating a simple function inside the editor and
2293 This is an example of creating a simple function inside the editor and
2294 then modifying it. First, start up the editor:
2294 then modifying it. First, start up the editor:
2295
2295
2296 In [1]: ed
2296 In [1]: ed
2297 Editing... done. Executing edited code...
2297 Editing... done. Executing edited code...
2298 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2299
2299
2300 We can then call the function foo():
2300 We can then call the function foo():
2301
2301
2302 In [2]: foo()
2302 In [2]: foo()
2303 foo() was defined in an editing session
2303 foo() was defined in an editing session
2304
2304
2305 Now we edit foo. IPython automatically loads the editor with the
2305 Now we edit foo. IPython automatically loads the editor with the
2306 (temporary) file where foo() was previously defined:
2306 (temporary) file where foo() was previously defined:
2307
2307
2308 In [3]: ed foo
2308 In [3]: ed foo
2309 Editing... done. Executing edited code...
2309 Editing... done. Executing edited code...
2310
2310
2311 And if we call foo() again we get the modified version:
2311 And if we call foo() again we get the modified version:
2312
2312
2313 In [4]: foo()
2313 In [4]: foo()
2314 foo() has now been changed!
2314 foo() has now been changed!
2315
2315
2316 Here is an example of how to edit a code snippet successive
2316 Here is an example of how to edit a code snippet successive
2317 times. First we call the editor:
2317 times. First we call the editor:
2318
2318
2319 In [5]: ed
2319 In [5]: ed
2320 Editing... done. Executing edited code...
2320 Editing... done. Executing edited code...
2321 hello
2321 hello
2322 Out[5]: "print 'hello'n"
2322 Out[5]: "print 'hello'n"
2323
2323
2324 Now we call it again with the previous output (stored in _):
2324 Now we call it again with the previous output (stored in _):
2325
2325
2326 In [6]: ed _
2326 In [6]: ed _
2327 Editing... done. Executing edited code...
2327 Editing... done. Executing edited code...
2328 hello world
2328 hello world
2329 Out[6]: "print 'hello world'n"
2329 Out[6]: "print 'hello world'n"
2330
2330
2331 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331 Now we call it with the output #8 (stored in _8, also as Out[8]):
2332
2332
2333 In [7]: ed _8
2333 In [7]: ed _8
2334 Editing... done. Executing edited code...
2334 Editing... done. Executing edited code...
2335 hello again
2335 hello again
2336 Out[7]: "print 'hello again'n"
2336 Out[7]: "print 'hello again'n"
2337
2337
2338
2338
2339 Changing the default editor hook:
2339 Changing the default editor hook:
2340
2340
2341 If you wish to write your own editor hook, you can put it in a
2341 If you wish to write your own editor hook, you can put it in a
2342 configuration file which you load at startup time. The default hook
2342 configuration file which you load at startup time. The default hook
2343 is defined in the IPython.core.hooks module, and you can use that as a
2343 is defined in the IPython.core.hooks module, and you can use that as a
2344 starting example for further modifications. That file also has
2344 starting example for further modifications. That file also has
2345 general instructions on how to set a new hook for use once you've
2345 general instructions on how to set a new hook for use once you've
2346 defined it."""
2346 defined it."""
2347
2347
2348 # FIXME: This function has become a convoluted mess. It needs a
2348 # FIXME: This function has become a convoluted mess. It needs a
2349 # ground-up rewrite with clean, simple logic.
2349 # ground-up rewrite with clean, simple logic.
2350
2350
2351 def make_filename(arg):
2351 def make_filename(arg):
2352 "Make a filename from the given args"
2352 "Make a filename from the given args"
2353 try:
2353 try:
2354 filename = get_py_filename(arg)
2354 filename = get_py_filename(arg)
2355 except IOError:
2355 except IOError:
2356 if args.endswith('.py'):
2356 if args.endswith('.py'):
2357 filename = arg
2357 filename = arg
2358 else:
2358 else:
2359 filename = None
2359 filename = None
2360 return filename
2360 return filename
2361
2361
2362 # custom exceptions
2362 # custom exceptions
2363 class DataIsObject(Exception): pass
2363 class DataIsObject(Exception): pass
2364
2364
2365 opts,args = self.parse_options(parameter_s,'prxn:')
2365 opts,args = self.parse_options(parameter_s,'prxn:')
2366 # Set a few locals from the options for convenience:
2366 # Set a few locals from the options for convenience:
2367 opts_p = opts.has_key('p')
2367 opts_p = opts.has_key('p')
2368 opts_r = opts.has_key('r')
2368 opts_r = opts.has_key('r')
2369
2369
2370 # Default line number value
2370 # Default line number value
2371 lineno = opts.get('n',None)
2371 lineno = opts.get('n',None)
2372
2372
2373 if opts_p:
2373 if opts_p:
2374 args = '_%s' % last_call[0]
2374 args = '_%s' % last_call[0]
2375 if not self.shell.user_ns.has_key(args):
2375 if not self.shell.user_ns.has_key(args):
2376 args = last_call[1]
2376 args = last_call[1]
2377
2377
2378 # use last_call to remember the state of the previous call, but don't
2378 # use last_call to remember the state of the previous call, but don't
2379 # let it be clobbered by successive '-p' calls.
2379 # let it be clobbered by successive '-p' calls.
2380 try:
2380 try:
2381 last_call[0] = self.shell.outputcache.prompt_count
2381 last_call[0] = self.shell.displayhook.prompt_count
2382 if not opts_p:
2382 if not opts_p:
2383 last_call[1] = parameter_s
2383 last_call[1] = parameter_s
2384 except:
2384 except:
2385 pass
2385 pass
2386
2386
2387 # by default this is done with temp files, except when the given
2387 # by default this is done with temp files, except when the given
2388 # arg is a filename
2388 # arg is a filename
2389 use_temp = 1
2389 use_temp = 1
2390
2390
2391 if re.match(r'\d',args):
2391 if re.match(r'\d',args):
2392 # Mode where user specifies ranges of lines, like in %macro.
2392 # Mode where user specifies ranges of lines, like in %macro.
2393 # This means that you can't edit files whose names begin with
2393 # This means that you can't edit files whose names begin with
2394 # numbers this way. Tough.
2394 # numbers this way. Tough.
2395 ranges = args.split()
2395 ranges = args.split()
2396 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 data = ''.join(self.extract_input_slices(ranges,opts_r))
2397 elif args.endswith('.py'):
2397 elif args.endswith('.py'):
2398 filename = make_filename(args)
2398 filename = make_filename(args)
2399 data = ''
2399 data = ''
2400 use_temp = 0
2400 use_temp = 0
2401 elif args:
2401 elif args:
2402 try:
2402 try:
2403 # Load the parameter given as a variable. If not a string,
2403 # Load the parameter given as a variable. If not a string,
2404 # process it as an object instead (below)
2404 # process it as an object instead (below)
2405
2405
2406 #print '*** args',args,'type',type(args) # dbg
2406 #print '*** args',args,'type',type(args) # dbg
2407 data = eval(args,self.shell.user_ns)
2407 data = eval(args,self.shell.user_ns)
2408 if not type(data) in StringTypes:
2408 if not type(data) in StringTypes:
2409 raise DataIsObject
2409 raise DataIsObject
2410
2410
2411 except (NameError,SyntaxError):
2411 except (NameError,SyntaxError):
2412 # given argument is not a variable, try as a filename
2412 # given argument is not a variable, try as a filename
2413 filename = make_filename(args)
2413 filename = make_filename(args)
2414 if filename is None:
2414 if filename is None:
2415 warn("Argument given (%s) can't be found as a variable "
2415 warn("Argument given (%s) can't be found as a variable "
2416 "or as a filename." % args)
2416 "or as a filename." % args)
2417 return
2417 return
2418
2418
2419 data = ''
2419 data = ''
2420 use_temp = 0
2420 use_temp = 0
2421 except DataIsObject:
2421 except DataIsObject:
2422
2422
2423 # macros have a special edit function
2423 # macros have a special edit function
2424 if isinstance(data,Macro):
2424 if isinstance(data,Macro):
2425 self._edit_macro(args,data)
2425 self._edit_macro(args,data)
2426 return
2426 return
2427
2427
2428 # For objects, try to edit the file where they are defined
2428 # For objects, try to edit the file where they are defined
2429 try:
2429 try:
2430 filename = inspect.getabsfile(data)
2430 filename = inspect.getabsfile(data)
2431 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2432 # class created by %edit? Try to find source
2432 # class created by %edit? Try to find source
2433 # by looking for method definitions instead, the
2433 # by looking for method definitions instead, the
2434 # __module__ in those classes is FakeModule.
2434 # __module__ in those classes is FakeModule.
2435 attrs = [getattr(data, aname) for aname in dir(data)]
2435 attrs = [getattr(data, aname) for aname in dir(data)]
2436 for attr in attrs:
2436 for attr in attrs:
2437 if not inspect.ismethod(attr):
2437 if not inspect.ismethod(attr):
2438 continue
2438 continue
2439 filename = inspect.getabsfile(attr)
2439 filename = inspect.getabsfile(attr)
2440 if filename and 'fakemodule' not in filename.lower():
2440 if filename and 'fakemodule' not in filename.lower():
2441 # change the attribute to be the edit target instead
2441 # change the attribute to be the edit target instead
2442 data = attr
2442 data = attr
2443 break
2443 break
2444
2444
2445 datafile = 1
2445 datafile = 1
2446 except TypeError:
2446 except TypeError:
2447 filename = make_filename(args)
2447 filename = make_filename(args)
2448 datafile = 1
2448 datafile = 1
2449 warn('Could not find file where `%s` is defined.\n'
2449 warn('Could not find file where `%s` is defined.\n'
2450 'Opening a file named `%s`' % (args,filename))
2450 'Opening a file named `%s`' % (args,filename))
2451 # Now, make sure we can actually read the source (if it was in
2451 # Now, make sure we can actually read the source (if it was in
2452 # a temp file it's gone by now).
2452 # a temp file it's gone by now).
2453 if datafile:
2453 if datafile:
2454 try:
2454 try:
2455 if lineno is None:
2455 if lineno is None:
2456 lineno = inspect.getsourcelines(data)[1]
2456 lineno = inspect.getsourcelines(data)[1]
2457 except IOError:
2457 except IOError:
2458 filename = make_filename(args)
2458 filename = make_filename(args)
2459 if filename is None:
2459 if filename is None:
2460 warn('The file `%s` where `%s` was defined cannot '
2460 warn('The file `%s` where `%s` was defined cannot '
2461 'be read.' % (filename,data))
2461 'be read.' % (filename,data))
2462 return
2462 return
2463 use_temp = 0
2463 use_temp = 0
2464 else:
2464 else:
2465 data = ''
2465 data = ''
2466
2466
2467 if use_temp:
2467 if use_temp:
2468 filename = self.shell.mktempfile(data)
2468 filename = self.shell.mktempfile(data)
2469 print 'IPython will make a temporary file named:',filename
2469 print 'IPython will make a temporary file named:',filename
2470
2470
2471 # do actual editing here
2471 # do actual editing here
2472 print 'Editing...',
2472 print 'Editing...',
2473 sys.stdout.flush()
2473 sys.stdout.flush()
2474 try:
2474 try:
2475 # Quote filenames that may have spaces in them
2475 # Quote filenames that may have spaces in them
2476 if ' ' in filename:
2476 if ' ' in filename:
2477 filename = "%s" % filename
2477 filename = "%s" % filename
2478 self.shell.hooks.editor(filename,lineno)
2478 self.shell.hooks.editor(filename,lineno)
2479 except TryNext:
2479 except TryNext:
2480 warn('Could not open editor')
2480 warn('Could not open editor')
2481 return
2481 return
2482
2482
2483 # XXX TODO: should this be generalized for all string vars?
2483 # XXX TODO: should this be generalized for all string vars?
2484 # For now, this is special-cased to blocks created by cpaste
2484 # For now, this is special-cased to blocks created by cpaste
2485 if args.strip() == 'pasted_block':
2485 if args.strip() == 'pasted_block':
2486 self.shell.user_ns['pasted_block'] = file_read(filename)
2486 self.shell.user_ns['pasted_block'] = file_read(filename)
2487
2487
2488 if opts.has_key('x'): # -x prevents actual execution
2488 if opts.has_key('x'): # -x prevents actual execution
2489 print
2489 print
2490 else:
2490 else:
2491 print 'done. Executing edited code...'
2491 print 'done. Executing edited code...'
2492 if opts_r:
2492 if opts_r:
2493 self.shell.runlines(file_read(filename))
2493 self.shell.runlines(file_read(filename))
2494 else:
2494 else:
2495 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 self.shell.safe_execfile(filename,self.shell.user_ns,
2496 self.shell.user_ns)
2496 self.shell.user_ns)
2497
2497
2498
2498
2499 if use_temp:
2499 if use_temp:
2500 try:
2500 try:
2501 return open(filename).read()
2501 return open(filename).read()
2502 except IOError,msg:
2502 except IOError,msg:
2503 if msg.filename == filename:
2503 if msg.filename == filename:
2504 warn('File not found. Did you forget to save?')
2504 warn('File not found. Did you forget to save?')
2505 return
2505 return
2506 else:
2506 else:
2507 self.shell.showtraceback()
2507 self.shell.showtraceback()
2508
2508
2509 def magic_xmode(self,parameter_s = ''):
2509 def magic_xmode(self,parameter_s = ''):
2510 """Switch modes for the exception handlers.
2510 """Switch modes for the exception handlers.
2511
2511
2512 Valid modes: Plain, Context and Verbose.
2512 Valid modes: Plain, Context and Verbose.
2513
2513
2514 If called without arguments, acts as a toggle."""
2514 If called without arguments, acts as a toggle."""
2515
2515
2516 def xmode_switch_err(name):
2516 def xmode_switch_err(name):
2517 warn('Error changing %s exception modes.\n%s' %
2517 warn('Error changing %s exception modes.\n%s' %
2518 (name,sys.exc_info()[1]))
2518 (name,sys.exc_info()[1]))
2519
2519
2520 shell = self.shell
2520 shell = self.shell
2521 new_mode = parameter_s.strip().capitalize()
2521 new_mode = parameter_s.strip().capitalize()
2522 try:
2522 try:
2523 shell.InteractiveTB.set_mode(mode=new_mode)
2523 shell.InteractiveTB.set_mode(mode=new_mode)
2524 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 print 'Exception reporting mode:',shell.InteractiveTB.mode
2525 except:
2525 except:
2526 xmode_switch_err('user')
2526 xmode_switch_err('user')
2527
2527
2528 def magic_colors(self,parameter_s = ''):
2528 def magic_colors(self,parameter_s = ''):
2529 """Switch color scheme for prompts, info system and exception handlers.
2529 """Switch color scheme for prompts, info system and exception handlers.
2530
2530
2531 Currently implemented schemes: NoColor, Linux, LightBG.
2531 Currently implemented schemes: NoColor, Linux, LightBG.
2532
2532
2533 Color scheme names are not case-sensitive."""
2533 Color scheme names are not case-sensitive."""
2534
2534
2535 def color_switch_err(name):
2535 def color_switch_err(name):
2536 warn('Error changing %s color schemes.\n%s' %
2536 warn('Error changing %s color schemes.\n%s' %
2537 (name,sys.exc_info()[1]))
2537 (name,sys.exc_info()[1]))
2538
2538
2539
2539
2540 new_scheme = parameter_s.strip()
2540 new_scheme = parameter_s.strip()
2541 if not new_scheme:
2541 if not new_scheme:
2542 raise UsageError(
2542 raise UsageError(
2543 "%colors: you must specify a color scheme. See '%colors?'")
2543 "%colors: you must specify a color scheme. See '%colors?'")
2544 return
2544 return
2545 # local shortcut
2545 # local shortcut
2546 shell = self.shell
2546 shell = self.shell
2547
2547
2548 import IPython.utils.rlineimpl as readline
2548 import IPython.utils.rlineimpl as readline
2549
2549
2550 if not readline.have_readline and sys.platform == "win32":
2550 if not readline.have_readline and sys.platform == "win32":
2551 msg = """\
2551 msg = """\
2552 Proper color support under MS Windows requires the pyreadline library.
2552 Proper color support under MS Windows requires the pyreadline library.
2553 You can find it at:
2553 You can find it at:
2554 http://ipython.scipy.org/moin/PyReadline/Intro
2554 http://ipython.scipy.org/moin/PyReadline/Intro
2555 Gary's readline needs the ctypes module, from:
2555 Gary's readline needs the ctypes module, from:
2556 http://starship.python.net/crew/theller/ctypes
2556 http://starship.python.net/crew/theller/ctypes
2557 (Note that ctypes is already part of Python versions 2.5 and newer).
2557 (Note that ctypes is already part of Python versions 2.5 and newer).
2558
2558
2559 Defaulting color scheme to 'NoColor'"""
2559 Defaulting color scheme to 'NoColor'"""
2560 new_scheme = 'NoColor'
2560 new_scheme = 'NoColor'
2561 warn(msg)
2561 warn(msg)
2562
2562
2563 # readline option is 0
2563 # readline option is 0
2564 if not shell.has_readline:
2564 if not shell.has_readline:
2565 new_scheme = 'NoColor'
2565 new_scheme = 'NoColor'
2566
2566
2567 # Set prompt colors
2567 # Set prompt colors
2568 try:
2568 try:
2569 shell.outputcache.set_colors(new_scheme)
2569 shell.displayhook.set_colors(new_scheme)
2570 except:
2570 except:
2571 color_switch_err('prompt')
2571 color_switch_err('prompt')
2572 else:
2572 else:
2573 shell.colors = \
2573 shell.colors = \
2574 shell.outputcache.color_table.active_scheme_name
2574 shell.displayhook.color_table.active_scheme_name
2575 # Set exception colors
2575 # Set exception colors
2576 try:
2576 try:
2577 shell.InteractiveTB.set_colors(scheme = new_scheme)
2577 shell.InteractiveTB.set_colors(scheme = new_scheme)
2578 shell.SyntaxTB.set_colors(scheme = new_scheme)
2578 shell.SyntaxTB.set_colors(scheme = new_scheme)
2579 except:
2579 except:
2580 color_switch_err('exception')
2580 color_switch_err('exception')
2581
2581
2582 # Set info (for 'object?') colors
2582 # Set info (for 'object?') colors
2583 if shell.color_info:
2583 if shell.color_info:
2584 try:
2584 try:
2585 shell.inspector.set_active_scheme(new_scheme)
2585 shell.inspector.set_active_scheme(new_scheme)
2586 except:
2586 except:
2587 color_switch_err('object inspector')
2587 color_switch_err('object inspector')
2588 else:
2588 else:
2589 shell.inspector.set_active_scheme('NoColor')
2589 shell.inspector.set_active_scheme('NoColor')
2590
2590
2591 def magic_color_info(self,parameter_s = ''):
2591 def magic_color_info(self,parameter_s = ''):
2592 """Toggle color_info.
2592 """Toggle color_info.
2593
2593
2594 The color_info configuration parameter controls whether colors are
2594 The color_info configuration parameter controls whether colors are
2595 used for displaying object details (by things like %psource, %pfile or
2595 used for displaying object details (by things like %psource, %pfile or
2596 the '?' system). This function toggles this value with each call.
2596 the '?' system). This function toggles this value with each call.
2597
2597
2598 Note that unless you have a fairly recent pager (less works better
2598 Note that unless you have a fairly recent pager (less works better
2599 than more) in your system, using colored object information displays
2599 than more) in your system, using colored object information displays
2600 will not work properly. Test it and see."""
2600 will not work properly. Test it and see."""
2601
2601
2602 self.shell.color_info = not self.shell.color_info
2602 self.shell.color_info = not self.shell.color_info
2603 self.magic_colors(self.shell.colors)
2603 self.magic_colors(self.shell.colors)
2604 print 'Object introspection functions have now coloring:',
2604 print 'Object introspection functions have now coloring:',
2605 print ['OFF','ON'][int(self.shell.color_info)]
2605 print ['OFF','ON'][int(self.shell.color_info)]
2606
2606
2607 def magic_Pprint(self, parameter_s=''):
2607 def magic_Pprint(self, parameter_s=''):
2608 """Toggle pretty printing on/off."""
2608 """Toggle pretty printing on/off."""
2609
2609
2610 self.shell.pprint = 1 - self.shell.pprint
2610 self.shell.pprint = 1 - self.shell.pprint
2611 print 'Pretty printing has been turned', \
2611 print 'Pretty printing has been turned', \
2612 ['OFF','ON'][self.shell.pprint]
2612 ['OFF','ON'][self.shell.pprint]
2613
2613
2614 def magic_Exit(self, parameter_s=''):
2614 def magic_Exit(self, parameter_s=''):
2615 """Exit IPython without confirmation."""
2615 """Exit IPython without confirmation."""
2616
2616
2617 self.shell.ask_exit()
2617 self.shell.ask_exit()
2618
2618
2619 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2619 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2620 magic_exit = magic_quit = magic_Quit = magic_Exit
2620 magic_exit = magic_quit = magic_Quit = magic_Exit
2621
2621
2622 #......................................................................
2622 #......................................................................
2623 # Functions to implement unix shell-type things
2623 # Functions to implement unix shell-type things
2624
2624
2625 @testdec.skip_doctest
2625 @testdec.skip_doctest
2626 def magic_alias(self, parameter_s = ''):
2626 def magic_alias(self, parameter_s = ''):
2627 """Define an alias for a system command.
2627 """Define an alias for a system command.
2628
2628
2629 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2629 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2630
2630
2631 Then, typing 'alias_name params' will execute the system command 'cmd
2631 Then, typing 'alias_name params' will execute the system command 'cmd
2632 params' (from your underlying operating system).
2632 params' (from your underlying operating system).
2633
2633
2634 Aliases have lower precedence than magic functions and Python normal
2634 Aliases have lower precedence than magic functions and Python normal
2635 variables, so if 'foo' is both a Python variable and an alias, the
2635 variables, so if 'foo' is both a Python variable and an alias, the
2636 alias can not be executed until 'del foo' removes the Python variable.
2636 alias can not be executed until 'del foo' removes the Python variable.
2637
2637
2638 You can use the %l specifier in an alias definition to represent the
2638 You can use the %l specifier in an alias definition to represent the
2639 whole line when the alias is called. For example:
2639 whole line when the alias is called. For example:
2640
2640
2641 In [2]: alias all echo "Input in brackets: <%l>"
2641 In [2]: alias all echo "Input in brackets: <%l>"
2642 In [3]: all hello world
2642 In [3]: all hello world
2643 Input in brackets: <hello world>
2643 Input in brackets: <hello world>
2644
2644
2645 You can also define aliases with parameters using %s specifiers (one
2645 You can also define aliases with parameters using %s specifiers (one
2646 per parameter):
2646 per parameter):
2647
2647
2648 In [1]: alias parts echo first %s second %s
2648 In [1]: alias parts echo first %s second %s
2649 In [2]: %parts A B
2649 In [2]: %parts A B
2650 first A second B
2650 first A second B
2651 In [3]: %parts A
2651 In [3]: %parts A
2652 Incorrect number of arguments: 2 expected.
2652 Incorrect number of arguments: 2 expected.
2653 parts is an alias to: 'echo first %s second %s'
2653 parts is an alias to: 'echo first %s second %s'
2654
2654
2655 Note that %l and %s are mutually exclusive. You can only use one or
2655 Note that %l and %s are mutually exclusive. You can only use one or
2656 the other in your aliases.
2656 the other in your aliases.
2657
2657
2658 Aliases expand Python variables just like system calls using ! or !!
2658 Aliases expand Python variables just like system calls using ! or !!
2659 do: all expressions prefixed with '$' get expanded. For details of
2659 do: all expressions prefixed with '$' get expanded. For details of
2660 the semantic rules, see PEP-215:
2660 the semantic rules, see PEP-215:
2661 http://www.python.org/peps/pep-0215.html. This is the library used by
2661 http://www.python.org/peps/pep-0215.html. This is the library used by
2662 IPython for variable expansion. If you want to access a true shell
2662 IPython for variable expansion. If you want to access a true shell
2663 variable, an extra $ is necessary to prevent its expansion by IPython:
2663 variable, an extra $ is necessary to prevent its expansion by IPython:
2664
2664
2665 In [6]: alias show echo
2665 In [6]: alias show echo
2666 In [7]: PATH='A Python string'
2666 In [7]: PATH='A Python string'
2667 In [8]: show $PATH
2667 In [8]: show $PATH
2668 A Python string
2668 A Python string
2669 In [9]: show $$PATH
2669 In [9]: show $$PATH
2670 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2670 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2671
2671
2672 You can use the alias facility to acess all of $PATH. See the %rehash
2672 You can use the alias facility to acess all of $PATH. See the %rehash
2673 and %rehashx functions, which automatically create aliases for the
2673 and %rehashx functions, which automatically create aliases for the
2674 contents of your $PATH.
2674 contents of your $PATH.
2675
2675
2676 If called with no parameters, %alias prints the current alias table."""
2676 If called with no parameters, %alias prints the current alias table."""
2677
2677
2678 par = parameter_s.strip()
2678 par = parameter_s.strip()
2679 if not par:
2679 if not par:
2680 stored = self.db.get('stored_aliases', {} )
2680 stored = self.db.get('stored_aliases', {} )
2681 aliases = sorted(self.shell.alias_manager.aliases)
2681 aliases = sorted(self.shell.alias_manager.aliases)
2682 # for k, v in stored:
2682 # for k, v in stored:
2683 # atab.append(k, v[0])
2683 # atab.append(k, v[0])
2684
2684
2685 print "Total number of aliases:", len(aliases)
2685 print "Total number of aliases:", len(aliases)
2686 return aliases
2686 return aliases
2687
2687
2688 # Now try to define a new one
2688 # Now try to define a new one
2689 try:
2689 try:
2690 alias,cmd = par.split(None, 1)
2690 alias,cmd = par.split(None, 1)
2691 except:
2691 except:
2692 print oinspect.getdoc(self.magic_alias)
2692 print oinspect.getdoc(self.magic_alias)
2693 else:
2693 else:
2694 self.shell.alias_manager.soft_define_alias(alias, cmd)
2694 self.shell.alias_manager.soft_define_alias(alias, cmd)
2695 # end magic_alias
2695 # end magic_alias
2696
2696
2697 def magic_unalias(self, parameter_s = ''):
2697 def magic_unalias(self, parameter_s = ''):
2698 """Remove an alias"""
2698 """Remove an alias"""
2699
2699
2700 aname = parameter_s.strip()
2700 aname = parameter_s.strip()
2701 self.shell.alias_manager.undefine_alias(aname)
2701 self.shell.alias_manager.undefine_alias(aname)
2702 stored = self.db.get('stored_aliases', {} )
2702 stored = self.db.get('stored_aliases', {} )
2703 if aname in stored:
2703 if aname in stored:
2704 print "Removing %stored alias",aname
2704 print "Removing %stored alias",aname
2705 del stored[aname]
2705 del stored[aname]
2706 self.db['stored_aliases'] = stored
2706 self.db['stored_aliases'] = stored
2707
2707
2708
2708
2709 def magic_rehashx(self, parameter_s = ''):
2709 def magic_rehashx(self, parameter_s = ''):
2710 """Update the alias table with all executable files in $PATH.
2710 """Update the alias table with all executable files in $PATH.
2711
2711
2712 This version explicitly checks that every entry in $PATH is a file
2712 This version explicitly checks that every entry in $PATH is a file
2713 with execute access (os.X_OK), so it is much slower than %rehash.
2713 with execute access (os.X_OK), so it is much slower than %rehash.
2714
2714
2715 Under Windows, it checks executability as a match agains a
2715 Under Windows, it checks executability as a match agains a
2716 '|'-separated string of extensions, stored in the IPython config
2716 '|'-separated string of extensions, stored in the IPython config
2717 variable win_exec_ext. This defaults to 'exe|com|bat'.
2717 variable win_exec_ext. This defaults to 'exe|com|bat'.
2718
2718
2719 This function also resets the root module cache of module completer,
2719 This function also resets the root module cache of module completer,
2720 used on slow filesystems.
2720 used on slow filesystems.
2721 """
2721 """
2722 from IPython.core.alias import InvalidAliasError
2722 from IPython.core.alias import InvalidAliasError
2723
2723
2724 # for the benefit of module completer in ipy_completers.py
2724 # for the benefit of module completer in ipy_completers.py
2725 del self.db['rootmodules']
2725 del self.db['rootmodules']
2726
2726
2727 path = [os.path.abspath(os.path.expanduser(p)) for p in
2727 path = [os.path.abspath(os.path.expanduser(p)) for p in
2728 os.environ.get('PATH','').split(os.pathsep)]
2728 os.environ.get('PATH','').split(os.pathsep)]
2729 path = filter(os.path.isdir,path)
2729 path = filter(os.path.isdir,path)
2730
2730
2731 syscmdlist = []
2731 syscmdlist = []
2732 # Now define isexec in a cross platform manner.
2732 # Now define isexec in a cross platform manner.
2733 if os.name == 'posix':
2733 if os.name == 'posix':
2734 isexec = lambda fname:os.path.isfile(fname) and \
2734 isexec = lambda fname:os.path.isfile(fname) and \
2735 os.access(fname,os.X_OK)
2735 os.access(fname,os.X_OK)
2736 else:
2736 else:
2737 try:
2737 try:
2738 winext = os.environ['pathext'].replace(';','|').replace('.','')
2738 winext = os.environ['pathext'].replace(';','|').replace('.','')
2739 except KeyError:
2739 except KeyError:
2740 winext = 'exe|com|bat|py'
2740 winext = 'exe|com|bat|py'
2741 if 'py' not in winext:
2741 if 'py' not in winext:
2742 winext += '|py'
2742 winext += '|py'
2743 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2743 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2744 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2744 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2745 savedir = os.getcwd()
2745 savedir = os.getcwd()
2746
2746
2747 # Now walk the paths looking for executables to alias.
2747 # Now walk the paths looking for executables to alias.
2748 try:
2748 try:
2749 # write the whole loop for posix/Windows so we don't have an if in
2749 # write the whole loop for posix/Windows so we don't have an if in
2750 # the innermost part
2750 # the innermost part
2751 if os.name == 'posix':
2751 if os.name == 'posix':
2752 for pdir in path:
2752 for pdir in path:
2753 os.chdir(pdir)
2753 os.chdir(pdir)
2754 for ff in os.listdir(pdir):
2754 for ff in os.listdir(pdir):
2755 if isexec(ff):
2755 if isexec(ff):
2756 try:
2756 try:
2757 # Removes dots from the name since ipython
2757 # Removes dots from the name since ipython
2758 # will assume names with dots to be python.
2758 # will assume names with dots to be python.
2759 self.shell.alias_manager.define_alias(
2759 self.shell.alias_manager.define_alias(
2760 ff.replace('.',''), ff)
2760 ff.replace('.',''), ff)
2761 except InvalidAliasError:
2761 except InvalidAliasError:
2762 pass
2762 pass
2763 else:
2763 else:
2764 syscmdlist.append(ff)
2764 syscmdlist.append(ff)
2765 else:
2765 else:
2766 no_alias = self.shell.alias_manager.no_alias
2766 no_alias = self.shell.alias_manager.no_alias
2767 for pdir in path:
2767 for pdir in path:
2768 os.chdir(pdir)
2768 os.chdir(pdir)
2769 for ff in os.listdir(pdir):
2769 for ff in os.listdir(pdir):
2770 base, ext = os.path.splitext(ff)
2770 base, ext = os.path.splitext(ff)
2771 if isexec(ff) and base.lower() not in no_alias:
2771 if isexec(ff) and base.lower() not in no_alias:
2772 if ext.lower() == '.exe':
2772 if ext.lower() == '.exe':
2773 ff = base
2773 ff = base
2774 try:
2774 try:
2775 # Removes dots from the name since ipython
2775 # Removes dots from the name since ipython
2776 # will assume names with dots to be python.
2776 # will assume names with dots to be python.
2777 self.shell.alias_manager.define_alias(
2777 self.shell.alias_manager.define_alias(
2778 base.lower().replace('.',''), ff)
2778 base.lower().replace('.',''), ff)
2779 except InvalidAliasError:
2779 except InvalidAliasError:
2780 pass
2780 pass
2781 syscmdlist.append(ff)
2781 syscmdlist.append(ff)
2782 db = self.db
2782 db = self.db
2783 db['syscmdlist'] = syscmdlist
2783 db['syscmdlist'] = syscmdlist
2784 finally:
2784 finally:
2785 os.chdir(savedir)
2785 os.chdir(savedir)
2786
2786
2787 def magic_pwd(self, parameter_s = ''):
2787 def magic_pwd(self, parameter_s = ''):
2788 """Return the current working directory path."""
2788 """Return the current working directory path."""
2789 return os.getcwd()
2789 return os.getcwd()
2790
2790
2791 def magic_cd(self, parameter_s=''):
2791 def magic_cd(self, parameter_s=''):
2792 """Change the current working directory.
2792 """Change the current working directory.
2793
2793
2794 This command automatically maintains an internal list of directories
2794 This command automatically maintains an internal list of directories
2795 you visit during your IPython session, in the variable _dh. The
2795 you visit during your IPython session, in the variable _dh. The
2796 command %dhist shows this history nicely formatted. You can also
2796 command %dhist shows this history nicely formatted. You can also
2797 do 'cd -<tab>' to see directory history conveniently.
2797 do 'cd -<tab>' to see directory history conveniently.
2798
2798
2799 Usage:
2799 Usage:
2800
2800
2801 cd 'dir': changes to directory 'dir'.
2801 cd 'dir': changes to directory 'dir'.
2802
2802
2803 cd -: changes to the last visited directory.
2803 cd -: changes to the last visited directory.
2804
2804
2805 cd -<n>: changes to the n-th directory in the directory history.
2805 cd -<n>: changes to the n-th directory in the directory history.
2806
2806
2807 cd --foo: change to directory that matches 'foo' in history
2807 cd --foo: change to directory that matches 'foo' in history
2808
2808
2809 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2809 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2810 (note: cd <bookmark_name> is enough if there is no
2810 (note: cd <bookmark_name> is enough if there is no
2811 directory <bookmark_name>, but a bookmark with the name exists.)
2811 directory <bookmark_name>, but a bookmark with the name exists.)
2812 'cd -b <tab>' allows you to tab-complete bookmark names.
2812 'cd -b <tab>' allows you to tab-complete bookmark names.
2813
2813
2814 Options:
2814 Options:
2815
2815
2816 -q: quiet. Do not print the working directory after the cd command is
2816 -q: quiet. Do not print the working directory after the cd command is
2817 executed. By default IPython's cd command does print this directory,
2817 executed. By default IPython's cd command does print this directory,
2818 since the default prompts do not display path information.
2818 since the default prompts do not display path information.
2819
2819
2820 Note that !cd doesn't work for this purpose because the shell where
2820 Note that !cd doesn't work for this purpose because the shell where
2821 !command runs is immediately discarded after executing 'command'."""
2821 !command runs is immediately discarded after executing 'command'."""
2822
2822
2823 parameter_s = parameter_s.strip()
2823 parameter_s = parameter_s.strip()
2824 #bkms = self.shell.persist.get("bookmarks",{})
2824 #bkms = self.shell.persist.get("bookmarks",{})
2825
2825
2826 oldcwd = os.getcwd()
2826 oldcwd = os.getcwd()
2827 numcd = re.match(r'(-)(\d+)$',parameter_s)
2827 numcd = re.match(r'(-)(\d+)$',parameter_s)
2828 # jump in directory history by number
2828 # jump in directory history by number
2829 if numcd:
2829 if numcd:
2830 nn = int(numcd.group(2))
2830 nn = int(numcd.group(2))
2831 try:
2831 try:
2832 ps = self.shell.user_ns['_dh'][nn]
2832 ps = self.shell.user_ns['_dh'][nn]
2833 except IndexError:
2833 except IndexError:
2834 print 'The requested directory does not exist in history.'
2834 print 'The requested directory does not exist in history.'
2835 return
2835 return
2836 else:
2836 else:
2837 opts = {}
2837 opts = {}
2838 elif parameter_s.startswith('--'):
2838 elif parameter_s.startswith('--'):
2839 ps = None
2839 ps = None
2840 fallback = None
2840 fallback = None
2841 pat = parameter_s[2:]
2841 pat = parameter_s[2:]
2842 dh = self.shell.user_ns['_dh']
2842 dh = self.shell.user_ns['_dh']
2843 # first search only by basename (last component)
2843 # first search only by basename (last component)
2844 for ent in reversed(dh):
2844 for ent in reversed(dh):
2845 if pat in os.path.basename(ent) and os.path.isdir(ent):
2845 if pat in os.path.basename(ent) and os.path.isdir(ent):
2846 ps = ent
2846 ps = ent
2847 break
2847 break
2848
2848
2849 if fallback is None and pat in ent and os.path.isdir(ent):
2849 if fallback is None and pat in ent and os.path.isdir(ent):
2850 fallback = ent
2850 fallback = ent
2851
2851
2852 # if we have no last part match, pick the first full path match
2852 # if we have no last part match, pick the first full path match
2853 if ps is None:
2853 if ps is None:
2854 ps = fallback
2854 ps = fallback
2855
2855
2856 if ps is None:
2856 if ps is None:
2857 print "No matching entry in directory history"
2857 print "No matching entry in directory history"
2858 return
2858 return
2859 else:
2859 else:
2860 opts = {}
2860 opts = {}
2861
2861
2862
2862
2863 else:
2863 else:
2864 #turn all non-space-escaping backslashes to slashes,
2864 #turn all non-space-escaping backslashes to slashes,
2865 # for c:\windows\directory\names\
2865 # for c:\windows\directory\names\
2866 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2866 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2867 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2867 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2868 # jump to previous
2868 # jump to previous
2869 if ps == '-':
2869 if ps == '-':
2870 try:
2870 try:
2871 ps = self.shell.user_ns['_dh'][-2]
2871 ps = self.shell.user_ns['_dh'][-2]
2872 except IndexError:
2872 except IndexError:
2873 raise UsageError('%cd -: No previous directory to change to.')
2873 raise UsageError('%cd -: No previous directory to change to.')
2874 # jump to bookmark if needed
2874 # jump to bookmark if needed
2875 else:
2875 else:
2876 if not os.path.isdir(ps) or opts.has_key('b'):
2876 if not os.path.isdir(ps) or opts.has_key('b'):
2877 bkms = self.db.get('bookmarks', {})
2877 bkms = self.db.get('bookmarks', {})
2878
2878
2879 if bkms.has_key(ps):
2879 if bkms.has_key(ps):
2880 target = bkms[ps]
2880 target = bkms[ps]
2881 print '(bookmark:%s) -> %s' % (ps,target)
2881 print '(bookmark:%s) -> %s' % (ps,target)
2882 ps = target
2882 ps = target
2883 else:
2883 else:
2884 if opts.has_key('b'):
2884 if opts.has_key('b'):
2885 raise UsageError("Bookmark '%s' not found. "
2885 raise UsageError("Bookmark '%s' not found. "
2886 "Use '%%bookmark -l' to see your bookmarks." % ps)
2886 "Use '%%bookmark -l' to see your bookmarks." % ps)
2887
2887
2888 # at this point ps should point to the target dir
2888 # at this point ps should point to the target dir
2889 if ps:
2889 if ps:
2890 try:
2890 try:
2891 os.chdir(os.path.expanduser(ps))
2891 os.chdir(os.path.expanduser(ps))
2892 if self.shell.term_title:
2892 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2893 set_term_title('IPython: ' + abbrev_cwd())
2893 set_term_title('IPython: ' + abbrev_cwd())
2894 except OSError:
2894 except OSError:
2895 print sys.exc_info()[1]
2895 print sys.exc_info()[1]
2896 else:
2896 else:
2897 cwd = os.getcwd()
2897 cwd = os.getcwd()
2898 dhist = self.shell.user_ns['_dh']
2898 dhist = self.shell.user_ns['_dh']
2899 if oldcwd != cwd:
2899 if oldcwd != cwd:
2900 dhist.append(cwd)
2900 dhist.append(cwd)
2901 self.db['dhist'] = compress_dhist(dhist)[-100:]
2901 self.db['dhist'] = compress_dhist(dhist)[-100:]
2902
2902
2903 else:
2903 else:
2904 os.chdir(self.shell.home_dir)
2904 os.chdir(self.shell.home_dir)
2905 if self.shell.term_title:
2905 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2906 set_term_title('IPython: ' + '~')
2906 set_term_title('IPython: ' + '~')
2907 cwd = os.getcwd()
2907 cwd = os.getcwd()
2908 dhist = self.shell.user_ns['_dh']
2908 dhist = self.shell.user_ns['_dh']
2909
2909
2910 if oldcwd != cwd:
2910 if oldcwd != cwd:
2911 dhist.append(cwd)
2911 dhist.append(cwd)
2912 self.db['dhist'] = compress_dhist(dhist)[-100:]
2912 self.db['dhist'] = compress_dhist(dhist)[-100:]
2913 if not 'q' in opts and self.shell.user_ns['_dh']:
2913 if not 'q' in opts and self.shell.user_ns['_dh']:
2914 print self.shell.user_ns['_dh'][-1]
2914 print self.shell.user_ns['_dh'][-1]
2915
2915
2916
2916
2917 def magic_env(self, parameter_s=''):
2917 def magic_env(self, parameter_s=''):
2918 """List environment variables."""
2918 """List environment variables."""
2919
2919
2920 return os.environ.data
2920 return os.environ.data
2921
2921
2922 def magic_pushd(self, parameter_s=''):
2922 def magic_pushd(self, parameter_s=''):
2923 """Place the current dir on stack and change directory.
2923 """Place the current dir on stack and change directory.
2924
2924
2925 Usage:\\
2925 Usage:\\
2926 %pushd ['dirname']
2926 %pushd ['dirname']
2927 """
2927 """
2928
2928
2929 dir_s = self.shell.dir_stack
2929 dir_s = self.shell.dir_stack
2930 tgt = os.path.expanduser(parameter_s)
2930 tgt = os.path.expanduser(parameter_s)
2931 cwd = os.getcwd().replace(self.home_dir,'~')
2931 cwd = os.getcwd().replace(self.home_dir,'~')
2932 if tgt:
2932 if tgt:
2933 self.magic_cd(parameter_s)
2933 self.magic_cd(parameter_s)
2934 dir_s.insert(0,cwd)
2934 dir_s.insert(0,cwd)
2935 return self.magic_dirs()
2935 return self.magic_dirs()
2936
2936
2937 def magic_popd(self, parameter_s=''):
2937 def magic_popd(self, parameter_s=''):
2938 """Change to directory popped off the top of the stack.
2938 """Change to directory popped off the top of the stack.
2939 """
2939 """
2940 if not self.shell.dir_stack:
2940 if not self.shell.dir_stack:
2941 raise UsageError("%popd on empty stack")
2941 raise UsageError("%popd on empty stack")
2942 top = self.shell.dir_stack.pop(0)
2942 top = self.shell.dir_stack.pop(0)
2943 self.magic_cd(top)
2943 self.magic_cd(top)
2944 print "popd ->",top
2944 print "popd ->",top
2945
2945
2946 def magic_dirs(self, parameter_s=''):
2946 def magic_dirs(self, parameter_s=''):
2947 """Return the current directory stack."""
2947 """Return the current directory stack."""
2948
2948
2949 return self.shell.dir_stack
2949 return self.shell.dir_stack
2950
2950
2951 def magic_dhist(self, parameter_s=''):
2951 def magic_dhist(self, parameter_s=''):
2952 """Print your history of visited directories.
2952 """Print your history of visited directories.
2953
2953
2954 %dhist -> print full history\\
2954 %dhist -> print full history\\
2955 %dhist n -> print last n entries only\\
2955 %dhist n -> print last n entries only\\
2956 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2956 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2957
2957
2958 This history is automatically maintained by the %cd command, and
2958 This history is automatically maintained by the %cd command, and
2959 always available as the global list variable _dh. You can use %cd -<n>
2959 always available as the global list variable _dh. You can use %cd -<n>
2960 to go to directory number <n>.
2960 to go to directory number <n>.
2961
2961
2962 Note that most of time, you should view directory history by entering
2962 Note that most of time, you should view directory history by entering
2963 cd -<TAB>.
2963 cd -<TAB>.
2964
2964
2965 """
2965 """
2966
2966
2967 dh = self.shell.user_ns['_dh']
2967 dh = self.shell.user_ns['_dh']
2968 if parameter_s:
2968 if parameter_s:
2969 try:
2969 try:
2970 args = map(int,parameter_s.split())
2970 args = map(int,parameter_s.split())
2971 except:
2971 except:
2972 self.arg_err(Magic.magic_dhist)
2972 self.arg_err(Magic.magic_dhist)
2973 return
2973 return
2974 if len(args) == 1:
2974 if len(args) == 1:
2975 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2975 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2976 elif len(args) == 2:
2976 elif len(args) == 2:
2977 ini,fin = args
2977 ini,fin = args
2978 else:
2978 else:
2979 self.arg_err(Magic.magic_dhist)
2979 self.arg_err(Magic.magic_dhist)
2980 return
2980 return
2981 else:
2981 else:
2982 ini,fin = 0,len(dh)
2982 ini,fin = 0,len(dh)
2983 nlprint(dh,
2983 nlprint(dh,
2984 header = 'Directory history (kept in _dh)',
2984 header = 'Directory history (kept in _dh)',
2985 start=ini,stop=fin)
2985 start=ini,stop=fin)
2986
2986
2987 @testdec.skip_doctest
2987 @testdec.skip_doctest
2988 def magic_sc(self, parameter_s=''):
2988 def magic_sc(self, parameter_s=''):
2989 """Shell capture - execute a shell command and capture its output.
2989 """Shell capture - execute a shell command and capture its output.
2990
2990
2991 DEPRECATED. Suboptimal, retained for backwards compatibility.
2991 DEPRECATED. Suboptimal, retained for backwards compatibility.
2992
2992
2993 You should use the form 'var = !command' instead. Example:
2993 You should use the form 'var = !command' instead. Example:
2994
2994
2995 "%sc -l myfiles = ls ~" should now be written as
2995 "%sc -l myfiles = ls ~" should now be written as
2996
2996
2997 "myfiles = !ls ~"
2997 "myfiles = !ls ~"
2998
2998
2999 myfiles.s, myfiles.l and myfiles.n still apply as documented
2999 myfiles.s, myfiles.l and myfiles.n still apply as documented
3000 below.
3000 below.
3001
3001
3002 --
3002 --
3003 %sc [options] varname=command
3003 %sc [options] varname=command
3004
3004
3005 IPython will run the given command using commands.getoutput(), and
3005 IPython will run the given command using commands.getoutput(), and
3006 will then update the user's interactive namespace with a variable
3006 will then update the user's interactive namespace with a variable
3007 called varname, containing the value of the call. Your command can
3007 called varname, containing the value of the call. Your command can
3008 contain shell wildcards, pipes, etc.
3008 contain shell wildcards, pipes, etc.
3009
3009
3010 The '=' sign in the syntax is mandatory, and the variable name you
3010 The '=' sign in the syntax is mandatory, and the variable name you
3011 supply must follow Python's standard conventions for valid names.
3011 supply must follow Python's standard conventions for valid names.
3012
3012
3013 (A special format without variable name exists for internal use)
3013 (A special format without variable name exists for internal use)
3014
3014
3015 Options:
3015 Options:
3016
3016
3017 -l: list output. Split the output on newlines into a list before
3017 -l: list output. Split the output on newlines into a list before
3018 assigning it to the given variable. By default the output is stored
3018 assigning it to the given variable. By default the output is stored
3019 as a single string.
3019 as a single string.
3020
3020
3021 -v: verbose. Print the contents of the variable.
3021 -v: verbose. Print the contents of the variable.
3022
3022
3023 In most cases you should not need to split as a list, because the
3023 In most cases you should not need to split as a list, because the
3024 returned value is a special type of string which can automatically
3024 returned value is a special type of string which can automatically
3025 provide its contents either as a list (split on newlines) or as a
3025 provide its contents either as a list (split on newlines) or as a
3026 space-separated string. These are convenient, respectively, either
3026 space-separated string. These are convenient, respectively, either
3027 for sequential processing or to be passed to a shell command.
3027 for sequential processing or to be passed to a shell command.
3028
3028
3029 For example:
3029 For example:
3030
3030
3031 # all-random
3031 # all-random
3032
3032
3033 # Capture into variable a
3033 # Capture into variable a
3034 In [1]: sc a=ls *py
3034 In [1]: sc a=ls *py
3035
3035
3036 # a is a string with embedded newlines
3036 # a is a string with embedded newlines
3037 In [2]: a
3037 In [2]: a
3038 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3038 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3039
3039
3040 # which can be seen as a list:
3040 # which can be seen as a list:
3041 In [3]: a.l
3041 In [3]: a.l
3042 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3042 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3043
3043
3044 # or as a whitespace-separated string:
3044 # or as a whitespace-separated string:
3045 In [4]: a.s
3045 In [4]: a.s
3046 Out[4]: 'setup.py win32_manual_post_install.py'
3046 Out[4]: 'setup.py win32_manual_post_install.py'
3047
3047
3048 # a.s is useful to pass as a single command line:
3048 # a.s is useful to pass as a single command line:
3049 In [5]: !wc -l $a.s
3049 In [5]: !wc -l $a.s
3050 146 setup.py
3050 146 setup.py
3051 130 win32_manual_post_install.py
3051 130 win32_manual_post_install.py
3052 276 total
3052 276 total
3053
3053
3054 # while the list form is useful to loop over:
3054 # while the list form is useful to loop over:
3055 In [6]: for f in a.l:
3055 In [6]: for f in a.l:
3056 ...: !wc -l $f
3056 ...: !wc -l $f
3057 ...:
3057 ...:
3058 146 setup.py
3058 146 setup.py
3059 130 win32_manual_post_install.py
3059 130 win32_manual_post_install.py
3060
3060
3061 Similiarly, the lists returned by the -l option are also special, in
3061 Similiarly, the lists returned by the -l option are also special, in
3062 the sense that you can equally invoke the .s attribute on them to
3062 the sense that you can equally invoke the .s attribute on them to
3063 automatically get a whitespace-separated string from their contents:
3063 automatically get a whitespace-separated string from their contents:
3064
3064
3065 In [7]: sc -l b=ls *py
3065 In [7]: sc -l b=ls *py
3066
3066
3067 In [8]: b
3067 In [8]: b
3068 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3068 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3069
3069
3070 In [9]: b.s
3070 In [9]: b.s
3071 Out[9]: 'setup.py win32_manual_post_install.py'
3071 Out[9]: 'setup.py win32_manual_post_install.py'
3072
3072
3073 In summary, both the lists and strings used for ouptut capture have
3073 In summary, both the lists and strings used for ouptut capture have
3074 the following special attributes:
3074 the following special attributes:
3075
3075
3076 .l (or .list) : value as list.
3076 .l (or .list) : value as list.
3077 .n (or .nlstr): value as newline-separated string.
3077 .n (or .nlstr): value as newline-separated string.
3078 .s (or .spstr): value as space-separated string.
3078 .s (or .spstr): value as space-separated string.
3079 """
3079 """
3080
3080
3081 opts,args = self.parse_options(parameter_s,'lv')
3081 opts,args = self.parse_options(parameter_s,'lv')
3082 # Try to get a variable name and command to run
3082 # Try to get a variable name and command to run
3083 try:
3083 try:
3084 # the variable name must be obtained from the parse_options
3084 # the variable name must be obtained from the parse_options
3085 # output, which uses shlex.split to strip options out.
3085 # output, which uses shlex.split to strip options out.
3086 var,_ = args.split('=',1)
3086 var,_ = args.split('=',1)
3087 var = var.strip()
3087 var = var.strip()
3088 # But the the command has to be extracted from the original input
3088 # But the the command has to be extracted from the original input
3089 # parameter_s, not on what parse_options returns, to avoid the
3089 # parameter_s, not on what parse_options returns, to avoid the
3090 # quote stripping which shlex.split performs on it.
3090 # quote stripping which shlex.split performs on it.
3091 _,cmd = parameter_s.split('=',1)
3091 _,cmd = parameter_s.split('=',1)
3092 except ValueError:
3092 except ValueError:
3093 var,cmd = '',''
3093 var,cmd = '',''
3094 # If all looks ok, proceed
3094 # If all looks ok, proceed
3095 out,err = self.shell.getoutputerror(cmd)
3095 out,err = self.shell.getoutputerror(cmd)
3096 if err:
3096 if err:
3097 print >> IPython.utils.io.Term.cerr, err
3097 print >> IPython.utils.io.Term.cerr, err
3098 if opts.has_key('l'):
3098 if opts.has_key('l'):
3099 out = SList(out.split('\n'))
3099 out = SList(out.split('\n'))
3100 else:
3100 else:
3101 out = LSString(out)
3101 out = LSString(out)
3102 if opts.has_key('v'):
3102 if opts.has_key('v'):
3103 print '%s ==\n%s' % (var,pformat(out))
3103 print '%s ==\n%s' % (var,pformat(out))
3104 if var:
3104 if var:
3105 self.shell.user_ns.update({var:out})
3105 self.shell.user_ns.update({var:out})
3106 else:
3106 else:
3107 return out
3107 return out
3108
3108
3109 def magic_sx(self, parameter_s=''):
3109 def magic_sx(self, parameter_s=''):
3110 """Shell execute - run a shell command and capture its output.
3110 """Shell execute - run a shell command and capture its output.
3111
3111
3112 %sx command
3112 %sx command
3113
3113
3114 IPython will run the given command using commands.getoutput(), and
3114 IPython will run the given command using commands.getoutput(), and
3115 return the result formatted as a list (split on '\\n'). Since the
3115 return the result formatted as a list (split on '\\n'). Since the
3116 output is _returned_, it will be stored in ipython's regular output
3116 output is _returned_, it will be stored in ipython's regular output
3117 cache Out[N] and in the '_N' automatic variables.
3117 cache Out[N] and in the '_N' automatic variables.
3118
3118
3119 Notes:
3119 Notes:
3120
3120
3121 1) If an input line begins with '!!', then %sx is automatically
3121 1) If an input line begins with '!!', then %sx is automatically
3122 invoked. That is, while:
3122 invoked. That is, while:
3123 !ls
3123 !ls
3124 causes ipython to simply issue system('ls'), typing
3124 causes ipython to simply issue system('ls'), typing
3125 !!ls
3125 !!ls
3126 is a shorthand equivalent to:
3126 is a shorthand equivalent to:
3127 %sx ls
3127 %sx ls
3128
3128
3129 2) %sx differs from %sc in that %sx automatically splits into a list,
3129 2) %sx differs from %sc in that %sx automatically splits into a list,
3130 like '%sc -l'. The reason for this is to make it as easy as possible
3130 like '%sc -l'. The reason for this is to make it as easy as possible
3131 to process line-oriented shell output via further python commands.
3131 to process line-oriented shell output via further python commands.
3132 %sc is meant to provide much finer control, but requires more
3132 %sc is meant to provide much finer control, but requires more
3133 typing.
3133 typing.
3134
3134
3135 3) Just like %sc -l, this is a list with special attributes:
3135 3) Just like %sc -l, this is a list with special attributes:
3136
3136
3137 .l (or .list) : value as list.
3137 .l (or .list) : value as list.
3138 .n (or .nlstr): value as newline-separated string.
3138 .n (or .nlstr): value as newline-separated string.
3139 .s (or .spstr): value as whitespace-separated string.
3139 .s (or .spstr): value as whitespace-separated string.
3140
3140
3141 This is very useful when trying to use such lists as arguments to
3141 This is very useful when trying to use such lists as arguments to
3142 system commands."""
3142 system commands."""
3143
3143
3144 if parameter_s:
3144 if parameter_s:
3145 out,err = self.shell.getoutputerror(parameter_s)
3145 out,err = self.shell.getoutputerror(parameter_s)
3146 if err:
3146 if err:
3147 print >> IPython.utils.io.Term.cerr, err
3147 print >> IPython.utils.io.Term.cerr, err
3148 return SList(out.split('\n'))
3148 return SList(out.split('\n'))
3149
3149
3150 def magic_r(self, parameter_s=''):
3150 def magic_r(self, parameter_s=''):
3151 """Repeat previous input.
3151 """Repeat previous input.
3152
3152
3153 Note: Consider using the more powerfull %rep instead!
3153 Note: Consider using the more powerfull %rep instead!
3154
3154
3155 If given an argument, repeats the previous command which starts with
3155 If given an argument, repeats the previous command which starts with
3156 the same string, otherwise it just repeats the previous input.
3156 the same string, otherwise it just repeats the previous input.
3157
3157
3158 Shell escaped commands (with ! as first character) are not recognized
3158 Shell escaped commands (with ! as first character) are not recognized
3159 by this system, only pure python code and magic commands.
3159 by this system, only pure python code and magic commands.
3160 """
3160 """
3161
3161
3162 start = parameter_s.strip()
3162 start = parameter_s.strip()
3163 esc_magic = ESC_MAGIC
3163 esc_magic = ESC_MAGIC
3164 # Identify magic commands even if automagic is on (which means
3164 # Identify magic commands even if automagic is on (which means
3165 # the in-memory version is different from that typed by the user).
3165 # the in-memory version is different from that typed by the user).
3166 if self.shell.automagic:
3166 if self.shell.automagic:
3167 start_magic = esc_magic+start
3167 start_magic = esc_magic+start
3168 else:
3168 else:
3169 start_magic = start
3169 start_magic = start
3170 # Look through the input history in reverse
3170 # Look through the input history in reverse
3171 for n in range(len(self.shell.input_hist)-2,0,-1):
3171 for n in range(len(self.shell.input_hist)-2,0,-1):
3172 input = self.shell.input_hist[n]
3172 input = self.shell.input_hist[n]
3173 # skip plain 'r' lines so we don't recurse to infinity
3173 # skip plain 'r' lines so we don't recurse to infinity
3174 if input != '_ip.magic("r")\n' and \
3174 if input != '_ip.magic("r")\n' and \
3175 (input.startswith(start) or input.startswith(start_magic)):
3175 (input.startswith(start) or input.startswith(start_magic)):
3176 #print 'match',`input` # dbg
3176 #print 'match',`input` # dbg
3177 print 'Executing:',input,
3177 print 'Executing:',input,
3178 self.shell.runlines(input)
3178 self.shell.runlines(input)
3179 return
3179 return
3180 print 'No previous input matching `%s` found.' % start
3180 print 'No previous input matching `%s` found.' % start
3181
3181
3182
3182
3183 def magic_bookmark(self, parameter_s=''):
3183 def magic_bookmark(self, parameter_s=''):
3184 """Manage IPython's bookmark system.
3184 """Manage IPython's bookmark system.
3185
3185
3186 %bookmark <name> - set bookmark to current dir
3186 %bookmark <name> - set bookmark to current dir
3187 %bookmark <name> <dir> - set bookmark to <dir>
3187 %bookmark <name> <dir> - set bookmark to <dir>
3188 %bookmark -l - list all bookmarks
3188 %bookmark -l - list all bookmarks
3189 %bookmark -d <name> - remove bookmark
3189 %bookmark -d <name> - remove bookmark
3190 %bookmark -r - remove all bookmarks
3190 %bookmark -r - remove all bookmarks
3191
3191
3192 You can later on access a bookmarked folder with:
3192 You can later on access a bookmarked folder with:
3193 %cd -b <name>
3193 %cd -b <name>
3194 or simply '%cd <name>' if there is no directory called <name> AND
3194 or simply '%cd <name>' if there is no directory called <name> AND
3195 there is such a bookmark defined.
3195 there is such a bookmark defined.
3196
3196
3197 Your bookmarks persist through IPython sessions, but they are
3197 Your bookmarks persist through IPython sessions, but they are
3198 associated with each profile."""
3198 associated with each profile."""
3199
3199
3200 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3200 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3201 if len(args) > 2:
3201 if len(args) > 2:
3202 raise UsageError("%bookmark: too many arguments")
3202 raise UsageError("%bookmark: too many arguments")
3203
3203
3204 bkms = self.db.get('bookmarks',{})
3204 bkms = self.db.get('bookmarks',{})
3205
3205
3206 if opts.has_key('d'):
3206 if opts.has_key('d'):
3207 try:
3207 try:
3208 todel = args[0]
3208 todel = args[0]
3209 except IndexError:
3209 except IndexError:
3210 raise UsageError(
3210 raise UsageError(
3211 "%bookmark -d: must provide a bookmark to delete")
3211 "%bookmark -d: must provide a bookmark to delete")
3212 else:
3212 else:
3213 try:
3213 try:
3214 del bkms[todel]
3214 del bkms[todel]
3215 except KeyError:
3215 except KeyError:
3216 raise UsageError(
3216 raise UsageError(
3217 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3217 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3218
3218
3219 elif opts.has_key('r'):
3219 elif opts.has_key('r'):
3220 bkms = {}
3220 bkms = {}
3221 elif opts.has_key('l'):
3221 elif opts.has_key('l'):
3222 bks = bkms.keys()
3222 bks = bkms.keys()
3223 bks.sort()
3223 bks.sort()
3224 if bks:
3224 if bks:
3225 size = max(map(len,bks))
3225 size = max(map(len,bks))
3226 else:
3226 else:
3227 size = 0
3227 size = 0
3228 fmt = '%-'+str(size)+'s -> %s'
3228 fmt = '%-'+str(size)+'s -> %s'
3229 print 'Current bookmarks:'
3229 print 'Current bookmarks:'
3230 for bk in bks:
3230 for bk in bks:
3231 print fmt % (bk,bkms[bk])
3231 print fmt % (bk,bkms[bk])
3232 else:
3232 else:
3233 if not args:
3233 if not args:
3234 raise UsageError("%bookmark: You must specify the bookmark name")
3234 raise UsageError("%bookmark: You must specify the bookmark name")
3235 elif len(args)==1:
3235 elif len(args)==1:
3236 bkms[args[0]] = os.getcwd()
3236 bkms[args[0]] = os.getcwd()
3237 elif len(args)==2:
3237 elif len(args)==2:
3238 bkms[args[0]] = args[1]
3238 bkms[args[0]] = args[1]
3239 self.db['bookmarks'] = bkms
3239 self.db['bookmarks'] = bkms
3240
3240
3241 def magic_pycat(self, parameter_s=''):
3241 def magic_pycat(self, parameter_s=''):
3242 """Show a syntax-highlighted file through a pager.
3242 """Show a syntax-highlighted file through a pager.
3243
3243
3244 This magic is similar to the cat utility, but it will assume the file
3244 This magic is similar to the cat utility, but it will assume the file
3245 to be Python source and will show it with syntax highlighting. """
3245 to be Python source and will show it with syntax highlighting. """
3246
3246
3247 try:
3247 try:
3248 filename = get_py_filename(parameter_s)
3248 filename = get_py_filename(parameter_s)
3249 cont = file_read(filename)
3249 cont = file_read(filename)
3250 except IOError:
3250 except IOError:
3251 try:
3251 try:
3252 cont = eval(parameter_s,self.user_ns)
3252 cont = eval(parameter_s,self.user_ns)
3253 except NameError:
3253 except NameError:
3254 cont = None
3254 cont = None
3255 if cont is None:
3255 if cont is None:
3256 print "Error: no such file or variable"
3256 print "Error: no such file or variable"
3257 return
3257 return
3258
3258
3259 page(self.shell.pycolorize(cont),
3259 page(self.shell.pycolorize(cont),
3260 screen_lines=self.shell.usable_screen_length)
3260 screen_lines=self.shell.usable_screen_length)
3261
3261
3262 def _rerun_pasted(self):
3262 def _rerun_pasted(self):
3263 """ Rerun a previously pasted command.
3263 """ Rerun a previously pasted command.
3264 """
3264 """
3265 b = self.user_ns.get('pasted_block', None)
3265 b = self.user_ns.get('pasted_block', None)
3266 if b is None:
3266 if b is None:
3267 raise UsageError('No previous pasted block available')
3267 raise UsageError('No previous pasted block available')
3268 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3268 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3269 exec b in self.user_ns
3269 exec b in self.user_ns
3270
3270
3271 def _get_pasted_lines(self, sentinel):
3271 def _get_pasted_lines(self, sentinel):
3272 """ Yield pasted lines until the user enters the given sentinel value.
3272 """ Yield pasted lines until the user enters the given sentinel value.
3273 """
3273 """
3274 from IPython.core import interactiveshell
3274 from IPython.core import interactiveshell
3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3276 while True:
3276 while True:
3277 l = interactiveshell.raw_input_original(':')
3277 l = interactiveshell.raw_input_original(':')
3278 if l == sentinel:
3278 if l == sentinel:
3279 return
3279 return
3280 else:
3280 else:
3281 yield l
3281 yield l
3282
3282
3283 def _strip_pasted_lines_for_code(self, raw_lines):
3283 def _strip_pasted_lines_for_code(self, raw_lines):
3284 """ Strip non-code parts of a sequence of lines to return a block of
3284 """ Strip non-code parts of a sequence of lines to return a block of
3285 code.
3285 code.
3286 """
3286 """
3287 # Regular expressions that declare text we strip from the input:
3287 # Regular expressions that declare text we strip from the input:
3288 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3288 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3289 r'^\s*(\s?>)+', # Python input prompt
3289 r'^\s*(\s?>)+', # Python input prompt
3290 r'^\s*\.{3,}', # Continuation prompts
3290 r'^\s*\.{3,}', # Continuation prompts
3291 r'^\++',
3291 r'^\++',
3292 ]
3292 ]
3293
3293
3294 strip_from_start = map(re.compile,strip_re)
3294 strip_from_start = map(re.compile,strip_re)
3295
3295
3296 lines = []
3296 lines = []
3297 for l in raw_lines:
3297 for l in raw_lines:
3298 for pat in strip_from_start:
3298 for pat in strip_from_start:
3299 l = pat.sub('',l)
3299 l = pat.sub('',l)
3300 lines.append(l)
3300 lines.append(l)
3301
3301
3302 block = "\n".join(lines) + '\n'
3302 block = "\n".join(lines) + '\n'
3303 #print "block:\n",block
3303 #print "block:\n",block
3304 return block
3304 return block
3305
3305
3306 def _execute_block(self, block, par):
3306 def _execute_block(self, block, par):
3307 """ Execute a block, or store it in a variable, per the user's request.
3307 """ Execute a block, or store it in a variable, per the user's request.
3308 """
3308 """
3309 if not par:
3309 if not par:
3310 b = textwrap.dedent(block)
3310 b = textwrap.dedent(block)
3311 self.user_ns['pasted_block'] = b
3311 self.user_ns['pasted_block'] = b
3312 exec b in self.user_ns
3312 exec b in self.user_ns
3313 else:
3313 else:
3314 self.user_ns[par] = SList(block.splitlines())
3314 self.user_ns[par] = SList(block.splitlines())
3315 print "Block assigned to '%s'" % par
3315 print "Block assigned to '%s'" % par
3316
3316
3317 def magic_cpaste(self, parameter_s=''):
3317 def magic_cpaste(self, parameter_s=''):
3318 """Allows you to paste & execute a pre-formatted code block from clipboard.
3318 """Allows you to paste & execute a pre-formatted code block from clipboard.
3319
3319
3320 You must terminate the block with '--' (two minus-signs) alone on the
3320 You must terminate the block with '--' (two minus-signs) alone on the
3321 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3321 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3322 is the new sentinel for this operation)
3322 is the new sentinel for this operation)
3323
3323
3324 The block is dedented prior to execution to enable execution of method
3324 The block is dedented prior to execution to enable execution of method
3325 definitions. '>' and '+' characters at the beginning of a line are
3325 definitions. '>' and '+' characters at the beginning of a line are
3326 ignored, to allow pasting directly from e-mails, diff files and
3326 ignored, to allow pasting directly from e-mails, diff files and
3327 doctests (the '...' continuation prompt is also stripped). The
3327 doctests (the '...' continuation prompt is also stripped). The
3328 executed block is also assigned to variable named 'pasted_block' for
3328 executed block is also assigned to variable named 'pasted_block' for
3329 later editing with '%edit pasted_block'.
3329 later editing with '%edit pasted_block'.
3330
3330
3331 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3331 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3332 This assigns the pasted block to variable 'foo' as string, without
3332 This assigns the pasted block to variable 'foo' as string, without
3333 dedenting or executing it (preceding >>> and + is still stripped)
3333 dedenting or executing it (preceding >>> and + is still stripped)
3334
3334
3335 '%cpaste -r' re-executes the block previously entered by cpaste.
3335 '%cpaste -r' re-executes the block previously entered by cpaste.
3336
3336
3337 Do not be alarmed by garbled output on Windows (it's a readline bug).
3337 Do not be alarmed by garbled output on Windows (it's a readline bug).
3338 Just press enter and type -- (and press enter again) and the block
3338 Just press enter and type -- (and press enter again) and the block
3339 will be what was just pasted.
3339 will be what was just pasted.
3340
3340
3341 IPython statements (magics, shell escapes) are not supported (yet).
3341 IPython statements (magics, shell escapes) are not supported (yet).
3342
3342
3343 See also
3343 See also
3344 --------
3344 --------
3345 paste: automatically pull code from clipboard.
3345 paste: automatically pull code from clipboard.
3346 """
3346 """
3347
3347
3348 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3348 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3349 par = args.strip()
3349 par = args.strip()
3350 if opts.has_key('r'):
3350 if opts.has_key('r'):
3351 self._rerun_pasted()
3351 self._rerun_pasted()
3352 return
3352 return
3353
3353
3354 sentinel = opts.get('s','--')
3354 sentinel = opts.get('s','--')
3355
3355
3356 block = self._strip_pasted_lines_for_code(
3356 block = self._strip_pasted_lines_for_code(
3357 self._get_pasted_lines(sentinel))
3357 self._get_pasted_lines(sentinel))
3358
3358
3359 self._execute_block(block, par)
3359 self._execute_block(block, par)
3360
3360
3361 def magic_paste(self, parameter_s=''):
3361 def magic_paste(self, parameter_s=''):
3362 """Allows you to paste & execute a pre-formatted code block from clipboard.
3362 """Allows you to paste & execute a pre-formatted code block from clipboard.
3363
3363
3364 The text is pulled directly from the clipboard without user
3364 The text is pulled directly from the clipboard without user
3365 intervention and printed back on the screen before execution (unless
3365 intervention and printed back on the screen before execution (unless
3366 the -q flag is given to force quiet mode).
3366 the -q flag is given to force quiet mode).
3367
3367
3368 The block is dedented prior to execution to enable execution of method
3368 The block is dedented prior to execution to enable execution of method
3369 definitions. '>' and '+' characters at the beginning of a line are
3369 definitions. '>' and '+' characters at the beginning of a line are
3370 ignored, to allow pasting directly from e-mails, diff files and
3370 ignored, to allow pasting directly from e-mails, diff files and
3371 doctests (the '...' continuation prompt is also stripped). The
3371 doctests (the '...' continuation prompt is also stripped). The
3372 executed block is also assigned to variable named 'pasted_block' for
3372 executed block is also assigned to variable named 'pasted_block' for
3373 later editing with '%edit pasted_block'.
3373 later editing with '%edit pasted_block'.
3374
3374
3375 You can also pass a variable name as an argument, e.g. '%paste foo'.
3375 You can also pass a variable name as an argument, e.g. '%paste foo'.
3376 This assigns the pasted block to variable 'foo' as string, without
3376 This assigns the pasted block to variable 'foo' as string, without
3377 dedenting or executing it (preceding >>> and + is still stripped)
3377 dedenting or executing it (preceding >>> and + is still stripped)
3378
3378
3379 Options
3379 Options
3380 -------
3380 -------
3381
3381
3382 -r: re-executes the block previously entered by cpaste.
3382 -r: re-executes the block previously entered by cpaste.
3383
3383
3384 -q: quiet mode: do not echo the pasted text back to the terminal.
3384 -q: quiet mode: do not echo the pasted text back to the terminal.
3385
3385
3386 IPython statements (magics, shell escapes) are not supported (yet).
3386 IPython statements (magics, shell escapes) are not supported (yet).
3387
3387
3388 See also
3388 See also
3389 --------
3389 --------
3390 cpaste: manually paste code into terminal until you mark its end.
3390 cpaste: manually paste code into terminal until you mark its end.
3391 """
3391 """
3392 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3392 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3393 par = args.strip()
3393 par = args.strip()
3394 if opts.has_key('r'):
3394 if opts.has_key('r'):
3395 self._rerun_pasted()
3395 self._rerun_pasted()
3396 return
3396 return
3397
3397
3398 text = self.shell.hooks.clipboard_get()
3398 text = self.shell.hooks.clipboard_get()
3399 block = self._strip_pasted_lines_for_code(text.splitlines())
3399 block = self._strip_pasted_lines_for_code(text.splitlines())
3400
3400
3401 # By default, echo back to terminal unless quiet mode is requested
3401 # By default, echo back to terminal unless quiet mode is requested
3402 if not opts.has_key('q'):
3402 if not opts.has_key('q'):
3403 write = self.shell.write
3403 write = self.shell.write
3404 write(self.shell.pycolorize(block))
3404 write(self.shell.pycolorize(block))
3405 if not block.endswith('\n'):
3405 if not block.endswith('\n'):
3406 write('\n')
3406 write('\n')
3407 write("## -- End pasted text --\n")
3407 write("## -- End pasted text --\n")
3408
3408
3409 self._execute_block(block, par)
3409 self._execute_block(block, par)
3410
3410
3411 def magic_quickref(self,arg):
3411 def magic_quickref(self,arg):
3412 """ Show a quick reference sheet """
3412 """ Show a quick reference sheet """
3413 import IPython.core.usage
3413 import IPython.core.usage
3414 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3414 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3415
3415
3416 page(qr)
3416 page(qr)
3417
3417
3418 def magic_doctest_mode(self,parameter_s=''):
3418 def magic_doctest_mode(self,parameter_s=''):
3419 """Toggle doctest mode on and off.
3419 """Toggle doctest mode on and off.
3420
3420
3421 This mode allows you to toggle the prompt behavior between normal
3421 This mode allows you to toggle the prompt behavior between normal
3422 IPython prompts and ones that are as similar to the default IPython
3422 IPython prompts and ones that are as similar to the default IPython
3423 interpreter as possible.
3423 interpreter as possible.
3424
3424
3425 It also supports the pasting of code snippets that have leading '>>>'
3425 It also supports the pasting of code snippets that have leading '>>>'
3426 and '...' prompts in them. This means that you can paste doctests from
3426 and '...' prompts in them. This means that you can paste doctests from
3427 files or docstrings (even if they have leading whitespace), and the
3427 files or docstrings (even if they have leading whitespace), and the
3428 code will execute correctly. You can then use '%history -tn' to see
3428 code will execute correctly. You can then use '%history -tn' to see
3429 the translated history without line numbers; this will give you the
3429 the translated history without line numbers; this will give you the
3430 input after removal of all the leading prompts and whitespace, which
3430 input after removal of all the leading prompts and whitespace, which
3431 can be pasted back into an editor.
3431 can be pasted back into an editor.
3432
3432
3433 With these features, you can switch into this mode easily whenever you
3433 With these features, you can switch into this mode easily whenever you
3434 need to do testing and changes to doctests, without having to leave
3434 need to do testing and changes to doctests, without having to leave
3435 your existing IPython session.
3435 your existing IPython session.
3436 """
3436 """
3437
3437
3438 from IPython.utils.ipstruct import Struct
3438 from IPython.utils.ipstruct import Struct
3439
3439
3440 # Shorthands
3440 # Shorthands
3441 shell = self.shell
3441 shell = self.shell
3442 oc = shell.outputcache
3442 oc = shell.displayhook
3443 meta = shell.meta
3443 meta = shell.meta
3444 # dstore is a data store kept in the instance metadata bag to track any
3444 # dstore is a data store kept in the instance metadata bag to track any
3445 # changes we make, so we can undo them later.
3445 # changes we make, so we can undo them later.
3446 dstore = meta.setdefault('doctest_mode',Struct())
3446 dstore = meta.setdefault('doctest_mode',Struct())
3447 save_dstore = dstore.setdefault
3447 save_dstore = dstore.setdefault
3448
3448
3449 # save a few values we'll need to recover later
3449 # save a few values we'll need to recover later
3450 mode = save_dstore('mode',False)
3450 mode = save_dstore('mode',False)
3451 save_dstore('rc_pprint',shell.pprint)
3451 save_dstore('rc_pprint',shell.pprint)
3452 save_dstore('xmode',shell.InteractiveTB.mode)
3452 save_dstore('xmode',shell.InteractiveTB.mode)
3453 save_dstore('rc_separate_out',shell.separate_out)
3453 save_dstore('rc_separate_out',shell.separate_out)
3454 save_dstore('rc_separate_out2',shell.separate_out2)
3454 save_dstore('rc_separate_out2',shell.separate_out2)
3455 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3455 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3456 save_dstore('rc_separate_in',shell.separate_in)
3456 save_dstore('rc_separate_in',shell.separate_in)
3457
3457
3458 if mode == False:
3458 if mode == False:
3459 # turn on
3459 # turn on
3460 oc.prompt1.p_template = '>>> '
3460 oc.prompt1.p_template = '>>> '
3461 oc.prompt2.p_template = '... '
3461 oc.prompt2.p_template = '... '
3462 oc.prompt_out.p_template = ''
3462 oc.prompt_out.p_template = ''
3463
3463
3464 # Prompt separators like plain python
3464 # Prompt separators like plain python
3465 oc.input_sep = oc.prompt1.sep = ''
3465 oc.input_sep = oc.prompt1.sep = ''
3466 oc.output_sep = ''
3466 oc.output_sep = ''
3467 oc.output_sep2 = ''
3467 oc.output_sep2 = ''
3468
3468
3469 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3469 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3470 oc.prompt_out.pad_left = False
3470 oc.prompt_out.pad_left = False
3471
3471
3472 shell.pprint = False
3472 shell.pprint = False
3473
3473
3474 shell.magic_xmode('Plain')
3474 shell.magic_xmode('Plain')
3475
3475
3476 else:
3476 else:
3477 # turn off
3477 # turn off
3478 oc.prompt1.p_template = shell.prompt_in1
3478 oc.prompt1.p_template = shell.prompt_in1
3479 oc.prompt2.p_template = shell.prompt_in2
3479 oc.prompt2.p_template = shell.prompt_in2
3480 oc.prompt_out.p_template = shell.prompt_out
3480 oc.prompt_out.p_template = shell.prompt_out
3481
3481
3482 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3482 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3483
3483
3484 oc.output_sep = dstore.rc_separate_out
3484 oc.output_sep = dstore.rc_separate_out
3485 oc.output_sep2 = dstore.rc_separate_out2
3485 oc.output_sep2 = dstore.rc_separate_out2
3486
3486
3487 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3487 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3488 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3488 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3489
3489
3490 shell.pprint = dstore.rc_pprint
3490 shell.pprint = dstore.rc_pprint
3491
3491
3492 shell.magic_xmode(dstore.xmode)
3492 shell.magic_xmode(dstore.xmode)
3493
3493
3494 # Store new mode and inform
3494 # Store new mode and inform
3495 dstore.mode = bool(1-int(mode))
3495 dstore.mode = bool(1-int(mode))
3496 print 'Doctest mode is:',
3496 print 'Doctest mode is:',
3497 print ['OFF','ON'][dstore.mode]
3497 print ['OFF','ON'][dstore.mode]
3498
3498
3499 def magic_gui(self, parameter_s=''):
3499 def magic_gui(self, parameter_s=''):
3500 """Enable or disable IPython GUI event loop integration.
3500 """Enable or disable IPython GUI event loop integration.
3501
3501
3502 %gui [-a] [GUINAME]
3502 %gui [-a] [GUINAME]
3503
3503
3504 This magic replaces IPython's threaded shells that were activated
3504 This magic replaces IPython's threaded shells that were activated
3505 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3505 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3506 can now be enabled, disabled and swtiched at runtime and keyboard
3506 can now be enabled, disabled and swtiched at runtime and keyboard
3507 interrupts should work without any problems. The following toolkits
3507 interrupts should work without any problems. The following toolkits
3508 are supported: wxPython, PyQt4, PyGTK, and Tk::
3508 are supported: wxPython, PyQt4, PyGTK, and Tk::
3509
3509
3510 %gui wx # enable wxPython event loop integration
3510 %gui wx # enable wxPython event loop integration
3511 %gui qt4|qt # enable PyQt4 event loop integration
3511 %gui qt4|qt # enable PyQt4 event loop integration
3512 %gui gtk # enable PyGTK event loop integration
3512 %gui gtk # enable PyGTK event loop integration
3513 %gui tk # enable Tk event loop integration
3513 %gui tk # enable Tk event loop integration
3514 %gui # disable all event loop integration
3514 %gui # disable all event loop integration
3515
3515
3516 WARNING: after any of these has been called you can simply create
3516 WARNING: after any of these has been called you can simply create
3517 an application object, but DO NOT start the event loop yourself, as
3517 an application object, but DO NOT start the event loop yourself, as
3518 we have already handled that.
3518 we have already handled that.
3519
3519
3520 If you want us to create an appropriate application object add the
3520 If you want us to create an appropriate application object add the
3521 "-a" flag to your command::
3521 "-a" flag to your command::
3522
3522
3523 %gui -a wx
3523 %gui -a wx
3524
3524
3525 This is highly recommended for most users.
3525 This is highly recommended for most users.
3526 """
3526 """
3527 opts, arg = self.parse_options(parameter_s,'a')
3527 opts, arg = self.parse_options(parameter_s,'a')
3528 if arg=='': arg = None
3528 if arg=='': arg = None
3529 return enable_gui(arg, 'a' in opts)
3529 return enable_gui(arg, 'a' in opts)
3530
3530
3531 def magic_load_ext(self, module_str):
3531 def magic_load_ext(self, module_str):
3532 """Load an IPython extension by its module name."""
3532 """Load an IPython extension by its module name."""
3533 return self.extension_manager.load_extension(module_str)
3533 return self.extension_manager.load_extension(module_str)
3534
3534
3535 def magic_unload_ext(self, module_str):
3535 def magic_unload_ext(self, module_str):
3536 """Unload an IPython extension by its module name."""
3536 """Unload an IPython extension by its module name."""
3537 self.extension_manager.unload_extension(module_str)
3537 self.extension_manager.unload_extension(module_str)
3538
3538
3539 def magic_reload_ext(self, module_str):
3539 def magic_reload_ext(self, module_str):
3540 """Reload an IPython extension by its module name."""
3540 """Reload an IPython extension by its module name."""
3541 self.extension_manager.reload_extension(module_str)
3541 self.extension_manager.reload_extension(module_str)
3542
3542
3543 @testdec.skip_doctest
3543 @testdec.skip_doctest
3544 def magic_install_profiles(self, s):
3544 def magic_install_profiles(self, s):
3545 """Install the default IPython profiles into the .ipython dir.
3545 """Install the default IPython profiles into the .ipython dir.
3546
3546
3547 If the default profiles have already been installed, they will not
3547 If the default profiles have already been installed, they will not
3548 be overwritten. You can force overwriting them by using the ``-o``
3548 be overwritten. You can force overwriting them by using the ``-o``
3549 option::
3549 option::
3550
3550
3551 In [1]: %install_profiles -o
3551 In [1]: %install_profiles -o
3552 """
3552 """
3553 if '-o' in s:
3553 if '-o' in s:
3554 overwrite = True
3554 overwrite = True
3555 else:
3555 else:
3556 overwrite = False
3556 overwrite = False
3557 from IPython.config import profile
3557 from IPython.config import profile
3558 profile_dir = os.path.split(profile.__file__)[0]
3558 profile_dir = os.path.split(profile.__file__)[0]
3559 ipython_dir = self.ipython_dir
3559 ipython_dir = self.ipython_dir
3560 files = os.listdir(profile_dir)
3560 files = os.listdir(profile_dir)
3561
3561
3562 to_install = []
3562 to_install = []
3563 for f in files:
3563 for f in files:
3564 if f.startswith('ipython_config'):
3564 if f.startswith('ipython_config'):
3565 src = os.path.join(profile_dir, f)
3565 src = os.path.join(profile_dir, f)
3566 dst = os.path.join(ipython_dir, f)
3566 dst = os.path.join(ipython_dir, f)
3567 if (not os.path.isfile(dst)) or overwrite:
3567 if (not os.path.isfile(dst)) or overwrite:
3568 to_install.append((f, src, dst))
3568 to_install.append((f, src, dst))
3569 if len(to_install)>0:
3569 if len(to_install)>0:
3570 print "Installing profiles to: ", ipython_dir
3570 print "Installing profiles to: ", ipython_dir
3571 for (f, src, dst) in to_install:
3571 for (f, src, dst) in to_install:
3572 shutil.copy(src, dst)
3572 shutil.copy(src, dst)
3573 print " %s" % f
3573 print " %s" % f
3574
3574
3575 def magic_install_default_config(self, s):
3575 def magic_install_default_config(self, s):
3576 """Install IPython's default config file into the .ipython dir.
3576 """Install IPython's default config file into the .ipython dir.
3577
3577
3578 If the default config file (:file:`ipython_config.py`) is already
3578 If the default config file (:file:`ipython_config.py`) is already
3579 installed, it will not be overwritten. You can force overwriting
3579 installed, it will not be overwritten. You can force overwriting
3580 by using the ``-o`` option::
3580 by using the ``-o`` option::
3581
3581
3582 In [1]: %install_default_config
3582 In [1]: %install_default_config
3583 """
3583 """
3584 if '-o' in s:
3584 if '-o' in s:
3585 overwrite = True
3585 overwrite = True
3586 else:
3586 else:
3587 overwrite = False
3587 overwrite = False
3588 from IPython.config import default
3588 from IPython.config import default
3589 config_dir = os.path.split(default.__file__)[0]
3589 config_dir = os.path.split(default.__file__)[0]
3590 ipython_dir = self.ipython_dir
3590 ipython_dir = self.ipython_dir
3591 default_config_file_name = 'ipython_config.py'
3591 default_config_file_name = 'ipython_config.py'
3592 src = os.path.join(config_dir, default_config_file_name)
3592 src = os.path.join(config_dir, default_config_file_name)
3593 dst = os.path.join(ipython_dir, default_config_file_name)
3593 dst = os.path.join(ipython_dir, default_config_file_name)
3594 if (not os.path.isfile(dst)) or overwrite:
3594 if (not os.path.isfile(dst)) or overwrite:
3595 shutil.copy(src, dst)
3595 shutil.copy(src, dst)
3596 print "Installing default config file: %s" % dst
3596 print "Installing default config file: %s" % dst
3597
3597
3598 # Pylab support: simple wrappers that activate pylab, load gui input
3598 # Pylab support: simple wrappers that activate pylab, load gui input
3599 # handling and modify slightly %run
3599 # handling and modify slightly %run
3600
3600
3601 @testdec.skip_doctest
3601 @testdec.skip_doctest
3602 def _pylab_magic_run(self, parameter_s=''):
3602 def _pylab_magic_run(self, parameter_s=''):
3603 Magic.magic_run(self, parameter_s,
3603 Magic.magic_run(self, parameter_s,
3604 runner=mpl_runner(self.shell.safe_execfile))
3604 runner=mpl_runner(self.shell.safe_execfile))
3605
3605
3606 _pylab_magic_run.__doc__ = magic_run.__doc__
3606 _pylab_magic_run.__doc__ = magic_run.__doc__
3607
3607
3608 @testdec.skip_doctest
3608 @testdec.skip_doctest
3609 def magic_pylab(self, s):
3609 def magic_pylab(self, s):
3610 """Load numpy and matplotlib to work interactively.
3610 """Load numpy and matplotlib to work interactively.
3611
3611
3612 %pylab [GUINAME]
3612 %pylab [GUINAME]
3613
3613
3614 This function lets you activate pylab (matplotlib, numpy and
3614 This function lets you activate pylab (matplotlib, numpy and
3615 interactive support) at any point during an IPython session.
3615 interactive support) at any point during an IPython session.
3616
3616
3617 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3617 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3618 pylab and mlab, as well as all names from numpy and pylab.
3618 pylab and mlab, as well as all names from numpy and pylab.
3619
3619
3620 Parameters
3620 Parameters
3621 ----------
3621 ----------
3622 guiname : optional
3622 guiname : optional
3623 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3623 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3624 'tk'). If given, the corresponding Matplotlib backend is used,
3624 'tk'). If given, the corresponding Matplotlib backend is used,
3625 otherwise matplotlib's default (which you can override in your
3625 otherwise matplotlib's default (which you can override in your
3626 matplotlib config file) is used.
3626 matplotlib config file) is used.
3627
3627
3628 Examples
3628 Examples
3629 --------
3629 --------
3630 In this case, where the MPL default is TkAgg:
3630 In this case, where the MPL default is TkAgg:
3631 In [2]: %pylab
3631 In [2]: %pylab
3632
3632
3633 Welcome to pylab, a matplotlib-based Python environment.
3633 Welcome to pylab, a matplotlib-based Python environment.
3634 Backend in use: TkAgg
3634 Backend in use: TkAgg
3635 For more information, type 'help(pylab)'.
3635 For more information, type 'help(pylab)'.
3636
3636
3637 But you can explicitly request a different backend:
3637 But you can explicitly request a different backend:
3638 In [3]: %pylab qt
3638 In [3]: %pylab qt
3639
3639
3640 Welcome to pylab, a matplotlib-based Python environment.
3640 Welcome to pylab, a matplotlib-based Python environment.
3641 Backend in use: Qt4Agg
3641 Backend in use: Qt4Agg
3642 For more information, type 'help(pylab)'.
3642 For more information, type 'help(pylab)'.
3643 """
3643 """
3644 self.shell.enable_pylab(s)
3644 self.shell.enable_pylab(s)
3645
3645
3646 def magic_tb(self, s):
3646 def magic_tb(self, s):
3647 """Print the last traceback with the currently active exception mode.
3647 """Print the last traceback with the currently active exception mode.
3648
3648
3649 See %xmode for changing exception reporting modes."""
3649 See %xmode for changing exception reporting modes."""
3650 self.shell.showtraceback()
3650 self.shell.showtraceback()
3651
3651
3652 # end Magic
3652 # end Magic
@@ -1,1022 +1,1022 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.page import page
36 from IPython.core.page 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(cmp=lambda x,y: x.priority-y.priority)
240 self._transformers.sort(cmp=lambda x,y: x.priority-y.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(cmp=lambda x,y: x.priority-y.priority)
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.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
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
377 # needed, update the cache AND log it (so that the input cache array
378 # stays synced).
378 # stays synced).
379
379
380 # save the line away in case we crash, so the post-mortem handler can
380 # save the line away in case we crash, so the post-mortem handler can
381 # record it
381 # record it
382 self.shell._last_input_line = line
382 self.shell._last_input_line = line
383
383
384 if not line:
384 if not line:
385 # Return immediately on purely empty lines, so that if the user
385 # Return immediately on purely empty lines, so that if the user
386 # previously typed some whitespace that started a continuation
386 # previously typed some whitespace that started a continuation
387 # prompt, he can break out of that loop with just an empty line.
387 # prompt, he can break out of that loop with just an empty line.
388 # This is how the default python prompt works.
388 # This is how the default python prompt works.
389
389
390 # Only return if the accumulated input buffer was just whitespace!
390 # Only return if the accumulated input buffer was just whitespace!
391 if ''.join(self.shell.buffer).isspace():
391 if ''.join(self.shell.buffer).isspace():
392 self.shell.buffer[:] = []
392 self.shell.buffer[:] = []
393 return ''
393 return ''
394
394
395 # At this point, we invoke our transformers.
395 # At this point, we invoke our transformers.
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
397 line = self.transform_line(line, continue_prompt)
397 line = self.transform_line(line, continue_prompt)
398
398
399 # Now we compute line_info for the checkers and handlers
399 # Now we compute line_info for the checkers and handlers
400 line_info = LineInfo(line, continue_prompt)
400 line_info = LineInfo(line, continue_prompt)
401
401
402 # the input history needs to track even empty lines
402 # the input history needs to track even empty lines
403 stripped = line.strip()
403 stripped = line.strip()
404
404
405 normal_handler = self.get_handler_by_name('normal')
405 normal_handler = self.get_handler_by_name('normal')
406 if not stripped:
406 if not stripped:
407 if not continue_prompt:
407 if not continue_prompt:
408 self.shell.outputcache.prompt_count -= 1
408 self.shell.displayhook.prompt_count -= 1
409
409
410 return normal_handler.handle(line_info)
410 return normal_handler.handle(line_info)
411
411
412 # special handlers are only allowed for single line statements
412 # special handlers are only allowed for single line statements
413 if continue_prompt and not self.multi_line_specials:
413 if continue_prompt and not self.multi_line_specials:
414 return normal_handler.handle(line_info)
414 return normal_handler.handle(line_info)
415
415
416 prefiltered = self.prefilter_line_info(line_info)
416 prefiltered = self.prefilter_line_info(line_info)
417 # print "prefiltered line: %r" % prefiltered
417 # print "prefiltered line: %r" % prefiltered
418 return prefiltered
418 return prefiltered
419
419
420 def prefilter_lines(self, lines, continue_prompt=False):
420 def prefilter_lines(self, lines, continue_prompt=False):
421 """Prefilter multiple input lines of text.
421 """Prefilter multiple input lines of text.
422
422
423 This is the main entry point for prefiltering multiple lines of
423 This is the main entry point for prefiltering multiple lines of
424 input. This simply calls :meth:`prefilter_line` for each line of
424 input. This simply calls :meth:`prefilter_line` for each line of
425 input.
425 input.
426
426
427 This covers cases where there are multiple lines in the user entry,
427 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
428 which is the case when the user goes back to a multiline history
429 entry and presses enter.
429 entry and presses enter.
430 """
430 """
431 llines = lines.rstrip('\n').split('\n')
431 llines = lines.rstrip('\n').split('\n')
432 # We can get multiple lines in one shot, where multiline input 'blends'
432 # We can get multiple lines in one shot, where multiline input 'blends'
433 # into one line, in cases like recalling from the readline history
433 # into one line, in cases like recalling from the readline history
434 # buffer. We need to make sure that in such cases, we correctly
434 # buffer. We need to make sure that in such cases, we correctly
435 # communicate downstream which line is first and which are continuation
435 # communicate downstream which line is first and which are continuation
436 # ones.
436 # ones.
437 if len(llines) > 1:
437 if len(llines) > 1:
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
439 for lnum, line in enumerate(llines) ])
439 for lnum, line in enumerate(llines) ])
440 else:
440 else:
441 out = self.prefilter_line(llines[0], continue_prompt)
441 out = self.prefilter_line(llines[0], continue_prompt)
442
442
443 return out
443 return out
444
444
445 #-----------------------------------------------------------------------------
445 #-----------------------------------------------------------------------------
446 # Prefilter transformers
446 # Prefilter transformers
447 #-----------------------------------------------------------------------------
447 #-----------------------------------------------------------------------------
448
448
449
449
450 class PrefilterTransformer(Configurable):
450 class PrefilterTransformer(Configurable):
451 """Transform a line of user input."""
451 """Transform a line of user input."""
452
452
453 priority = Int(100, config=True)
453 priority = Int(100, config=True)
454 # Transformers don't currently use shell or prefilter_manager, but as we
454 # Transformers don't currently use shell or prefilter_manager, but as we
455 # move away from checkers and handlers, they will need them.
455 # move away from checkers and handlers, they will need them.
456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
458 enabled = Bool(True, config=True)
458 enabled = Bool(True, config=True)
459
459
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
461 super(PrefilterTransformer, self).__init__(
461 super(PrefilterTransformer, self).__init__(
462 shell=shell, prefilter_manager=prefilter_manager, config=config
462 shell=shell, prefilter_manager=prefilter_manager, config=config
463 )
463 )
464 self.prefilter_manager.register_transformer(self)
464 self.prefilter_manager.register_transformer(self)
465
465
466 def transform(self, line, continue_prompt):
466 def transform(self, line, continue_prompt):
467 """Transform a line, returning the new one."""
467 """Transform a line, returning the new one."""
468 return None
468 return None
469
469
470 def __repr__(self):
470 def __repr__(self):
471 return "<%s(priority=%r, enabled=%r)>" % (
471 return "<%s(priority=%r, enabled=%r)>" % (
472 self.__class__.__name__, self.priority, self.enabled)
472 self.__class__.__name__, self.priority, self.enabled)
473
473
474
474
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
476 r'\s*=\s*!(?P<cmd>.*)')
476 r'\s*=\s*!(?P<cmd>.*)')
477
477
478
478
479 class AssignSystemTransformer(PrefilterTransformer):
479 class AssignSystemTransformer(PrefilterTransformer):
480 """Handle the `files = !ls` syntax."""
480 """Handle the `files = !ls` syntax."""
481
481
482 priority = Int(100, config=True)
482 priority = Int(100, config=True)
483
483
484 def transform(self, line, continue_prompt):
484 def transform(self, line, continue_prompt):
485 m = _assign_system_re.match(line)
485 m = _assign_system_re.match(line)
486 if m is not None:
486 if m is not None:
487 cmd = m.group('cmd')
487 cmd = m.group('cmd')
488 lhs = m.group('lhs')
488 lhs = m.group('lhs')
489 expr = make_quoted_expr("sc -l =%s" % cmd)
489 expr = make_quoted_expr("sc -l =%s" % cmd)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
491 return new_line
491 return new_line
492 return line
492 return line
493
493
494
494
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
496 r'\s*=\s*%(?P<cmd>.*)')
496 r'\s*=\s*%(?P<cmd>.*)')
497
497
498 class AssignMagicTransformer(PrefilterTransformer):
498 class AssignMagicTransformer(PrefilterTransformer):
499 """Handle the `a = %who` syntax."""
499 """Handle the `a = %who` syntax."""
500
500
501 priority = Int(200, config=True)
501 priority = Int(200, config=True)
502
502
503 def transform(self, line, continue_prompt):
503 def transform(self, line, continue_prompt):
504 m = _assign_magic_re.match(line)
504 m = _assign_magic_re.match(line)
505 if m is not None:
505 if m is not None:
506 cmd = m.group('cmd')
506 cmd = m.group('cmd')
507 lhs = m.group('lhs')
507 lhs = m.group('lhs')
508 expr = make_quoted_expr(cmd)
508 expr = make_quoted_expr(cmd)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
510 return new_line
510 return new_line
511 return line
511 return line
512
512
513
513
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
515
515
516 class PyPromptTransformer(PrefilterTransformer):
516 class PyPromptTransformer(PrefilterTransformer):
517 """Handle inputs that start with '>>> ' syntax."""
517 """Handle inputs that start with '>>> ' syntax."""
518
518
519 priority = Int(50, config=True)
519 priority = Int(50, config=True)
520
520
521 def transform(self, line, continue_prompt):
521 def transform(self, line, continue_prompt):
522
522
523 if not line or line.isspace() or line.strip() == '...':
523 if not line or line.isspace() or line.strip() == '...':
524 # This allows us to recognize multiple input prompts separated by
524 # This allows us to recognize multiple input prompts separated by
525 # blank lines and pasted in a single chunk, very common when
525 # blank lines and pasted in a single chunk, very common when
526 # pasting doctests or long tutorial passages.
526 # pasting doctests or long tutorial passages.
527 return ''
527 return ''
528 m = _classic_prompt_re.match(line)
528 m = _classic_prompt_re.match(line)
529 if m:
529 if m:
530 return line[len(m.group(0)):]
530 return line[len(m.group(0)):]
531 else:
531 else:
532 return line
532 return line
533
533
534
534
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
536
536
537 class IPyPromptTransformer(PrefilterTransformer):
537 class IPyPromptTransformer(PrefilterTransformer):
538 """Handle inputs that start classic IPython prompt syntax."""
538 """Handle inputs that start classic IPython prompt syntax."""
539
539
540 priority = Int(50, config=True)
540 priority = Int(50, config=True)
541
541
542 def transform(self, line, continue_prompt):
542 def transform(self, line, continue_prompt):
543
543
544 if not line or line.isspace() or line.strip() == '...':
544 if not line or line.isspace() or line.strip() == '...':
545 # This allows us to recognize multiple input prompts separated by
545 # This allows us to recognize multiple input prompts separated by
546 # blank lines and pasted in a single chunk, very common when
546 # blank lines and pasted in a single chunk, very common when
547 # pasting doctests or long tutorial passages.
547 # pasting doctests or long tutorial passages.
548 return ''
548 return ''
549 m = _ipy_prompt_re.match(line)
549 m = _ipy_prompt_re.match(line)
550 if m:
550 if m:
551 return line[len(m.group(0)):]
551 return line[len(m.group(0)):]
552 else:
552 else:
553 return line
553 return line
554
554
555 #-----------------------------------------------------------------------------
555 #-----------------------------------------------------------------------------
556 # Prefilter checkers
556 # Prefilter checkers
557 #-----------------------------------------------------------------------------
557 #-----------------------------------------------------------------------------
558
558
559
559
560 class PrefilterChecker(Configurable):
560 class PrefilterChecker(Configurable):
561 """Inspect an input line and return a handler for that line."""
561 """Inspect an input line and return a handler for that line."""
562
562
563 priority = Int(100, config=True)
563 priority = Int(100, config=True)
564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
566 enabled = Bool(True, config=True)
566 enabled = Bool(True, config=True)
567
567
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
569 super(PrefilterChecker, self).__init__(
569 super(PrefilterChecker, self).__init__(
570 shell=shell, prefilter_manager=prefilter_manager, config=config
570 shell=shell, prefilter_manager=prefilter_manager, config=config
571 )
571 )
572 self.prefilter_manager.register_checker(self)
572 self.prefilter_manager.register_checker(self)
573
573
574 def check(self, line_info):
574 def check(self, line_info):
575 """Inspect line_info and return a handler instance or None."""
575 """Inspect line_info and return a handler instance or None."""
576 return None
576 return None
577
577
578 def __repr__(self):
578 def __repr__(self):
579 return "<%s(priority=%r, enabled=%r)>" % (
579 return "<%s(priority=%r, enabled=%r)>" % (
580 self.__class__.__name__, self.priority, self.enabled)
580 self.__class__.__name__, self.priority, self.enabled)
581
581
582
582
583 class EmacsChecker(PrefilterChecker):
583 class EmacsChecker(PrefilterChecker):
584
584
585 priority = Int(100, config=True)
585 priority = Int(100, config=True)
586 enabled = Bool(False, config=True)
586 enabled = Bool(False, config=True)
587
587
588 def check(self, line_info):
588 def check(self, line_info):
589 "Emacs ipython-mode tags certain input lines."
589 "Emacs ipython-mode tags certain input lines."
590 if line_info.line.endswith('# PYTHON-MODE'):
590 if line_info.line.endswith('# PYTHON-MODE'):
591 return self.prefilter_manager.get_handler_by_name('emacs')
591 return self.prefilter_manager.get_handler_by_name('emacs')
592 else:
592 else:
593 return None
593 return None
594
594
595
595
596 class ShellEscapeChecker(PrefilterChecker):
596 class ShellEscapeChecker(PrefilterChecker):
597
597
598 priority = Int(200, config=True)
598 priority = Int(200, config=True)
599
599
600 def check(self, line_info):
600 def check(self, line_info):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
602 return self.prefilter_manager.get_handler_by_name('shell')
602 return self.prefilter_manager.get_handler_by_name('shell')
603
603
604
604
605 class IPyAutocallChecker(PrefilterChecker):
605 class IPyAutocallChecker(PrefilterChecker):
606
606
607 priority = Int(300, config=True)
607 priority = Int(300, config=True)
608
608
609 def check(self, line_info):
609 def check(self, line_info):
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
611 obj = self.shell.user_ns.get(line_info.ifun, None)
611 obj = self.shell.user_ns.get(line_info.ifun, None)
612 if isinstance(obj, IPyAutocall):
612 if isinstance(obj, IPyAutocall):
613 obj.set_ip(self.shell)
613 obj.set_ip(self.shell)
614 return self.prefilter_manager.get_handler_by_name('auto')
614 return self.prefilter_manager.get_handler_by_name('auto')
615 else:
615 else:
616 return None
616 return None
617
617
618
618
619 class MultiLineMagicChecker(PrefilterChecker):
619 class MultiLineMagicChecker(PrefilterChecker):
620
620
621 priority = Int(400, config=True)
621 priority = Int(400, config=True)
622
622
623 def check(self, line_info):
623 def check(self, line_info):
624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
624 "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
625 # 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
626 # ifun and *not* the pre_char. Also note that the below test matches
627 # both ! and !!.
627 # both ! and !!.
628 if line_info.continue_prompt \
628 if line_info.continue_prompt \
629 and self.prefilter_manager.multi_line_specials:
629 and self.prefilter_manager.multi_line_specials:
630 if line_info.ifun.startswith(ESC_MAGIC):
630 if line_info.ifun.startswith(ESC_MAGIC):
631 return self.prefilter_manager.get_handler_by_name('magic')
631 return self.prefilter_manager.get_handler_by_name('magic')
632 else:
632 else:
633 return None
633 return None
634
634
635
635
636 class EscCharsChecker(PrefilterChecker):
636 class EscCharsChecker(PrefilterChecker):
637
637
638 priority = Int(500, config=True)
638 priority = Int(500, config=True)
639
639
640 def check(self, line_info):
640 def check(self, line_info):
641 """Check for escape character and return either a handler to handle it,
641 """Check for escape character and return either a handler to handle it,
642 or None if there is no escape char."""
642 or None if there is no escape char."""
643 if line_info.line[-1] == ESC_HELP \
643 if line_info.line[-1] == ESC_HELP \
644 and line_info.pre_char != ESC_SHELL \
644 and line_info.pre_char != ESC_SHELL \
645 and line_info.pre_char != ESC_SH_CAP:
645 and line_info.pre_char != ESC_SH_CAP:
646 # the ? can be at the end, but *not* for either kind of shell escape,
646 # 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
647 # because a ? can be a vaild final char in a shell cmd
648 return self.prefilter_manager.get_handler_by_name('help')
648 return self.prefilter_manager.get_handler_by_name('help')
649 else:
649 else:
650 # This returns None like it should if no handler exists
650 # This returns None like it should if no handler exists
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
652
652
653
653
654 class AssignmentChecker(PrefilterChecker):
654 class AssignmentChecker(PrefilterChecker):
655
655
656 priority = Int(600, config=True)
656 priority = Int(600, config=True)
657
657
658 def check(self, line_info):
658 def check(self, line_info):
659 """Check to see if user is assigning to a var for the first time, in
659 """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.
660 which case we want to avoid any sort of automagic / autocall games.
661
661
662 This allows users to assign to either alias or magic names true python
662 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
663 variables (the magic/alias systems always take second seat to true
664 python code). E.g. ls='hi', or ls,that=1,2"""
664 python code). E.g. ls='hi', or ls,that=1,2"""
665 if line_info.the_rest:
665 if line_info.the_rest:
666 if line_info.the_rest[0] in '=,':
666 if line_info.the_rest[0] in '=,':
667 return self.prefilter_manager.get_handler_by_name('normal')
667 return self.prefilter_manager.get_handler_by_name('normal')
668 else:
668 else:
669 return None
669 return None
670
670
671
671
672 class AutoMagicChecker(PrefilterChecker):
672 class AutoMagicChecker(PrefilterChecker):
673
673
674 priority = Int(700, config=True)
674 priority = Int(700, config=True)
675
675
676 def check(self, line_info):
676 def check(self, line_info):
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
678 non-auto magic would already have been triggered via '%' in
678 non-auto magic would already have been triggered via '%' in
679 check_esc_chars. This just checks for automagic. Also, before
679 check_esc_chars. This just checks for automagic. Also, before
680 triggering the magic handler, make sure that there is nothing in the
680 triggering the magic handler, make sure that there is nothing in the
681 user namespace which could shadow it."""
681 user namespace which could shadow it."""
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
683 return None
683 return None
684
684
685 # We have a likely magic method. Make sure we should actually call it.
685 # 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:
686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
687 return None
687 return None
688
688
689 head = line_info.ifun.split('.',1)[0]
689 head = line_info.ifun.split('.',1)[0]
690 if is_shadowed(head, self.shell):
690 if is_shadowed(head, self.shell):
691 return None
691 return None
692
692
693 return self.prefilter_manager.get_handler_by_name('magic')
693 return self.prefilter_manager.get_handler_by_name('magic')
694
694
695
695
696 class AliasChecker(PrefilterChecker):
696 class AliasChecker(PrefilterChecker):
697
697
698 priority = Int(800, config=True)
698 priority = Int(800, config=True)
699
699
700 def check(self, line_info):
700 def check(self, line_info):
701 "Check if the initital identifier on the line is an alias."
701 "Check if the initital identifier on the line is an alias."
702 # Note: aliases can not contain '.'
702 # Note: aliases can not contain '.'
703 head = line_info.ifun.split('.',1)[0]
703 head = line_info.ifun.split('.',1)[0]
704 if line_info.ifun not in self.shell.alias_manager \
704 if line_info.ifun not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
706 or is_shadowed(head, self.shell):
706 or is_shadowed(head, self.shell):
707 return None
707 return None
708
708
709 return self.prefilter_manager.get_handler_by_name('alias')
709 return self.prefilter_manager.get_handler_by_name('alias')
710
710
711
711
712 class PythonOpsChecker(PrefilterChecker):
712 class PythonOpsChecker(PrefilterChecker):
713
713
714 priority = Int(900, config=True)
714 priority = Int(900, config=True)
715
715
716 def check(self, line_info):
716 def check(self, line_info):
717 """If the 'rest' of the line begins with a function call or pretty much
717 """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
718 any python operator, we should simply execute the line (regardless of
719 whether or not there's a possible autocall expansion). This avoids
719 whether or not there's a possible autocall expansion). This avoids
720 spurious (and very confusing) geattr() accesses."""
720 spurious (and very confusing) geattr() accesses."""
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
722 return self.prefilter_manager.get_handler_by_name('normal')
722 return self.prefilter_manager.get_handler_by_name('normal')
723 else:
723 else:
724 return None
724 return None
725
725
726
726
727 class AutocallChecker(PrefilterChecker):
727 class AutocallChecker(PrefilterChecker):
728
728
729 priority = Int(1000, config=True)
729 priority = Int(1000, config=True)
730
730
731 def check(self, line_info):
731 def check(self, line_info):
732 "Check if the initial word/function is callable and autocall is on."
732 "Check if the initial word/function is callable and autocall is on."
733 if not self.shell.autocall:
733 if not self.shell.autocall:
734 return None
734 return None
735
735
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
737 if not oinfo['found']:
737 if not oinfo['found']:
738 return None
738 return None
739
739
740 if callable(oinfo['obj']) \
740 if callable(oinfo['obj']) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
742 and re_fun_name.match(line_info.ifun):
742 and re_fun_name.match(line_info.ifun):
743 return self.prefilter_manager.get_handler_by_name('auto')
743 return self.prefilter_manager.get_handler_by_name('auto')
744 else:
744 else:
745 return None
745 return None
746
746
747
747
748 #-----------------------------------------------------------------------------
748 #-----------------------------------------------------------------------------
749 # Prefilter handlers
749 # Prefilter handlers
750 #-----------------------------------------------------------------------------
750 #-----------------------------------------------------------------------------
751
751
752
752
753 class PrefilterHandler(Configurable):
753 class PrefilterHandler(Configurable):
754
754
755 handler_name = Str('normal')
755 handler_name = Str('normal')
756 esc_strings = List([])
756 esc_strings = List([])
757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
759
759
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
761 super(PrefilterHandler, self).__init__(
761 super(PrefilterHandler, self).__init__(
762 shell=shell, prefilter_manager=prefilter_manager, config=config
762 shell=shell, prefilter_manager=prefilter_manager, config=config
763 )
763 )
764 self.prefilter_manager.register_handler(
764 self.prefilter_manager.register_handler(
765 self.handler_name,
765 self.handler_name,
766 self,
766 self,
767 self.esc_strings
767 self.esc_strings
768 )
768 )
769
769
770 def handle(self, line_info):
770 def handle(self, line_info):
771 # print "normal: ", line_info
771 # print "normal: ", line_info
772 """Handle normal input lines. Use as a template for handlers."""
772 """Handle normal input lines. Use as a template for handlers."""
773
773
774 # With autoindent on, we need some way to exit the input loop, and I
774 # 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
775 # 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
776 # 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
777 # 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.
778 # of a size different to the indent level, will exit the input loop.
779 line = line_info.line
779 line = line_info.line
780 continue_prompt = line_info.continue_prompt
780 continue_prompt = line_info.continue_prompt
781
781
782 if (continue_prompt and
782 if (continue_prompt and
783 self.shell.autoindent and
783 self.shell.autoindent and
784 line.isspace() and
784 line.isspace() and
785
785
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
787 or
787 or
788 not self.shell.buffer
788 not self.shell.buffer
789 or
789 or
790 (self.shell.buffer[-1]).isspace()
790 (self.shell.buffer[-1]).isspace()
791 )
791 )
792 ):
792 ):
793 line = ''
793 line = ''
794
794
795 self.shell.log(line, line, continue_prompt)
795 self.shell.log(line, line, continue_prompt)
796 return line
796 return line
797
797
798 def __str__(self):
798 def __str__(self):
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
800
800
801
801
802 class AliasHandler(PrefilterHandler):
802 class AliasHandler(PrefilterHandler):
803
803
804 handler_name = Str('alias')
804 handler_name = Str('alias')
805
805
806 def handle(self, line_info):
806 def handle(self, line_info):
807 """Handle alias input lines. """
807 """Handle alias input lines. """
808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
808 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
809 # pre is needed, because it carries the leading whitespace. Otherwise
810 # aliases won't work in indented sections.
810 # aliases won't work in indented sections.
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
812 make_quoted_expr(transformed))
812 make_quoted_expr(transformed))
813
813
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
815 return line_out
815 return line_out
816
816
817
817
818 class ShellEscapeHandler(PrefilterHandler):
818 class ShellEscapeHandler(PrefilterHandler):
819
819
820 handler_name = Str('shell')
820 handler_name = Str('shell')
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
822
822
823 def handle(self, line_info):
823 def handle(self, line_info):
824 """Execute the line in a shell, empty return value"""
824 """Execute the line in a shell, empty return value"""
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
826
826
827 line = line_info.line
827 line = line_info.line
828 if line.lstrip().startswith(ESC_SH_CAP):
828 if line.lstrip().startswith(ESC_SH_CAP):
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
830 # call to %sx and the actual command to be executed, so
830 # call to %sx and the actual command to be executed, so
831 # handle_magic can work correctly. Note that this works even if
831 # handle_magic can work correctly. Note that this works even if
832 # the line is indented, so it handles multi_line_specials
832 # the line is indented, so it handles multi_line_specials
833 # properly.
833 # properly.
834 new_rest = line.lstrip()[2:]
834 new_rest = line.lstrip()[2:]
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
836 line_info.ifun = 'sx'
836 line_info.ifun = 'sx'
837 line_info.the_rest = new_rest
837 line_info.the_rest = new_rest
838 return magic_handler.handle(line_info)
838 return magic_handler.handle(line_info)
839 else:
839 else:
840 cmd = line.lstrip().lstrip(ESC_SHELL)
840 cmd = line.lstrip().lstrip(ESC_SHELL)
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
842 make_quoted_expr(cmd))
842 make_quoted_expr(cmd))
843 # update cache/log and return
843 # update cache/log and return
844 self.shell.log(line, line_out, line_info.continue_prompt)
844 self.shell.log(line, line_out, line_info.continue_prompt)
845 return line_out
845 return line_out
846
846
847
847
848 class MagicHandler(PrefilterHandler):
848 class MagicHandler(PrefilterHandler):
849
849
850 handler_name = Str('magic')
850 handler_name = Str('magic')
851 esc_strings = List([ESC_MAGIC])
851 esc_strings = List([ESC_MAGIC])
852
852
853 def handle(self, line_info):
853 def handle(self, line_info):
854 """Execute magic functions."""
854 """Execute magic functions."""
855 ifun = line_info.ifun
855 ifun = line_info.ifun
856 the_rest = line_info.the_rest
856 the_rest = line_info.the_rest
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
858 make_quoted_expr(ifun + " " + the_rest))
858 make_quoted_expr(ifun + " " + the_rest))
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
860 return cmd
860 return cmd
861
861
862
862
863 class AutoHandler(PrefilterHandler):
863 class AutoHandler(PrefilterHandler):
864
864
865 handler_name = Str('auto')
865 handler_name = Str('auto')
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
867
867
868 def handle(self, line_info):
868 def handle(self, line_info):
869 """Handle lines which can be auto-executed, quoting if requested."""
869 """Handle lines which can be auto-executed, quoting if requested."""
870 line = line_info.line
870 line = line_info.line
871 ifun = line_info.ifun
871 ifun = line_info.ifun
872 the_rest = line_info.the_rest
872 the_rest = line_info.the_rest
873 pre = line_info.pre
873 pre = line_info.pre
874 continue_prompt = line_info.continue_prompt
874 continue_prompt = line_info.continue_prompt
875 obj = line_info.ofind(self)['obj']
875 obj = line_info.ofind(self)['obj']
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
877
877
878 # This should only be active for single-line input!
878 # This should only be active for single-line input!
879 if continue_prompt:
879 if continue_prompt:
880 self.shell.log(line,line,continue_prompt)
880 self.shell.log(line,line,continue_prompt)
881 return line
881 return line
882
882
883 force_auto = isinstance(obj, IPyAutocall)
883 force_auto = isinstance(obj, IPyAutocall)
884 auto_rewrite = True
884 auto_rewrite = True
885
885
886 if pre == ESC_QUOTE:
886 if pre == ESC_QUOTE:
887 # Auto-quote splitting on whitespace
887 # Auto-quote splitting on whitespace
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 elif pre == ESC_QUOTE2:
889 elif pre == ESC_QUOTE2:
890 # Auto-quote whole string
890 # Auto-quote whole string
891 newcmd = '%s("%s")' % (ifun,the_rest)
891 newcmd = '%s("%s")' % (ifun,the_rest)
892 elif pre == ESC_PAREN:
892 elif pre == ESC_PAREN:
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 else:
894 else:
895 # Auto-paren.
895 # Auto-paren.
896 # We only apply it to argument-less calls if the autocall
896 # 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 <
897 # 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.
898 # 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:
899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 newcmd = '%s %s' % (ifun,the_rest)
900 newcmd = '%s %s' % (ifun,the_rest)
901 auto_rewrite = False
901 auto_rewrite = False
902 else:
902 else:
903 if not force_auto and the_rest.startswith('['):
903 if not force_auto and the_rest.startswith('['):
904 if hasattr(obj,'__getitem__'):
904 if hasattr(obj,'__getitem__'):
905 # Don't autocall in this case: item access for an object
905 # Don't autocall in this case: item access for an object
906 # which is BOTH callable and implements __getitem__.
906 # which is BOTH callable and implements __getitem__.
907 newcmd = '%s %s' % (ifun,the_rest)
907 newcmd = '%s %s' % (ifun,the_rest)
908 auto_rewrite = False
908 auto_rewrite = False
909 else:
909 else:
910 # if the object doesn't support [] access, go ahead and
910 # if the object doesn't support [] access, go ahead and
911 # autocall
911 # autocall
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 elif the_rest.endswith(';'):
913 elif the_rest.endswith(';'):
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 else:
915 else:
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917
917
918 if auto_rewrite:
918 if auto_rewrite:
919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
919 rw = self.shell.displayhook.prompt1.auto_rewrite() + newcmd
920
920
921 try:
921 try:
922 # plain ascii works better w/ pyreadline, on some machines, so
922 # plain ascii works better w/ pyreadline, on some machines, so
923 # we use it and only print uncolored rewrite if we have unicode
923 # we use it and only print uncolored rewrite if we have unicode
924 rw = str(rw)
924 rw = str(rw)
925 print >>IPython.utils.io.Term.cout, rw
925 print >>IPython.utils.io.Term.cout, rw
926 except UnicodeEncodeError:
926 except UnicodeEncodeError:
927 print "-------------->" + newcmd
927 print "-------------->" + newcmd
928
928
929 # log what is now valid Python, not the actual user input (without the
929 # log what is now valid Python, not the actual user input (without the
930 # final newline)
930 # final newline)
931 self.shell.log(line,newcmd,continue_prompt)
931 self.shell.log(line,newcmd,continue_prompt)
932 return newcmd
932 return newcmd
933
933
934
934
935 class HelpHandler(PrefilterHandler):
935 class HelpHandler(PrefilterHandler):
936
936
937 handler_name = Str('help')
937 handler_name = Str('help')
938 esc_strings = List([ESC_HELP])
938 esc_strings = List([ESC_HELP])
939
939
940 def handle(self, line_info):
940 def handle(self, line_info):
941 """Try to get some help for the object.
941 """Try to get some help for the object.
942
942
943 obj? or ?obj -> basic information.
943 obj? or ?obj -> basic information.
944 obj?? or ??obj -> more details.
944 obj?? or ??obj -> more details.
945 """
945 """
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
947 line = line_info.line
947 line = line_info.line
948 # We need to make sure that we don't process lines which would be
948 # We need to make sure that we don't process lines which would be
949 # otherwise valid python, such as "x=1 # what?"
949 # otherwise valid python, such as "x=1 # what?"
950 try:
950 try:
951 codeop.compile_command(line)
951 codeop.compile_command(line)
952 except SyntaxError:
952 except SyntaxError:
953 # We should only handle as help stuff which is NOT valid syntax
953 # We should only handle as help stuff which is NOT valid syntax
954 if line[0]==ESC_HELP:
954 if line[0]==ESC_HELP:
955 line = line[1:]
955 line = line[1:]
956 elif line[-1]==ESC_HELP:
956 elif line[-1]==ESC_HELP:
957 line = line[:-1]
957 line = line[:-1]
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
959 if line:
959 if line:
960 #print 'line:<%r>' % line # dbg
960 #print 'line:<%r>' % line # dbg
961 self.shell.magic_pinfo(line)
961 self.shell.magic_pinfo(line)
962 else:
962 else:
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
964 return '' # Empty string is needed here!
964 return '' # Empty string is needed here!
965 except:
965 except:
966 raise
966 raise
967 # Pass any other exceptions through to the normal handler
967 # Pass any other exceptions through to the normal handler
968 return normal_handler.handle(line_info)
968 return normal_handler.handle(line_info)
969 else:
969 else:
970 # If the code compiles ok, we should handle it normally
970 # If the code compiles ok, we should handle it normally
971 return normal_handler.handle(line_info)
971 return normal_handler.handle(line_info)
972
972
973
973
974 class EmacsHandler(PrefilterHandler):
974 class EmacsHandler(PrefilterHandler):
975
975
976 handler_name = Str('emacs')
976 handler_name = Str('emacs')
977 esc_strings = List([])
977 esc_strings = List([])
978
978
979 def handle(self, line_info):
979 def handle(self, line_info):
980 """Handle input lines marked by python-mode."""
980 """Handle input lines marked by python-mode."""
981
981
982 # Currently, nothing is done. Later more functionality can be added
982 # Currently, nothing is done. Later more functionality can be added
983 # here if needed.
983 # here if needed.
984
984
985 # The input cache shouldn't be updated
985 # The input cache shouldn't be updated
986 return line_info.line
986 return line_info.line
987
987
988
988
989 #-----------------------------------------------------------------------------
989 #-----------------------------------------------------------------------------
990 # Defaults
990 # Defaults
991 #-----------------------------------------------------------------------------
991 #-----------------------------------------------------------------------------
992
992
993
993
994 _default_transformers = [
994 _default_transformers = [
995 AssignSystemTransformer,
995 AssignSystemTransformer,
996 AssignMagicTransformer,
996 AssignMagicTransformer,
997 PyPromptTransformer,
997 PyPromptTransformer,
998 IPyPromptTransformer,
998 IPyPromptTransformer,
999 ]
999 ]
1000
1000
1001 _default_checkers = [
1001 _default_checkers = [
1002 EmacsChecker,
1002 EmacsChecker,
1003 ShellEscapeChecker,
1003 ShellEscapeChecker,
1004 IPyAutocallChecker,
1004 IPyAutocallChecker,
1005 MultiLineMagicChecker,
1005 MultiLineMagicChecker,
1006 EscCharsChecker,
1006 EscCharsChecker,
1007 AssignmentChecker,
1007 AssignmentChecker,
1008 AutoMagicChecker,
1008 AutoMagicChecker,
1009 AliasChecker,
1009 AliasChecker,
1010 PythonOpsChecker,
1010 PythonOpsChecker,
1011 AutocallChecker
1011 AutocallChecker
1012 ]
1012 ]
1013
1013
1014 _default_handlers = [
1014 _default_handlers = [
1015 PrefilterHandler,
1015 PrefilterHandler,
1016 AliasHandler,
1016 AliasHandler,
1017 ShellEscapeHandler,
1017 ShellEscapeHandler,
1018 MagicHandler,
1018 MagicHandler,
1019 AutoHandler,
1019 AutoHandler,
1020 HelpHandler,
1020 HelpHandler,
1021 EmacsHandler
1021 EmacsHandler
1022 ]
1022 ]
@@ -1,639 +1,437 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
3
4 Authors:
5
6 * Fernando Perez
7 * Brian Granger
4 """
8 """
5
9
6 #*****************************************************************************
10 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2010 The IPython Development Team
8 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
9 #
13 #
10 # 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
11 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
16 #-----------------------------------------------------------------------------
13
17
14 #****************************************************************************
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
15
21
16 import __builtin__
17 import os
22 import os
18 import re
23 import re
19 import socket
24 import socket
20 import sys
25 import sys
21
26
22 from IPython.core import release
27 from IPython.core import release
23 from IPython.external.Itpl import ItplNS
28 from IPython.external.Itpl import ItplNS
24 from IPython.core.error import TryNext
25 from IPython.utils import coloransi
29 from IPython.utils import coloransi
26 import IPython.utils.generics
27 from IPython.utils.warn import warn
28 import IPython.utils.io
29
30
30 #****************************************************************************
31 #-----------------------------------------------------------------------------
31 #Color schemes for Prompts.
32 # Color schemes for prompts
33 #-----------------------------------------------------------------------------
32
34
33 PromptColors = coloransi.ColorSchemeTable()
35 PromptColors = coloransi.ColorSchemeTable()
34 InputColors = coloransi.InputTermColors # just a shorthand
36 InputColors = coloransi.InputTermColors # just a shorthand
35 Colors = coloransi.TermColors # just a shorthand
37 Colors = coloransi.TermColors # just a shorthand
36
38
37 PromptColors.add_scheme(coloransi.ColorScheme(
39 PromptColors.add_scheme(coloransi.ColorScheme(
38 'NoColor',
40 'NoColor',
39 in_prompt = InputColors.NoColor, # Input prompt
41 in_prompt = InputColors.NoColor, # Input prompt
40 in_number = InputColors.NoColor, # Input prompt number
42 in_number = InputColors.NoColor, # Input prompt number
41 in_prompt2 = InputColors.NoColor, # Continuation prompt
43 in_prompt2 = InputColors.NoColor, # Continuation prompt
42 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
44 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
43
45
44 out_prompt = Colors.NoColor, # Output prompt
46 out_prompt = Colors.NoColor, # Output prompt
45 out_number = Colors.NoColor, # Output prompt number
47 out_number = Colors.NoColor, # Output prompt number
46
48
47 normal = Colors.NoColor # color off (usu. Colors.Normal)
49 normal = Colors.NoColor # color off (usu. Colors.Normal)
48 ))
50 ))
49
51
50 # 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:
51 __PColLinux = coloransi.ColorScheme(
53 __PColLinux = coloransi.ColorScheme(
52 'Linux',
54 'Linux',
53 in_prompt = InputColors.Green,
55 in_prompt = InputColors.Green,
54 in_number = InputColors.LightGreen,
56 in_number = InputColors.LightGreen,
55 in_prompt2 = InputColors.Green,
57 in_prompt2 = InputColors.Green,
56 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
57
59
58 out_prompt = Colors.Red,
60 out_prompt = Colors.Red,
59 out_number = Colors.LightRed,
61 out_number = Colors.LightRed,
60
62
61 normal = Colors.Normal
63 normal = Colors.Normal
62 )
64 )
63 # Don't forget to enter it into the table!
65 # Don't forget to enter it into the table!
64 PromptColors.add_scheme(__PColLinux)
66 PromptColors.add_scheme(__PColLinux)
65
67
66 # Slightly modified Linux for light backgrounds
68 # Slightly modified Linux for light backgrounds
67 __PColLightBG = __PColLinux.copy('LightBG')
69 __PColLightBG = __PColLinux.copy('LightBG')
68
70
69 __PColLightBG.colors.update(
71 __PColLightBG.colors.update(
70 in_prompt = InputColors.Blue,
72 in_prompt = InputColors.Blue,
71 in_number = InputColors.LightBlue,
73 in_number = InputColors.LightBlue,
72 in_prompt2 = InputColors.Blue
74 in_prompt2 = InputColors.Blue
73 )
75 )
74 PromptColors.add_scheme(__PColLightBG)
76 PromptColors.add_scheme(__PColLightBG)
75
77
76 del Colors,InputColors
78 del Colors,InputColors
77
79
78 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Utilities
82 #-----------------------------------------------------------------------------
83
79 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
80 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
81 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
82
87
83 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
84 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
85
90
86 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
87 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
88 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
89 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)
90
95
91 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
92 # 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 #-----------------------------------------------------------------------------
93
99
94 # 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
95 # 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
96 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # reasonable directory name will do, we just want the $HOME -> '~' operation
97 # 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
98 # prompt call.
104 # prompt call.
99
105
100 # FIXME:
106 # FIXME:
101
107
102 # - 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,
103 # 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.
104 # 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
105 # below.
111 # below.
106
112
107 # - 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
108 # 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.
109
115
110 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
111
117
112 # 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
113 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # fixed once ipython starts. This reduces the runtime overhead of computing
114 # prompt strings.
120 # prompt strings.
115 USER = os.environ.get("USER")
121 USER = os.environ.get("USER")
116 HOSTNAME = socket.gethostname()
122 HOSTNAME = socket.gethostname()
117 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
118 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
119
125
120 prompt_specials_color = {
126 prompt_specials_color = {
121 # Prompt/history count
127 # Prompt/history count
122 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
123 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
124 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
130 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
125 # can get numbers displayed in whatever color they want.
131 # can get numbers displayed in whatever color they want.
126 r'\N': '${self.cache.prompt_count}',
132 r'\N': '${self.cache.prompt_count}',
127
133
128 # Prompt/history count, with the actual digits replaced by dots. Used
134 # Prompt/history count, with the actual digits replaced by dots. Used
129 # mainly in continuation prompts (prompt_in2)
135 # mainly in continuation prompts (prompt_in2)
130 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
136 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
131
137
132 # More robust form of the above expression, that uses the __builtin__
138 # More robust form of the above expression, that uses the __builtin__
133 # 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
134 # 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,
135 # depending on the context (Python makes no guarantees on it). In
141 # depending on the context (Python makes no guarantees on it). In
136 # contrast, __builtin__ is always a module object, though it must be
142 # contrast, __builtin__ is always a module object, though it must be
137 # explicitly imported.
143 # explicitly imported.
138 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
144 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
139
145
140 # Current working directory
146 # Current working directory
141 r'\w': '${os.getcwd()}',
147 r'\w': '${os.getcwd()}',
142 # Current time
148 # Current time
143 r'\t' : '${time.strftime("%H:%M:%S")}',
149 r'\t' : '${time.strftime("%H:%M:%S")}',
144 # Basename of current working directory.
150 # Basename of current working directory.
145 # (use os.sep to make this portable across OSes)
151 # (use os.sep to make this portable across OSes)
146 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
152 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
147 # 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
148 # N terms of the path, after replacing $HOME with '~'
154 # N terms of the path, after replacing $HOME with '~'
149 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
155 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
150 r'\X1': '${self.cwd_filt(1)}',
156 r'\X1': '${self.cwd_filt(1)}',
151 r'\X2': '${self.cwd_filt(2)}',
157 r'\X2': '${self.cwd_filt(2)}',
152 r'\X3': '${self.cwd_filt(3)}',
158 r'\X3': '${self.cwd_filt(3)}',
153 r'\X4': '${self.cwd_filt(4)}',
159 r'\X4': '${self.cwd_filt(4)}',
154 r'\X5': '${self.cwd_filt(5)}',
160 r'\X5': '${self.cwd_filt(5)}',
155 # 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
156 # N+1 in the list. Somewhat like %cN in tcsh.
162 # N+1 in the list. Somewhat like %cN in tcsh.
157 r'\Y0': '${self.cwd_filt2(0)}',
163 r'\Y0': '${self.cwd_filt2(0)}',
158 r'\Y1': '${self.cwd_filt2(1)}',
164 r'\Y1': '${self.cwd_filt2(1)}',
159 r'\Y2': '${self.cwd_filt2(2)}',
165 r'\Y2': '${self.cwd_filt2(2)}',
160 r'\Y3': '${self.cwd_filt2(3)}',
166 r'\Y3': '${self.cwd_filt2(3)}',
161 r'\Y4': '${self.cwd_filt2(4)}',
167 r'\Y4': '${self.cwd_filt2(4)}',
162 r'\Y5': '${self.cwd_filt2(5)}',
168 r'\Y5': '${self.cwd_filt2(5)}',
163 # Hostname up to first .
169 # Hostname up to first .
164 r'\h': HOSTNAME_SHORT,
170 r'\h': HOSTNAME_SHORT,
165 # Full hostname
171 # Full hostname
166 r'\H': HOSTNAME,
172 r'\H': HOSTNAME,
167 # Username of current user
173 # Username of current user
168 r'\u': USER,
174 r'\u': USER,
169 # Escaped '\'
175 # Escaped '\'
170 '\\\\': '\\',
176 '\\\\': '\\',
171 # Newline
177 # Newline
172 r'\n': '\n',
178 r'\n': '\n',
173 # Carriage return
179 # Carriage return
174 r'\r': '\r',
180 r'\r': '\r',
175 # Release version
181 # Release version
176 r'\v': release.version,
182 r'\v': release.version,
177 # Root symbol ($ or #)
183 # Root symbol ($ or #)
178 r'\$': ROOT_SYMBOL,
184 r'\$': ROOT_SYMBOL,
179 }
185 }
180
186
181 # 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,
182 # 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.
183 prompt_specials_nocolor = prompt_specials_color.copy()
189 prompt_specials_nocolor = prompt_specials_color.copy()
184 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
190 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
185 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
191 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
186
192
187 # Add in all the InputTermColors color escapes as valid prompt characters.
193 # Add in all the InputTermColors color escapes as valid prompt characters.
188 # 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
189 # 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
190 # 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
191 # anything else.
197 # anything else.
192 input_colors = coloransi.InputTermColors
198 input_colors = coloransi.InputTermColors
193 for _color in dir(input_colors):
199 for _color in dir(input_colors):
194 if _color[0] != '_':
200 if _color[0] != '_':
195 c_name = r'\C_'+_color
201 c_name = r'\C_'+_color
196 prompt_specials_color[c_name] = getattr(input_colors,_color)
202 prompt_specials_color[c_name] = getattr(input_colors,_color)
197 prompt_specials_nocolor[c_name] = ''
203 prompt_specials_nocolor[c_name] = ''
198
204
199 # 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
200 # variable used by all prompt objects.
206 # variable used by all prompt objects.
201 prompt_specials = prompt_specials_nocolor
207 prompt_specials = prompt_specials_nocolor
202
208
203 #-----------------------------------------------------------------------------
209 #-----------------------------------------------------------------------------
210 # More utilities
211 #-----------------------------------------------------------------------------
212
204 def str_safe(arg):
213 def str_safe(arg):
205 """Convert to a string, without ever raising an exception.
214 """Convert to a string, without ever raising an exception.
206
215
207 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
216 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
208 error message."""
217 error message."""
209
218
210 try:
219 try:
211 out = str(arg)
220 out = str(arg)
212 except UnicodeError:
221 except UnicodeError:
213 try:
222 try:
214 out = arg.encode('utf_8','replace')
223 out = arg.encode('utf_8','replace')
215 except Exception,msg:
224 except Exception,msg:
216 # 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
217 # case doesn't suffer from a double try wrapping.
226 # case doesn't suffer from a double try wrapping.
218 out = '<ERROR: %s>' % msg
227 out = '<ERROR: %s>' % msg
219 except Exception,msg:
228 except Exception,msg:
220 out = '<ERROR: %s>' % msg
229 out = '<ERROR: %s>' % msg
221 #raise # dbg
230 #raise # dbg
222 return out
231 return out
223
232
233 #-----------------------------------------------------------------------------
234 # Prompt classes
235 #-----------------------------------------------------------------------------
236
224 class BasePrompt(object):
237 class BasePrompt(object):
225 """Interactive prompt similar to Mathematica's."""
238 """Interactive prompt similar to Mathematica's."""
226
239
227 def _get_p_template(self):
240 def _get_p_template(self):
228 return self._p_template
241 return self._p_template
229
242
230 def _set_p_template(self,val):
243 def _set_p_template(self,val):
231 self._p_template = val
244 self._p_template = val
232 self.set_p_str()
245 self.set_p_str()
233
246
234 p_template = property(_get_p_template,_set_p_template,
247 p_template = property(_get_p_template,_set_p_template,
235 doc='Template for prompt string creation')
248 doc='Template for prompt string creation')
236
249
237 def __init__(self,cache,sep,prompt,pad_left=False):
250 def __init__(self, cache, sep, prompt, pad_left=False):
238
251
239 # Hack: we access information about the primary prompt through the
252 # Hack: we access information about the primary prompt through the
240 # cache argument. We need this, because we want the secondary prompt
253 # cache argument. We need this, because we want the secondary prompt
241 # 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
242 # by all prompt classes through the cache. Nice OO spaghetti code!
255 # by all prompt classes through the cache. Nice OO spaghetti code!
243 self.cache = cache
256 self.cache = cache
244 self.sep = sep
257 self.sep = sep
245
258
246 # 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
247 # expression, useful for prompt auto-rewriting
260 # expression, useful for prompt auto-rewriting
248 self.rspace = re.compile(r'(\s*)$')
261 self.rspace = re.compile(r'(\s*)$')
249 # 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
250 # prompt
263 # prompt
251 self.pad_left = pad_left
264 self.pad_left = pad_left
252
265
253 # Set template to create each actual prompt (where numbers change).
266 # Set template to create each actual prompt (where numbers change).
254 # Use a property
267 # Use a property
255 self.p_template = prompt
268 self.p_template = prompt
256 self.set_p_str()
269 self.set_p_str()
257
270
258 def set_p_str(self):
271 def set_p_str(self):
259 """ Set the interpolating prompt strings.
272 """ Set the interpolating prompt strings.
260
273
261 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
262 prompt_specials global may have changed."""
275 prompt_specials global may have changed."""
263
276
264 import os,time # needed in locals for prompt string handling
277 import os,time # needed in locals for prompt string handling
265 loc = locals()
278 loc = locals()
266 try:
279 try:
267 self.p_str = ItplNS('%s%s%s' %
280 self.p_str = ItplNS('%s%s%s' %
268 ('${self.sep}${self.col_p}',
281 ('${self.sep}${self.col_p}',
269 multiple_replace(prompt_specials, self.p_template),
282 multiple_replace(prompt_specials, self.p_template),
270 '${self.col_norm}'),self.cache.user_ns,loc)
283 '${self.col_norm}'),self.cache.shell.user_ns,loc)
271
284
272 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
285 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
273 self.p_template),
286 self.p_template),
274 self.cache.user_ns,loc)
287 self.cache.shell.user_ns,loc)
275 except:
288 except:
276 print "Illegal prompt template (check $ usage!):",self.p_template
289 print "Illegal prompt template (check $ usage!):",self.p_template
277 self.p_str = self.p_template
290 self.p_str = self.p_template
278 self.p_str_nocolor = self.p_template
291 self.p_str_nocolor = self.p_template
279
292
280 def write(self,msg): # dbg
293 def write(self, msg):
281 sys.stdout.write(msg)
294 sys.stdout.write(msg)
282 return ''
295 return ''
283
296
284 def __str__(self):
297 def __str__(self):
285 """Return a string form of the prompt.
298 """Return a string form of the prompt.
286
299
287 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
288 left-padded to match lengths with the primary one (if the
301 left-padded to match lengths with the primary one (if the
289 self.pad_left attribute is set)."""
302 self.pad_left attribute is set)."""
290
303
291 out_str = str_safe(self.p_str)
304 out_str = str_safe(self.p_str)
292 if self.pad_left:
305 if self.pad_left:
293 # We must find the amount of padding required to match lengths,
306 # We must find the amount of padding required to match lengths,
294 # taking the color escapes (which are invisible on-screen) into
307 # taking the color escapes (which are invisible on-screen) into
295 # account.
308 # account.
296 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))
297 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
310 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
298 return format % out_str
311 return format % out_str
299 else:
312 else:
300 return out_str
313 return out_str
301
314
302 # 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
303 # namespace where the prompt strings get evaluated
316 # namespace where the prompt strings get evaluated
304 def cwd_filt(self,depth):
317 def cwd_filt(self, depth):
305 """Return the last depth elements of the current working directory.
318 """Return the last depth elements of the current working directory.
306
319
307 $HOME is always replaced with '~'.
320 $HOME is always replaced with '~'.
308 If depth==0, the full path is returned."""
321 If depth==0, the full path is returned."""
309
322
310 cwd = os.getcwd().replace(HOME,"~")
323 cwd = os.getcwd().replace(HOME,"~")
311 out = os.sep.join(cwd.split(os.sep)[-depth:])
324 out = os.sep.join(cwd.split(os.sep)[-depth:])
312 if out:
325 if out:
313 return out
326 return out
314 else:
327 else:
315 return os.sep
328 return os.sep
316
329
317 def cwd_filt2(self,depth):
330 def cwd_filt2(self, depth):
318 """Return the last depth elements of the current working directory.
331 """Return the last depth elements of the current working directory.
319
332
320 $HOME is always replaced with '~'.
333 $HOME is always replaced with '~'.
321 If depth==0, the full path is returned."""
334 If depth==0, the full path is returned."""
322
335
323 full_cwd = os.getcwd()
336 full_cwd = os.getcwd()
324 cwd = full_cwd.replace(HOME,"~").split(os.sep)
337 cwd = full_cwd.replace(HOME,"~").split(os.sep)
325 if '~' in cwd and len(cwd) == depth+1:
338 if '~' in cwd and len(cwd) == depth+1:
326 depth += 1
339 depth += 1
327 drivepart = ''
340 drivepart = ''
328 if sys.platform == 'win32' and len(cwd) > depth:
341 if sys.platform == 'win32' and len(cwd) > depth:
329 drivepart = os.path.splitdrive(full_cwd)[0]
342 drivepart = os.path.splitdrive(full_cwd)[0]
330 out = drivepart + '/'.join(cwd[-depth:])
343 out = drivepart + '/'.join(cwd[-depth:])
331
344
332 if out:
345 if out:
333 return out
346 return out
334 else:
347 else:
335 return os.sep
348 return os.sep
336
349
337 def __nonzero__(self):
350 def __nonzero__(self):
338 """Implement boolean behavior.
351 """Implement boolean behavior.
339
352
340 Checks whether the p_str attribute is non-empty"""
353 Checks whether the p_str attribute is non-empty"""
341
354
342 return bool(self.p_template)
355 return bool(self.p_template)
343
356
357
344 class Prompt1(BasePrompt):
358 class Prompt1(BasePrompt):
345 """Input interactive prompt similar to Mathematica's."""
359 """Input interactive prompt similar to Mathematica's."""
346
360
347 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
361 def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True):
348 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
362 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
349
363
350 def set_colors(self):
364 def set_colors(self):
351 self.set_p_str()
365 self.set_p_str()
352 Colors = self.cache.color_table.active_colors # shorthand
366 Colors = self.cache.color_table.active_colors # shorthand
353 self.col_p = Colors.in_prompt
367 self.col_p = Colors.in_prompt
354 self.col_num = Colors.in_number
368 self.col_num = Colors.in_number
355 self.col_norm = Colors.in_normal
369 self.col_norm = Colors.in_normal
356 # We need a non-input version of these escapes for the '--->'
370 # We need a non-input version of these escapes for the '--->'
357 # auto-call prompts used in the auto_rewrite() method.
371 # auto-call prompts used in the auto_rewrite() method.
358 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
372 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
359 self.col_norm_ni = Colors.normal
373 self.col_norm_ni = Colors.normal
360
374
361 def __str__(self):
375 def __str__(self):
362 self.cache.prompt_count += 1
376 self.cache.prompt_count += 1
363 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
377 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
364 return str_safe(self.p_str)
378 return str_safe(self.p_str)
365
379
366 def auto_rewrite(self):
380 def auto_rewrite(self):
367 """Print a string of the form '--->' which lines up with the previous
381 """Print a string of the form '--->' which lines up with the previous
368 input string. Useful for systems which re-write the user input when
382 input string. Useful for systems which re-write the user input when
369 handling automatically special syntaxes."""
383 handling automatically special syntaxes."""
370
384
371 curr = str(self.cache.last_prompt)
385 curr = str(self.cache.last_prompt)
372 nrspaces = len(self.rspace.search(curr).group())
386 nrspaces = len(self.rspace.search(curr).group())
373 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
387 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
374 ' '*nrspaces,self.col_norm_ni)
388 ' '*nrspaces,self.col_norm_ni)
375
389
390
376 class PromptOut(BasePrompt):
391 class PromptOut(BasePrompt):
377 """Output interactive prompt similar to Mathematica's."""
392 """Output interactive prompt similar to Mathematica's."""
378
393
379 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
394 def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True):
380 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
395 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
381 if not self.p_template:
396 if not self.p_template:
382 self.__str__ = lambda: ''
397 self.__str__ = lambda: ''
383
398
384 def set_colors(self):
399 def set_colors(self):
385 self.set_p_str()
400 self.set_p_str()
386 Colors = self.cache.color_table.active_colors # shorthand
401 Colors = self.cache.color_table.active_colors # shorthand
387 self.col_p = Colors.out_prompt
402 self.col_p = Colors.out_prompt
388 self.col_num = Colors.out_number
403 self.col_num = Colors.out_number
389 self.col_norm = Colors.normal
404 self.col_norm = Colors.normal
390
405
406
391 class Prompt2(BasePrompt):
407 class Prompt2(BasePrompt):
392 """Interactive continuation prompt."""
408 """Interactive continuation prompt."""
393
409
394 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
410 def __init__(self, cache, prompt=' .\\D.: ', pad_left=True):
395 self.cache = cache
411 self.cache = cache
396 self.p_template = prompt
412 self.p_template = prompt
397 self.pad_left = pad_left
413 self.pad_left = pad_left
398 self.set_p_str()
414 self.set_p_str()
399
415
400 def set_p_str(self):
416 def set_p_str(self):
401 import os,time # needed in locals for prompt string handling
417 import os,time # needed in locals for prompt string handling
402 loc = locals()
418 loc = locals()
403 self.p_str = ItplNS('%s%s%s' %
419 self.p_str = ItplNS('%s%s%s' %
404 ('${self.col_p2}',
420 ('${self.col_p2}',
405 multiple_replace(prompt_specials, self.p_template),
421 multiple_replace(prompt_specials, self.p_template),
406 '$self.col_norm'),
422 '$self.col_norm'),
407 self.cache.user_ns,loc)
423 self.cache.shell.user_ns,loc)
408 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
424 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
409 self.p_template),
425 self.p_template),
410 self.cache.user_ns,loc)
426 self.cache.shell.user_ns,loc)
411
427
412 def set_colors(self):
428 def set_colors(self):
413 self.set_p_str()
429 self.set_p_str()
414 Colors = self.cache.color_table.active_colors
430 Colors = self.cache.color_table.active_colors
415 self.col_p2 = Colors.in_prompt2
431 self.col_p2 = Colors.in_prompt2
416 self.col_norm = Colors.in_normal
432 self.col_norm = Colors.in_normal
417 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
433 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
418 # updated their prompt_in2 definitions. Remove eventually.
434 # updated their prompt_in2 definitions. Remove eventually.
419 self.col_p = Colors.out_prompt
435 self.col_p = Colors.out_prompt
420 self.col_num = Colors.out_number
436 self.col_num = Colors.out_number
421
437
422
423 #-----------------------------------------------------------------------------
424 class CachedOutput:
425 """Class for printing output from calculations while keeping a cache of
426 reults. It dynamically creates global variables prefixed with _ which
427 contain these results.
428
429 Meant to be used as a sys.displayhook replacement, providing numbered
430 prompts and cache services.
431
432 Initialize with initial and final values for cache counter (this defines
433 the maximum size of the cache."""
434
435 def __init__(self,shell,cache_size,Pprint,
436 colors='NoColor',input_sep='\n',
437 output_sep='\n',output_sep2='',
438 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
439
440 cache_size_min = 3
441 if cache_size <= 0:
442 self.do_full_cache = 0
443 cache_size = 0
444 elif cache_size < cache_size_min:
445 self.do_full_cache = 0
446 cache_size = 0
447 warn('caching was disabled (min value for cache size is %s).' %
448 cache_size_min,level=3)
449 else:
450 self.do_full_cache = 1
451
452 self.cache_size = cache_size
453 self.input_sep = input_sep
454
455 # we need a reference to the user-level namespace
456 self.shell = shell
457 self.user_ns = shell.user_ns
458 # and to the user's input
459 self.input_hist = shell.input_hist
460 # and to the user's logger, for logging output
461 self.logger = shell.logger
462
463 # Set input prompt strings and colors
464 if cache_size == 0:
465 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
466 or ps1.find(r'\N') > -1:
467 ps1 = '>>> '
468 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
469 or ps2.find(r'\N') > -1:
470 ps2 = '... '
471 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
472 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
473 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
474
475 self.color_table = PromptColors
476 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
477 pad_left=pad_left)
478 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
479 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
480 pad_left=pad_left)
481 self.set_colors(colors)
482
483 # other more normal stuff
484 # b/c each call to the In[] prompt raises it by 1, even the first.
485 self.prompt_count = 0
486 # Store the last prompt string each time, we need it for aligning
487 # continuation and auto-rewrite prompts
488 self.last_prompt = ''
489 self.Pprint = Pprint
490 self.output_sep = output_sep
491 self.output_sep2 = output_sep2
492 self._,self.__,self.___ = '','',''
493 self.pprint_types = map(type,[(),[],{}])
494
495 # these are deliberately global:
496 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
497 self.user_ns.update(to_user_ns)
498
499 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
500 if p_str is None:
501 if self.do_full_cache:
502 return cache_def
503 else:
504 return no_cache_def
505 else:
506 return p_str
507
508 def set_colors(self,colors):
509 """Set the active color scheme and configure colors for the three
510 prompt subsystems."""
511
512 # FIXME: the prompt_specials global should be gobbled inside this
513 # class instead. Do it when cleaning up the whole 3-prompt system.
514 global prompt_specials
515 if colors.lower()=='nocolor':
516 prompt_specials = prompt_specials_nocolor
517 else:
518 prompt_specials = prompt_specials_color
519
520 self.color_table.set_active_scheme(colors)
521 self.prompt1.set_colors()
522 self.prompt2.set_colors()
523 self.prompt_out.set_colors()
524
525 def __call__(self,arg=None):
526 """Printing with history cache management.
527
528 This is invoked everytime the interpreter needs to print, and is
529 activated by setting the variable sys.displayhook to it."""
530
531 # If something injected a '_' variable in __builtin__, delete
532 # ipython's automatic one so we don't clobber that. gettext() in
533 # particular uses _, so we need to stay away from it.
534 if '_' in __builtin__.__dict__:
535 try:
536 del self.user_ns['_']
537 except KeyError:
538 pass
539 if arg is not None:
540 cout_write = IPython.utils.io.Term.cout.write # fast lookup
541 # first handle the cache and counters
542
543 # do not print output if input ends in ';'
544 try:
545 if self.input_hist[self.prompt_count].endswith(';\n'):
546 return
547 except IndexError:
548 # some uses of ipshellembed may fail here
549 pass
550 # don't use print, puts an extra space
551 cout_write(self.output_sep)
552 outprompt = self.shell.hooks.generate_output_prompt()
553 # print "Got prompt: ", outprompt
554 if self.do_full_cache:
555 cout_write(outprompt)
556
557 # and now call a possibly user-defined print mechanism. Note that
558 # self.display typically prints as a side-effect, we don't do any
559 # printing to stdout here.
560 try:
561 manipulated_val = self.display(arg)
562 except TypeError:
563 # If the user's display hook didn't return a string we can
564 # print, we're done. Happens commonly if they return None
565 cout_write('\n')
566 return
567
568 # user display hooks can change the variable to be stored in
569 # output history
570 if manipulated_val is not None:
571 arg = manipulated_val
572
573 # avoid recursive reference when displaying _oh/Out
574 if arg is not self.user_ns['_oh']:
575 self.update(arg)
576
577 if self.logger.log_output:
578 self.logger.log_write(repr(arg),'output')
579 cout_write(self.output_sep2)
580 IPython.utils.io.Term.cout.flush()
581
582 def _display(self,arg):
583 """Default printer method, uses pprint.
584
585 Do ip.set_hook("result_display", my_displayhook) for custom result
586 display, e.g. when your own objects need special formatting.
587 """
588 try:
589 return IPython.utils.generics.result_display(arg)
590 except TryNext:
591 return self.shell.hooks.result_display(arg)
592
593 # Assign the default display method:
594 display = _display
595
596 def update(self,arg):
597 #print '***cache_count', self.cache_count # dbg
598 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
599 warn('Output cache limit (currently '+
600 `self.cache_size`+' entries) hit.\n'
601 'Flushing cache and resetting history counter...\n'
602 'The only history variables available will be _,__,___ and _1\n'
603 'with the current result.')
604
605 self.flush()
606 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
607 # we cause buggy behavior for things like gettext).
608 if '_' not in __builtin__.__dict__:
609 self.___ = self.__
610 self.__ = self._
611 self._ = arg
612 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
613
614 # hackish access to top-level namespace to create _1,_2... dynamically
615 to_main = {}
616 if self.do_full_cache:
617 new_result = '_'+`self.prompt_count`
618 to_main[new_result] = arg
619 self.user_ns.update(to_main)
620 self.user_ns['_oh'][self.prompt_count] = arg
621
622 def flush(self):
623 if not self.do_full_cache:
624 raise ValueError,"You shouldn't have reached the cache flush "\
625 "if full caching is not enabled!"
626 # delete auto-generated vars from global namespace
627
628 for n in range(1,self.prompt_count + 1):
629 key = '_'+`n`
630 try:
631 del self.user_ns[key]
632 except: pass
633 self.user_ns['_oh'].clear()
634
635 if '_' not in __builtin__.__dict__:
636 self.user_ns.update({'_':None,'__':None, '___':None})
637 import gc
638 gc.collect() # xxx needed?
639
@@ -1,169 +1,169 b''
1 """Tests for code execution (%run and related), which is particularly tricky.
1 """Tests for code execution (%run and related), which is particularly tricky.
2
2
3 Because of how %run manages namespaces, and the fact that we are trying here to
3 Because of how %run manages namespaces, and the fact that we are trying here to
4 verify subtle object deletion and reference counting issues, the %run tests
4 verify subtle object deletion and reference counting issues, the %run tests
5 will be kept in this separate file. This makes it easier to aggregate in one
5 will be kept in this separate file. This makes it easier to aggregate in one
6 place the tricks needed to handle it; most other magics are much easier to test
6 place the tricks needed to handle it; most other magics are much easier to test
7 and we do so in a common test_magic file.
7 and we do so in a common test_magic file.
8 """
8 """
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18
18
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 from IPython.testing import decorators as dec
21 from IPython.testing import decorators as dec
22 from IPython.testing import tools as tt
22 from IPython.testing import tools as tt
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions begin
25 # Test functions begin
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 def doctest_refbug():
28 def doctest_refbug():
29 """Very nasty problem with references held by multiple runs of a script.
29 """Very nasty problem with references held by multiple runs of a script.
30 See: https://bugs.launchpad.net/ipython/+bug/269966
30 See: https://bugs.launchpad.net/ipython/+bug/269966
31
31
32 In [1]: _ip.clear_main_mod_cache()
32 In [1]: _ip.clear_main_mod_cache()
33 # random
33 # random
34
34
35 In [2]: %run refbug
35 In [2]: %run refbug
36
36
37 In [3]: call_f()
37 In [3]: call_f()
38 lowercased: hello
38 lowercased: hello
39
39
40 In [4]: %run refbug
40 In [4]: %run refbug
41
41
42 In [5]: call_f()
42 In [5]: call_f()
43 lowercased: hello
43 lowercased: hello
44 lowercased: hello
44 lowercased: hello
45 """
45 """
46
46
47
47
48 def doctest_run_builtins():
48 def doctest_run_builtins():
49 r"""Check that %run doesn't damage __builtins__.
49 r"""Check that %run doesn't damage __builtins__.
50
50
51 In [1]: import tempfile
51 In [1]: import tempfile
52
52
53 In [2]: bid1 = id(__builtins__)
53 In [2]: bid1 = id(__builtins__)
54
54
55 In [3]: fname = tempfile.mkstemp('.py')[1]
55 In [3]: fname = tempfile.mkstemp('.py')[1]
56
56
57 In [3]: f = open(fname,'w')
57 In [3]: f = open(fname,'w')
58
58
59 In [4]: f.write('pass\n')
59 In [4]: f.write('pass\n')
60
60
61 In [5]: f.flush()
61 In [5]: f.flush()
62
62
63 In [6]: t1 = type(__builtins__)
63 In [6]: t1 = type(__builtins__)
64
64
65 In [7]: %run $fname
65 In [7]: %run $fname
66
66
67 In [7]: f.close()
67 In [7]: f.close()
68
68
69 In [8]: bid2 = id(__builtins__)
69 In [8]: bid2 = id(__builtins__)
70
70
71 In [9]: t2 = type(__builtins__)
71 In [9]: t2 = type(__builtins__)
72
72
73 In [10]: t1 == t2
73 In [10]: t1 == t2
74 Out[10]: True
74 Out[10]: True
75
75
76 In [10]: bid1 == bid2
76 In [10]: bid1 == bid2
77 Out[10]: True
77 Out[10]: True
78
78
79 In [12]: try:
79 In [12]: try:
80 ....: os.unlink(fname)
80 ....: os.unlink(fname)
81 ....: except:
81 ....: except:
82 ....: pass
82 ....: pass
83 ....:
83 ....:
84 """
84 """
85
85
86 # For some tests, it will be handy to organize them in a class with a common
86 # For some tests, it will be handy to organize them in a class with a common
87 # setup that makes a temp file
87 # setup that makes a temp file
88
88
89 class TestMagicRunPass(tt.TempFileMixin):
89 class TestMagicRunPass(tt.TempFileMixin):
90
90
91 def setup(self):
91 def setup(self):
92 """Make a valid python temp file."""
92 """Make a valid python temp file."""
93 self.mktmp('pass\n')
93 self.mktmp('pass\n')
94
94
95 def run_tmpfile(self):
95 def run_tmpfile(self):
96 _ip = get_ipython()
96 _ip = get_ipython()
97 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
97 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
98 # See below and ticket https://bugs.launchpad.net/bugs/366353
98 # See below and ticket https://bugs.launchpad.net/bugs/366353
99 _ip.magic('run %s' % self.fname)
99 _ip.magic('run %s' % self.fname)
100
100
101 def test_builtins_id(self):
101 def test_builtins_id(self):
102 """Check that %run doesn't damage __builtins__ """
102 """Check that %run doesn't damage __builtins__ """
103 _ip = get_ipython()
103 _ip = get_ipython()
104 # Test that the id of __builtins__ is not modified by %run
104 # Test that the id of __builtins__ is not modified by %run
105 bid1 = id(_ip.user_ns['__builtins__'])
105 bid1 = id(_ip.user_ns['__builtins__'])
106 self.run_tmpfile()
106 self.run_tmpfile()
107 bid2 = id(_ip.user_ns['__builtins__'])
107 bid2 = id(_ip.user_ns['__builtins__'])
108 tt.assert_equals(bid1, bid2)
108 tt.assert_equals(bid1, bid2)
109
109
110 def test_builtins_type(self):
110 def test_builtins_type(self):
111 """Check that the type of __builtins__ doesn't change with %run.
111 """Check that the type of __builtins__ doesn't change with %run.
112
112
113 However, the above could pass if __builtins__ was already modified to
113 However, the above could pass if __builtins__ was already modified to
114 be a dict (it should be a module) by a previous use of %run. So we
114 be a dict (it should be a module) by a previous use of %run. So we
115 also check explicitly that it really is a module:
115 also check explicitly that it really is a module:
116 """
116 """
117 _ip = get_ipython()
117 _ip = get_ipython()
118 self.run_tmpfile()
118 self.run_tmpfile()
119 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
119 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
120
120
121 def test_prompts(self):
121 def test_prompts(self):
122 """Test that prompts correctly generate after %run"""
122 """Test that prompts correctly generate after %run"""
123 self.run_tmpfile()
123 self.run_tmpfile()
124 _ip = get_ipython()
124 _ip = get_ipython()
125 p2 = str(_ip.outputcache.prompt2).strip()
125 p2 = str(_ip.displayhook.prompt2).strip()
126 nt.assert_equals(p2[:3], '...')
126 nt.assert_equals(p2[:3], '...')
127
127
128
128
129 class TestMagicRunSimple(tt.TempFileMixin):
129 class TestMagicRunSimple(tt.TempFileMixin):
130
130
131 def test_simpledef(self):
131 def test_simpledef(self):
132 """Test that simple class definitions work."""
132 """Test that simple class definitions work."""
133 src = ("class foo: pass\n"
133 src = ("class foo: pass\n"
134 "def f(): return foo()")
134 "def f(): return foo()")
135 self.mktmp(src)
135 self.mktmp(src)
136 _ip.magic('run %s' % self.fname)
136 _ip.magic('run %s' % self.fname)
137 _ip.runlines('t = isinstance(f(), foo)')
137 _ip.runlines('t = isinstance(f(), foo)')
138 nt.assert_true(_ip.user_ns['t'])
138 nt.assert_true(_ip.user_ns['t'])
139
139
140 # We have to skip these in win32 because getoutputerr() crashes,
140 # We have to skip these in win32 because getoutputerr() crashes,
141 # due to the fact that subprocess does not support close_fds when
141 # due to the fact that subprocess does not support close_fds when
142 # redirecting stdout/err. So unless someone who knows more tells us how to
142 # redirecting stdout/err. So unless someone who knows more tells us how to
143 # implement getoutputerr() in win32, we're stuck avoiding these.
143 # implement getoutputerr() in win32, we're stuck avoiding these.
144 @dec.skip_win32
144 @dec.skip_win32
145 def test_obj_del(self):
145 def test_obj_del(self):
146 """Test that object's __del__ methods are called on exit."""
146 """Test that object's __del__ methods are called on exit."""
147
147
148 # This test is known to fail on win32.
148 # This test is known to fail on win32.
149 # See ticket https://bugs.launchpad.net/bugs/366334
149 # See ticket https://bugs.launchpad.net/bugs/366334
150 src = ("class A(object):\n"
150 src = ("class A(object):\n"
151 " def __del__(self):\n"
151 " def __del__(self):\n"
152 " print 'object A deleted'\n"
152 " print 'object A deleted'\n"
153 "a = A()\n")
153 "a = A()\n")
154 self.mktmp(src)
154 self.mktmp(src)
155 tt.ipexec_validate(self.fname, 'object A deleted')
155 tt.ipexec_validate(self.fname, 'object A deleted')
156
156
157 @dec.skip_win32
157 @dec.skip_win32
158 def test_tclass(self):
158 def test_tclass(self):
159 mydir = os.path.dirname(__file__)
159 mydir = os.path.dirname(__file__)
160 tc = os.path.join(mydir, 'tclass')
160 tc = os.path.join(mydir, 'tclass')
161 src = ("%%run '%s' C-first\n"
161 src = ("%%run '%s' C-first\n"
162 "%%run '%s' C-second\n") % (tc, tc)
162 "%%run '%s' C-second\n") % (tc, tc)
163 self.mktmp(src, '.ipy')
163 self.mktmp(src, '.ipy')
164 out = """\
164 out = """\
165 ARGV 1-: ['C-first']
165 ARGV 1-: ['C-first']
166 ARGV 1-: ['C-second']
166 ARGV 1-: ['C-second']
167 tclass.py: deleting object: C-first
167 tclass.py: deleting object: C-first
168 """
168 """
169 tt.ipexec_validate(self.fname, out)
169 tt.ipexec_validate(self.fname, out)
@@ -1,523 +1,523 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 exit_now = CBool(False)
79 exit_now = CBool(False)
80 pager = Str('less', config=True)
80 pager = Str('less', config=True)
81
81
82 screen_length = Int(0, config=True)
82 screen_length = Int(0, config=True)
83 term_title = CBool(False, config=True)
83 term_title = CBool(False, config=True)
84
84
85 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 def __init__(self, config=None, ipython_dir=None, user_ns=None,
86 user_global_ns=None, custom_exceptions=((),None),
86 user_global_ns=None, custom_exceptions=((),None),
87 usage=None, banner1=None, banner2=None,
87 usage=None, banner1=None, banner2=None,
88 display_banner=None):
88 display_banner=None):
89
89
90 super(TerminalInteractiveShell, self).__init__(
90 super(TerminalInteractiveShell, self).__init__(
91 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
92 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
93 )
93 )
94 self.init_term_title()
94 self.init_term_title()
95 self.init_usage(usage)
95 self.init_usage(usage)
96 self.init_banner(banner1, banner2, display_banner)
96 self.init_banner(banner1, banner2, display_banner)
97
97
98 #-------------------------------------------------------------------------
98 #-------------------------------------------------------------------------
99 # Things related to the terminal
99 # Things related to the terminal
100 #-------------------------------------------------------------------------
100 #-------------------------------------------------------------------------
101
101
102 @property
102 @property
103 def usable_screen_length(self):
103 def usable_screen_length(self):
104 if self.screen_length == 0:
104 if self.screen_length == 0:
105 return 0
105 return 0
106 else:
106 else:
107 num_lines_bot = self.separate_in.count('\n')+1
107 num_lines_bot = self.separate_in.count('\n')+1
108 return self.screen_length - num_lines_bot
108 return self.screen_length - num_lines_bot
109
109
110 def init_term_title(self):
110 def init_term_title(self):
111 # Enable or disable the terminal title.
111 # Enable or disable the terminal title.
112 if self.term_title:
112 if self.term_title:
113 toggle_set_term_title(True)
113 toggle_set_term_title(True)
114 set_term_title('IPython: ' + abbrev_cwd())
114 set_term_title('IPython: ' + abbrev_cwd())
115 else:
115 else:
116 toggle_set_term_title(False)
116 toggle_set_term_title(False)
117
117
118 #-------------------------------------------------------------------------
118 #-------------------------------------------------------------------------
119 # Things related to the banner and usage
119 # Things related to the banner and usage
120 #-------------------------------------------------------------------------
120 #-------------------------------------------------------------------------
121
121
122 def _banner1_changed(self):
122 def _banner1_changed(self):
123 self.compute_banner()
123 self.compute_banner()
124
124
125 def _banner2_changed(self):
125 def _banner2_changed(self):
126 self.compute_banner()
126 self.compute_banner()
127
127
128 def _term_title_changed(self, name, new_value):
128 def _term_title_changed(self, name, new_value):
129 self.init_term_title()
129 self.init_term_title()
130
130
131 def init_banner(self, banner1, banner2, display_banner):
131 def init_banner(self, banner1, banner2, display_banner):
132 if banner1 is not None:
132 if banner1 is not None:
133 self.banner1 = banner1
133 self.banner1 = banner1
134 if banner2 is not None:
134 if banner2 is not None:
135 self.banner2 = banner2
135 self.banner2 = banner2
136 if display_banner is not None:
136 if display_banner is not None:
137 self.display_banner = display_banner
137 self.display_banner = display_banner
138 self.compute_banner()
138 self.compute_banner()
139
139
140 def show_banner(self, banner=None):
140 def show_banner(self, banner=None):
141 if banner is None:
141 if banner is None:
142 banner = self.banner
142 banner = self.banner
143 self.write(banner)
143 self.write(banner)
144
144
145 def compute_banner(self):
145 def compute_banner(self):
146 self.banner = self.banner1 + '\n'
146 self.banner = self.banner1 + '\n'
147 if self.profile:
147 if self.profile:
148 self.banner += '\nIPython profile: %s\n' % self.profile
148 self.banner += '\nIPython profile: %s\n' % self.profile
149 if self.banner2:
149 if self.banner2:
150 self.banner += '\n' + self.banner2 + '\n'
150 self.banner += '\n' + self.banner2 + '\n'
151
151
152 def init_usage(self, usage=None):
152 def init_usage(self, usage=None):
153 if usage is None:
153 if usage is None:
154 self.usage = interactive_usage
154 self.usage = interactive_usage
155 else:
155 else:
156 self.usage = usage
156 self.usage = usage
157
157
158 #-------------------------------------------------------------------------
158 #-------------------------------------------------------------------------
159 # Mainloop and code execution logic
159 # Mainloop and code execution logic
160 #-------------------------------------------------------------------------
160 #-------------------------------------------------------------------------
161
161
162 def mainloop(self, display_banner=None):
162 def mainloop(self, display_banner=None):
163 """Start the mainloop.
163 """Start the mainloop.
164
164
165 If an optional banner argument is given, it will override the
165 If an optional banner argument is given, it will override the
166 internally created default banner.
166 internally created default banner.
167 """
167 """
168
168
169 with nested(self.builtin_trap, self.display_trap):
169 with nested(self.builtin_trap, self.display_trap):
170
170
171 # if you run stuff with -c <cmd>, raw hist is not updated
171 # if you run stuff with -c <cmd>, raw hist is not updated
172 # ensure that it's in sync
172 # ensure that it's in sync
173 if len(self.input_hist) != len (self.input_hist_raw):
173 if len(self.input_hist) != len (self.input_hist_raw):
174 self.input_hist_raw = InputList(self.input_hist)
174 self.input_hist_raw = InputList(self.input_hist)
175
175
176 while 1:
176 while 1:
177 try:
177 try:
178 self.interact(display_banner=display_banner)
178 self.interact(display_banner=display_banner)
179 #self.interact_with_readline()
179 #self.interact_with_readline()
180 # XXX for testing of a readline-decoupled repl loop, call
180 # XXX for testing of a readline-decoupled repl loop, call
181 # interact_with_readline above
181 # interact_with_readline above
182 break
182 break
183 except KeyboardInterrupt:
183 except KeyboardInterrupt:
184 # this should not be necessary, but KeyboardInterrupt
184 # this should not be necessary, but KeyboardInterrupt
185 # handling seems rather unpredictable...
185 # handling seems rather unpredictable...
186 self.write("\nKeyboardInterrupt in interact()\n")
186 self.write("\nKeyboardInterrupt in interact()\n")
187
187
188 def interact(self, display_banner=None):
188 def interact(self, display_banner=None):
189 """Closely emulate the interactive Python console."""
189 """Closely emulate the interactive Python console."""
190
190
191 # batch run -> do not interact
191 # batch run -> do not interact
192 if self.exit_now:
192 if self.exit_now:
193 return
193 return
194
194
195 if display_banner is None:
195 if display_banner is None:
196 display_banner = self.display_banner
196 display_banner = self.display_banner
197 if display_banner:
197 if display_banner:
198 self.show_banner()
198 self.show_banner()
199
199
200 more = 0
200 more = 0
201
201
202 # Mark activity in the builtins
202 # Mark activity in the builtins
203 __builtin__.__dict__['__IPYTHON__active'] += 1
203 __builtin__.__dict__['__IPYTHON__active'] += 1
204
204
205 if self.has_readline:
205 if self.has_readline:
206 self.readline_startup_hook(self.pre_readline)
206 self.readline_startup_hook(self.pre_readline)
207 # exit_now is set by a call to %Exit or %Quit, through the
207 # exit_now is set by a call to %Exit or %Quit, through the
208 # ask_exit callback.
208 # ask_exit callback.
209
209
210 while not self.exit_now:
210 while not self.exit_now:
211 self.hooks.pre_prompt_hook()
211 self.hooks.pre_prompt_hook()
212 if more:
212 if more:
213 try:
213 try:
214 prompt = self.hooks.generate_prompt(True)
214 prompt = self.hooks.generate_prompt(True)
215 except:
215 except:
216 self.showtraceback()
216 self.showtraceback()
217 if self.autoindent:
217 if self.autoindent:
218 self.rl_do_indent = True
218 self.rl_do_indent = True
219
219
220 else:
220 else:
221 try:
221 try:
222 prompt = self.hooks.generate_prompt(False)
222 prompt = self.hooks.generate_prompt(False)
223 except:
223 except:
224 self.showtraceback()
224 self.showtraceback()
225 try:
225 try:
226 line = self.raw_input(prompt, more)
226 line = self.raw_input(prompt, more)
227 if self.exit_now:
227 if self.exit_now:
228 # quick exit on sys.std[in|out] close
228 # quick exit on sys.std[in|out] close
229 break
229 break
230 if self.autoindent:
230 if self.autoindent:
231 self.rl_do_indent = False
231 self.rl_do_indent = False
232
232
233 except KeyboardInterrupt:
233 except KeyboardInterrupt:
234 #double-guard against keyboardinterrupts during kbdint handling
234 #double-guard against keyboardinterrupts during kbdint handling
235 try:
235 try:
236 self.write('\nKeyboardInterrupt\n')
236 self.write('\nKeyboardInterrupt\n')
237 self.resetbuffer()
237 self.resetbuffer()
238 # keep cache in sync with the prompt counter:
238 # keep cache in sync with the prompt counter:
239 self.outputcache.prompt_count -= 1
239 self.displayhook.prompt_count -= 1
240
240
241 if self.autoindent:
241 if self.autoindent:
242 self.indent_current_nsp = 0
242 self.indent_current_nsp = 0
243 more = 0
243 more = 0
244 except KeyboardInterrupt:
244 except KeyboardInterrupt:
245 pass
245 pass
246 except EOFError:
246 except EOFError:
247 if self.autoindent:
247 if self.autoindent:
248 self.rl_do_indent = False
248 self.rl_do_indent = False
249 if self.has_readline:
249 if self.has_readline:
250 self.readline_startup_hook(None)
250 self.readline_startup_hook(None)
251 self.write('\n')
251 self.write('\n')
252 self.exit()
252 self.exit()
253 except bdb.BdbQuit:
253 except bdb.BdbQuit:
254 warn('The Python debugger has exited with a BdbQuit exception.\n'
254 warn('The Python debugger has exited with a BdbQuit exception.\n'
255 'Because of how pdb handles the stack, it is impossible\n'
255 'Because of how pdb handles the stack, it is impossible\n'
256 'for IPython to properly format this particular exception.\n'
256 'for IPython to properly format this particular exception.\n'
257 'IPython will resume normal operation.')
257 'IPython will resume normal operation.')
258 except:
258 except:
259 # exceptions here are VERY RARE, but they can be triggered
259 # exceptions here are VERY RARE, but they can be triggered
260 # asynchronously by signal handlers, for example.
260 # asynchronously by signal handlers, for example.
261 self.showtraceback()
261 self.showtraceback()
262 else:
262 else:
263 more = self.push_line(line)
263 more = self.push_line(line)
264 if (self.SyntaxTB.last_syntax_error and
264 if (self.SyntaxTB.last_syntax_error and
265 self.autoedit_syntax):
265 self.autoedit_syntax):
266 self.edit_syntax_error()
266 self.edit_syntax_error()
267
267
268 # We are off again...
268 # We are off again...
269 __builtin__.__dict__['__IPYTHON__active'] -= 1
269 __builtin__.__dict__['__IPYTHON__active'] -= 1
270
270
271 # Turn off the exit flag, so the mainloop can be restarted if desired
271 # Turn off the exit flag, so the mainloop can be restarted if desired
272 self.exit_now = False
272 self.exit_now = False
273
273
274 def raw_input(self,prompt='',continue_prompt=False):
274 def raw_input(self,prompt='',continue_prompt=False):
275 """Write a prompt and read a line.
275 """Write a prompt and read a line.
276
276
277 The returned line does not include the trailing newline.
277 The returned line does not include the trailing newline.
278 When the user enters the EOF key sequence, EOFError is raised.
278 When the user enters the EOF key sequence, EOFError is raised.
279
279
280 Optional inputs:
280 Optional inputs:
281
281
282 - prompt(''): a string to be printed to prompt the user.
282 - prompt(''): a string to be printed to prompt the user.
283
283
284 - continue_prompt(False): whether this line is the first one or a
284 - continue_prompt(False): whether this line is the first one or a
285 continuation in a sequence of inputs.
285 continuation in a sequence of inputs.
286 """
286 """
287 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
287 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
288
288
289 # Code run by the user may have modified the readline completer state.
289 # Code run by the user may have modified the readline completer state.
290 # We must ensure that our completer is back in place.
290 # We must ensure that our completer is back in place.
291
291
292 if self.has_readline:
292 if self.has_readline:
293 self.set_completer()
293 self.set_completer()
294
294
295 try:
295 try:
296 line = raw_input_original(prompt).decode(self.stdin_encoding)
296 line = raw_input_original(prompt).decode(self.stdin_encoding)
297 except ValueError:
297 except ValueError:
298 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
298 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
299 " or sys.stdout.close()!\nExiting IPython!")
299 " or sys.stdout.close()!\nExiting IPython!")
300 self.ask_exit()
300 self.ask_exit()
301 return ""
301 return ""
302
302
303 # Try to be reasonably smart about not re-indenting pasted input more
303 # Try to be reasonably smart about not re-indenting pasted input more
304 # than necessary. We do this by trimming out the auto-indent initial
304 # than necessary. We do this by trimming out the auto-indent initial
305 # spaces, if the user's actual input started itself with whitespace.
305 # spaces, if the user's actual input started itself with whitespace.
306 #debugx('self.buffer[-1]')
306 #debugx('self.buffer[-1]')
307
307
308 if self.autoindent:
308 if self.autoindent:
309 if num_ini_spaces(line) > self.indent_current_nsp:
309 if num_ini_spaces(line) > self.indent_current_nsp:
310 line = line[self.indent_current_nsp:]
310 line = line[self.indent_current_nsp:]
311 self.indent_current_nsp = 0
311 self.indent_current_nsp = 0
312
312
313 # store the unfiltered input before the user has any chance to modify
313 # store the unfiltered input before the user has any chance to modify
314 # it.
314 # it.
315 if line.strip():
315 if line.strip():
316 if continue_prompt:
316 if continue_prompt:
317 self.input_hist_raw[-1] += '%s\n' % line
317 self.input_hist_raw[-1] += '%s\n' % line
318 if self.has_readline and self.readline_use:
318 if self.has_readline and self.readline_use:
319 try:
319 try:
320 histlen = self.readline.get_current_history_length()
320 histlen = self.readline.get_current_history_length()
321 if histlen > 1:
321 if histlen > 1:
322 newhist = self.input_hist_raw[-1].rstrip()
322 newhist = self.input_hist_raw[-1].rstrip()
323 self.readline.remove_history_item(histlen-1)
323 self.readline.remove_history_item(histlen-1)
324 self.readline.replace_history_item(histlen-2,
324 self.readline.replace_history_item(histlen-2,
325 newhist.encode(self.stdin_encoding))
325 newhist.encode(self.stdin_encoding))
326 except AttributeError:
326 except AttributeError:
327 pass # re{move,place}_history_item are new in 2.4.
327 pass # re{move,place}_history_item are new in 2.4.
328 else:
328 else:
329 self.input_hist_raw.append('%s\n' % line)
329 self.input_hist_raw.append('%s\n' % line)
330 # only entries starting at first column go to shadow history
330 # only entries starting at first column go to shadow history
331 if line.lstrip() == line:
331 if line.lstrip() == line:
332 self.shadowhist.add(line.strip())
332 self.shadowhist.add(line.strip())
333 elif not continue_prompt:
333 elif not continue_prompt:
334 self.input_hist_raw.append('\n')
334 self.input_hist_raw.append('\n')
335 try:
335 try:
336 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
336 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
337 except:
337 except:
338 # blanket except, in case a user-defined prefilter crashes, so it
338 # blanket except, in case a user-defined prefilter crashes, so it
339 # can't take all of ipython with it.
339 # can't take all of ipython with it.
340 self.showtraceback()
340 self.showtraceback()
341 return ''
341 return ''
342 else:
342 else:
343 return lineout
343 return lineout
344
344
345 # TODO: The following three methods are an early attempt to refactor
345 # TODO: The following three methods are an early attempt to refactor
346 # the main code execution logic. We don't use them, but they may be
346 # the main code execution logic. We don't use them, but they may be
347 # helpful when we refactor the code execution logic further.
347 # helpful when we refactor the code execution logic further.
348 # def interact_prompt(self):
348 # def interact_prompt(self):
349 # """ Print the prompt (in read-eval-print loop)
349 # """ Print the prompt (in read-eval-print loop)
350 #
350 #
351 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
351 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
352 # used in standard IPython flow.
352 # used in standard IPython flow.
353 # """
353 # """
354 # if self.more:
354 # if self.more:
355 # try:
355 # try:
356 # prompt = self.hooks.generate_prompt(True)
356 # prompt = self.hooks.generate_prompt(True)
357 # except:
357 # except:
358 # self.showtraceback()
358 # self.showtraceback()
359 # if self.autoindent:
359 # if self.autoindent:
360 # self.rl_do_indent = True
360 # self.rl_do_indent = True
361 #
361 #
362 # else:
362 # else:
363 # try:
363 # try:
364 # prompt = self.hooks.generate_prompt(False)
364 # prompt = self.hooks.generate_prompt(False)
365 # except:
365 # except:
366 # self.showtraceback()
366 # self.showtraceback()
367 # self.write(prompt)
367 # self.write(prompt)
368 #
368 #
369 # def interact_handle_input(self,line):
369 # def interact_handle_input(self,line):
370 # """ Handle the input line (in read-eval-print loop)
370 # """ Handle the input line (in read-eval-print loop)
371 #
371 #
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
373 # used in standard IPython flow.
373 # used in standard IPython flow.
374 # """
374 # """
375 # if line.lstrip() == line:
375 # if line.lstrip() == line:
376 # self.shadowhist.add(line.strip())
376 # self.shadowhist.add(line.strip())
377 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
377 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
378 #
378 #
379 # if line.strip():
379 # if line.strip():
380 # if self.more:
380 # if self.more:
381 # self.input_hist_raw[-1] += '%s\n' % line
381 # self.input_hist_raw[-1] += '%s\n' % line
382 # else:
382 # else:
383 # self.input_hist_raw.append('%s\n' % line)
383 # self.input_hist_raw.append('%s\n' % line)
384 #
384 #
385 #
385 #
386 # self.more = self.push_line(lineout)
386 # self.more = self.push_line(lineout)
387 # if (self.SyntaxTB.last_syntax_error and
387 # if (self.SyntaxTB.last_syntax_error and
388 # self.autoedit_syntax):
388 # self.autoedit_syntax):
389 # self.edit_syntax_error()
389 # self.edit_syntax_error()
390 #
390 #
391 # def interact_with_readline(self):
391 # def interact_with_readline(self):
392 # """ Demo of using interact_handle_input, interact_prompt
392 # """ Demo of using interact_handle_input, interact_prompt
393 #
393 #
394 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
394 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
395 # it should work like this.
395 # it should work like this.
396 # """
396 # """
397 # self.readline_startup_hook(self.pre_readline)
397 # self.readline_startup_hook(self.pre_readline)
398 # while not self.exit_now:
398 # while not self.exit_now:
399 # self.interact_prompt()
399 # self.interact_prompt()
400 # if self.more:
400 # if self.more:
401 # self.rl_do_indent = True
401 # self.rl_do_indent = True
402 # else:
402 # else:
403 # self.rl_do_indent = False
403 # self.rl_do_indent = False
404 # line = raw_input_original().decode(self.stdin_encoding)
404 # line = raw_input_original().decode(self.stdin_encoding)
405 # self.interact_handle_input(line)
405 # self.interact_handle_input(line)
406
406
407 #-------------------------------------------------------------------------
407 #-------------------------------------------------------------------------
408 # Methods to support auto-editing of SyntaxErrors.
408 # Methods to support auto-editing of SyntaxErrors.
409 #-------------------------------------------------------------------------
409 #-------------------------------------------------------------------------
410
410
411 def edit_syntax_error(self):
411 def edit_syntax_error(self):
412 """The bottom half of the syntax error handler called in the main loop.
412 """The bottom half of the syntax error handler called in the main loop.
413
413
414 Loop until syntax error is fixed or user cancels.
414 Loop until syntax error is fixed or user cancels.
415 """
415 """
416
416
417 while self.SyntaxTB.last_syntax_error:
417 while self.SyntaxTB.last_syntax_error:
418 # copy and clear last_syntax_error
418 # copy and clear last_syntax_error
419 err = self.SyntaxTB.clear_err_state()
419 err = self.SyntaxTB.clear_err_state()
420 if not self._should_recompile(err):
420 if not self._should_recompile(err):
421 return
421 return
422 try:
422 try:
423 # may set last_syntax_error again if a SyntaxError is raised
423 # may set last_syntax_error again if a SyntaxError is raised
424 self.safe_execfile(err.filename,self.user_ns)
424 self.safe_execfile(err.filename,self.user_ns)
425 except:
425 except:
426 self.showtraceback()
426 self.showtraceback()
427 else:
427 else:
428 try:
428 try:
429 f = file(err.filename)
429 f = file(err.filename)
430 try:
430 try:
431 # This should be inside a display_trap block and I
431 # This should be inside a display_trap block and I
432 # think it is.
432 # think it is.
433 sys.displayhook(f.read())
433 sys.displayhook(f.read())
434 finally:
434 finally:
435 f.close()
435 f.close()
436 except:
436 except:
437 self.showtraceback()
437 self.showtraceback()
438
438
439 def _should_recompile(self,e):
439 def _should_recompile(self,e):
440 """Utility routine for edit_syntax_error"""
440 """Utility routine for edit_syntax_error"""
441
441
442 if e.filename in ('<ipython console>','<input>','<string>',
442 if e.filename in ('<ipython console>','<input>','<string>',
443 '<console>','<BackgroundJob compilation>',
443 '<console>','<BackgroundJob compilation>',
444 None):
444 None):
445
445
446 return False
446 return False
447 try:
447 try:
448 if (self.autoedit_syntax and
448 if (self.autoedit_syntax and
449 not self.ask_yes_no('Return to editor to correct syntax error? '
449 not self.ask_yes_no('Return to editor to correct syntax error? '
450 '[Y/n] ','y')):
450 '[Y/n] ','y')):
451 return False
451 return False
452 except EOFError:
452 except EOFError:
453 return False
453 return False
454
454
455 def int0(x):
455 def int0(x):
456 try:
456 try:
457 return int(x)
457 return int(x)
458 except TypeError:
458 except TypeError:
459 return 0
459 return 0
460 # always pass integer line and offset values to editor hook
460 # always pass integer line and offset values to editor hook
461 try:
461 try:
462 self.hooks.fix_error_editor(e.filename,
462 self.hooks.fix_error_editor(e.filename,
463 int0(e.lineno),int0(e.offset),e.msg)
463 int0(e.lineno),int0(e.offset),e.msg)
464 except TryNext:
464 except TryNext:
465 warn('Could not open editor')
465 warn('Could not open editor')
466 return False
466 return False
467 return True
467 return True
468
468
469 #-------------------------------------------------------------------------
469 #-------------------------------------------------------------------------
470 # Things related to GUI support and pylab
470 # Things related to GUI support and pylab
471 #-------------------------------------------------------------------------
471 #-------------------------------------------------------------------------
472
472
473 def enable_pylab(self, gui=None):
473 def enable_pylab(self, gui=None):
474 """Activate pylab support at runtime.
474 """Activate pylab support at runtime.
475
475
476 This turns on support for matplotlib, preloads into the interactive
476 This turns on support for matplotlib, preloads into the interactive
477 namespace all of numpy and pylab, and configures IPython to correcdtly
477 namespace all of numpy and pylab, and configures IPython to correcdtly
478 interact with the GUI event loop. The GUI backend to be used can be
478 interact with the GUI event loop. The GUI backend to be used can be
479 optionally selected with the optional :param:`gui` argument.
479 optionally selected with the optional :param:`gui` argument.
480
480
481 Parameters
481 Parameters
482 ----------
482 ----------
483 gui : optional, string
483 gui : optional, string
484
484
485 If given, dictates the choice of matplotlib GUI backend to use
485 If given, dictates the choice of matplotlib GUI backend to use
486 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
486 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
487 'gtk'), otherwise we use the default chosen by matplotlib (as
487 'gtk'), otherwise we use the default chosen by matplotlib (as
488 dictated by the matplotlib build-time options plus the user's
488 dictated by the matplotlib build-time options plus the user's
489 matplotlibrc configuration file).
489 matplotlibrc configuration file).
490 """
490 """
491 # We want to prevent the loading of pylab to pollute the user's
491 # We want to prevent the loading of pylab to pollute the user's
492 # namespace as shown by the %who* magics, so we execute the activation
492 # namespace as shown by the %who* magics, so we execute the activation
493 # code in an empty namespace, and we update *both* user_ns and
493 # code in an empty namespace, and we update *both* user_ns and
494 # user_ns_hidden with this information.
494 # user_ns_hidden with this information.
495 ns = {}
495 ns = {}
496 gui = pylab_activate(ns, gui)
496 gui = pylab_activate(ns, gui)
497 self.user_ns.update(ns)
497 self.user_ns.update(ns)
498 self.user_ns_hidden.update(ns)
498 self.user_ns_hidden.update(ns)
499 # Now we must activate the gui pylab wants to use, and fix %run to take
499 # Now we must activate the gui pylab wants to use, and fix %run to take
500 # plot updates into account
500 # plot updates into account
501 enable_gui(gui)
501 enable_gui(gui)
502 self.magic_run = self._pylab_magic_run
502 self.magic_run = self._pylab_magic_run
503
503
504 #-------------------------------------------------------------------------
504 #-------------------------------------------------------------------------
505 # Things related to exiting
505 # Things related to exiting
506 #-------------------------------------------------------------------------
506 #-------------------------------------------------------------------------
507
507
508 def ask_exit(self):
508 def ask_exit(self):
509 """ Ask the shell to exit. Can be overiden and used as a callback. """
509 """ Ask the shell to exit. Can be overiden and used as a callback. """
510 self.exit_now = True
510 self.exit_now = True
511
511
512 def exit(self):
512 def exit(self):
513 """Handle interactive exit.
513 """Handle interactive exit.
514
514
515 This method calls the ask_exit callback."""
515 This method calls the ask_exit callback."""
516 if self.confirm_exit:
516 if self.confirm_exit:
517 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
517 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
518 self.ask_exit()
518 self.ask_exit()
519 else:
519 else:
520 self.ask_exit()
520 self.ask_exit()
521
521
522
522
523 InteractiveShellABC.register(TerminalInteractiveShell)
523 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,442 +1,442 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Test Suite Runner.
2 """IPython Test Suite Runner.
3
3
4 This module provides a main entry point to a user script to test IPython
4 This module provides a main entry point to a user script to test IPython
5 itself from the command line. There are two ways of running this script:
5 itself from the command line. There are two ways of running this script:
6
6
7 1. With the syntax `iptest all`. This runs our entire test suite by
7 1. With the syntax `iptest all`. This runs our entire test suite by
8 calling this script (with different arguments) or trial recursively. This
8 calling this script (with different arguments) or trial recursively. This
9 causes modules and package to be tested in different processes, using nose
9 causes modules and package to be tested in different processes, using nose
10 or trial where appropriate.
10 or trial where appropriate.
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 the script simply calls nose, but with special command line flags and
12 the script simply calls nose, but with special command line flags and
13 plugins loaded.
13 plugins loaded.
14
14
15 For now, this script requires that both nose and twisted are installed. This
15 For now, this script requires that both nose and twisted are installed. This
16 will change in the future.
16 will change in the future.
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2009 The IPython Development Team
20 # Copyright (C) 2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 # Stdlib
30 # Stdlib
31 import os
31 import os
32 import os.path as path
32 import os.path as path
33 import signal
33 import signal
34 import sys
34 import sys
35 import subprocess
35 import subprocess
36 import tempfile
36 import tempfile
37 import time
37 import time
38 import warnings
38 import warnings
39
39
40 # Note: monkeypatch!
40 # Note: monkeypatch!
41 # We need to monkeypatch a small problem in nose itself first, before importing
41 # We need to monkeypatch a small problem in nose itself first, before importing
42 # it for actual use. This should get into nose upstream, but its release cycle
42 # it for actual use. This should get into nose upstream, but its release cycle
43 # is slow and we need it for our parametric tests to work correctly.
43 # is slow and we need it for our parametric tests to work correctly.
44 from IPython.testing import nosepatch
44 from IPython.testing import nosepatch
45 # Now, proceed to import nose itself
45 # Now, proceed to import nose itself
46 import nose.plugins.builtin
46 import nose.plugins.builtin
47 from nose.core import TestProgram
47 from nose.core import TestProgram
48
48
49 # Our own imports
49 # Our own imports
50 from IPython.utils.path import get_ipython_module_path
50 from IPython.utils.path import get_ipython_module_path
51 from IPython.utils.process import find_cmd, pycmd2argv
51 from IPython.utils.process import find_cmd, pycmd2argv
52 from IPython.utils.sysinfo import sys_info
52 from IPython.utils.sysinfo import sys_info
53
53
54 from IPython.testing import globalipapp
54 from IPython.testing import globalipapp
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
56
56
57 pjoin = path.join
57 pjoin = path.join
58
58
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Globals
61 # Globals
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Warnings control
66 # Warnings control
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
70 # that imports 'sets' as of today
70 # that imports 'sets' as of today
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
72 DeprecationWarning )
72 DeprecationWarning )
73
73
74 # This one also comes from Twisted
74 # This one also comes from Twisted
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
76 DeprecationWarning)
76 DeprecationWarning)
77
77
78 # Wx on Fedora11 spits these out
78 # Wx on Fedora11 spits these out
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
80 UserWarning)
80 UserWarning)
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Logic for skipping doctests
83 # Logic for skipping doctests
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 def test_for(mod):
86 def test_for(mod):
87 """Test to see if mod is importable."""
87 """Test to see if mod is importable."""
88 try:
88 try:
89 __import__(mod)
89 __import__(mod)
90 except (ImportError, RuntimeError):
90 except (ImportError, RuntimeError):
91 # GTK reports Runtime error if it can't be initialized even if it's
91 # GTK reports Runtime error if it can't be initialized even if it's
92 # importable.
92 # importable.
93 return False
93 return False
94 else:
94 else:
95 return True
95 return True
96
96
97 # Global dict where we can store information on what we have and what we don't
97 # Global dict where we can store information on what we have and what we don't
98 # have available at test run time
98 # have available at test run time
99 have = {}
99 have = {}
100
100
101 have['curses'] = test_for('_curses')
101 have['curses'] = test_for('_curses')
102 have['wx'] = test_for('wx')
102 have['wx'] = test_for('wx')
103 have['wx.aui'] = test_for('wx.aui')
103 have['wx.aui'] = test_for('wx.aui')
104 have['zope.interface'] = test_for('zope.interface')
104 have['zope.interface'] = test_for('zope.interface')
105 have['twisted'] = test_for('twisted')
105 have['twisted'] = test_for('twisted')
106 have['foolscap'] = test_for('foolscap')
106 have['foolscap'] = test_for('foolscap')
107 have['pexpect'] = test_for('pexpect')
107 have['pexpect'] = test_for('pexpect')
108 have['gtk'] = test_for('gtk')
108 have['gtk'] = test_for('gtk')
109 have['gobject'] = test_for('gobject')
109 have['gobject'] = test_for('gobject')
110
110
111 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
112 # Functions and classes
112 # Functions and classes
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114
114
115 def report():
115 def report():
116 """Return a string with a summary report of test-related variables."""
116 """Return a string with a summary report of test-related variables."""
117
117
118 out = [ sys_info() ]
118 out = [ sys_info() ]
119
119
120 avail = []
120 avail = []
121 not_avail = []
121 not_avail = []
122
122
123 for k, is_avail in have.items():
123 for k, is_avail in have.items():
124 if is_avail:
124 if is_avail:
125 avail.append(k)
125 avail.append(k)
126 else:
126 else:
127 not_avail.append(k)
127 not_avail.append(k)
128
128
129 if avail:
129 if avail:
130 out.append('\nTools and libraries available at test time:\n')
130 out.append('\nTools and libraries available at test time:\n')
131 avail.sort()
131 avail.sort()
132 out.append(' ' + ' '.join(avail)+'\n')
132 out.append(' ' + ' '.join(avail)+'\n')
133
133
134 if not_avail:
134 if not_avail:
135 out.append('\nTools and libraries NOT available at test time:\n')
135 out.append('\nTools and libraries NOT available at test time:\n')
136 not_avail.sort()
136 not_avail.sort()
137 out.append(' ' + ' '.join(not_avail)+'\n')
137 out.append(' ' + ' '.join(not_avail)+'\n')
138
138
139 return ''.join(out)
139 return ''.join(out)
140
140
141
141
142 def make_exclude():
142 def make_exclude():
143 """Make patterns of modules and packages to exclude from testing.
143 """Make patterns of modules and packages to exclude from testing.
144
144
145 For the IPythonDoctest plugin, we need to exclude certain patterns that
145 For the IPythonDoctest plugin, we need to exclude certain patterns that
146 cause testing problems. We should strive to minimize the number of
146 cause testing problems. We should strive to minimize the number of
147 skipped modules, since this means untested code.
147 skipped modules, since this means untested code.
148
148
149 These modules and packages will NOT get scanned by nose at all for tests.
149 These modules and packages will NOT get scanned by nose at all for tests.
150 """
150 """
151 # Simple utility to make IPython paths more readably, we need a lot of
151 # Simple utility to make IPython paths more readably, we need a lot of
152 # these below
152 # these below
153 ipjoin = lambda *paths: pjoin('IPython', *paths)
153 ipjoin = lambda *paths: pjoin('IPython', *paths)
154
154
155 exclusions = [ipjoin('external'),
155 exclusions = [ipjoin('external'),
156 pjoin('IPython_doctest_plugin'),
156 pjoin('IPython_doctest_plugin'),
157 ipjoin('quarantine'),
157 ipjoin('quarantine'),
158 ipjoin('deathrow'),
158 ipjoin('deathrow'),
159 ipjoin('testing', 'attic'),
159 ipjoin('testing', 'attic'),
160 # This guy is probably attic material
160 # This guy is probably attic material
161 ipjoin('testing', 'mkdoctests'),
161 ipjoin('testing', 'mkdoctests'),
162 # Testing inputhook will need a lot of thought, to figure out
162 # Testing inputhook will need a lot of thought, to figure out
163 # how to have tests that don't lock up with the gui event
163 # how to have tests that don't lock up with the gui event
164 # loops in the picture
164 # loops in the picture
165 ipjoin('lib', 'inputhook'),
165 ipjoin('lib', 'inputhook'),
166 # Config files aren't really importable stand-alone
166 # Config files aren't really importable stand-alone
167 ipjoin('config', 'default'),
167 ipjoin('config', 'default'),
168 ipjoin('config', 'profile'),
168 ipjoin('config', 'profile'),
169 ]
169 ]
170
170
171 if not have['wx']:
171 if not have['wx']:
172 exclusions.append(ipjoin('lib', 'inputhookwx'))
172 exclusions.append(ipjoin('lib', 'inputhookwx'))
173
173
174 if not have['gtk'] or not have['gobject']:
174 if not have['gtk'] or not have['gobject']:
175 exclusions.append(ipjoin('lib', 'inputhookgtk'))
175 exclusions.append(ipjoin('lib', 'inputhookgtk'))
176
176
177 # These have to be skipped on win32 because the use echo, rm, cd, etc.
177 # These have to be skipped on win32 because the use echo, rm, cd, etc.
178 # See ticket https://bugs.launchpad.net/bugs/366982
178 # See ticket https://bugs.launchpad.net/bugs/366982
179 if sys.platform == 'win32':
179 if sys.platform == 'win32':
180 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
180 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
181 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
181 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
182
182
183 if not have['pexpect']:
183 if not have['pexpect']:
184 exclusions.extend([ipjoin('scripts', 'irunner'),
184 exclusions.extend([ipjoin('scripts', 'irunner'),
185 ipjoin('lib', 'irunner')])
185 ipjoin('lib', 'irunner')])
186
186
187 # This is scary. We still have things in frontend and testing that
187 # This is scary. We still have things in frontend and testing that
188 # are being tested by nose that use twisted. We need to rethink
188 # are being tested by nose that use twisted. We need to rethink
189 # how we are isolating dependencies in testing.
189 # how we are isolating dependencies in testing.
190 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
190 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
191 exclusions.extend(
191 exclusions.extend(
192 [ipjoin('testing', 'parametric'),
192 [ipjoin('testing', 'parametric'),
193 ipjoin('testing', 'util'),
193 ipjoin('testing', 'util'),
194 ipjoin('testing', 'tests', 'test_decorators_trial'),
194 ipjoin('testing', 'tests', 'test_decorators_trial'),
195 ] )
195 ] )
196
196
197 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
197 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
198 if sys.platform == 'win32':
198 if sys.platform == 'win32':
199 exclusions = [s.replace('\\','\\\\') for s in exclusions]
199 exclusions = [s.replace('\\','\\\\') for s in exclusions]
200
200
201 return exclusions
201 return exclusions
202
202
203
203
204 class IPTester(object):
204 class IPTester(object):
205 """Call that calls iptest or trial in a subprocess.
205 """Call that calls iptest or trial in a subprocess.
206 """
206 """
207 #: string, name of test runner that will be called
207 #: string, name of test runner that will be called
208 runner = None
208 runner = None
209 #: list, parameters for test runner
209 #: list, parameters for test runner
210 params = None
210 params = None
211 #: list, arguments of system call to be made to call test runner
211 #: list, arguments of system call to be made to call test runner
212 call_args = None
212 call_args = None
213 #: list, process ids of subprocesses we start (for cleanup)
213 #: list, process ids of subprocesses we start (for cleanup)
214 pids = None
214 pids = None
215
215
216 def __init__(self, runner='iptest', params=None):
216 def __init__(self, runner='iptest', params=None):
217 """Create new test runner."""
217 """Create new test runner."""
218 p = os.path
218 p = os.path
219 if runner == 'iptest':
219 if runner == 'iptest':
220 iptest_app = get_ipython_module_path('IPython.testing.iptest')
220 iptest_app = get_ipython_module_path('IPython.testing.iptest')
221 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
221 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
222 elif runner == 'trial':
222 elif runner == 'trial':
223 # For trial, it needs to be installed system-wide
223 # For trial, it needs to be installed system-wide
224 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
224 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
225 else:
225 else:
226 raise Exception('Not a valid test runner: %s' % repr(runner))
226 raise Exception('Not a valid test runner: %s' % repr(runner))
227 if params is None:
227 if params is None:
228 params = []
228 params = []
229 if isinstance(params, str):
229 if isinstance(params, str):
230 params = [params]
230 params = [params]
231 self.params = params
231 self.params = params
232
232
233 # Assemble call
233 # Assemble call
234 self.call_args = self.runner+self.params
234 self.call_args = self.runner+self.params
235
235
236 # Store pids of anything we start to clean up on deletion, if possible
236 # Store pids of anything we start to clean up on deletion, if possible
237 # (on posix only, since win32 has no os.kill)
237 # (on posix only, since win32 has no os.kill)
238 self.pids = []
238 self.pids = []
239
239
240 if sys.platform == 'win32':
240 if sys.platform == 'win32':
241 def _run_cmd(self):
241 def _run_cmd(self):
242 # On Windows, use os.system instead of subprocess.call, because I
242 # On Windows, use os.system instead of subprocess.call, because I
243 # was having problems with subprocess and I just don't know enough
243 # was having problems with subprocess and I just don't know enough
244 # about win32 to debug this reliably. Os.system may be the 'old
244 # about win32 to debug this reliably. Os.system may be the 'old
245 # fashioned' way to do it, but it works just fine. If someone
245 # fashioned' way to do it, but it works just fine. If someone
246 # later can clean this up that's fine, as long as the tests run
246 # later can clean this up that's fine, as long as the tests run
247 # reliably in win32.
247 # reliably in win32.
248 # What types of problems are you having. They may be related to
248 # What types of problems are you having. They may be related to
249 # running Python in unboffered mode. BG.
249 # running Python in unboffered mode. BG.
250 return os.system(' '.join(self.call_args))
250 return os.system(' '.join(self.call_args))
251 else:
251 else:
252 def _run_cmd(self):
252 def _run_cmd(self):
253 #print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
253 # print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
254 subp = subprocess.Popen(self.call_args)
254 subp = subprocess.Popen(self.call_args)
255 self.pids.append(subp.pid)
255 self.pids.append(subp.pid)
256 # If this fails, the pid will be left in self.pids and cleaned up
256 # If this fails, the pid will be left in self.pids and cleaned up
257 # later, but if the wait call succeeds, then we can clear the
257 # later, but if the wait call succeeds, then we can clear the
258 # stored pid.
258 # stored pid.
259 retcode = subp.wait()
259 retcode = subp.wait()
260 self.pids.pop()
260 self.pids.pop()
261 return retcode
261 return retcode
262
262
263 def run(self):
263 def run(self):
264 """Run the stored commands"""
264 """Run the stored commands"""
265 try:
265 try:
266 return self._run_cmd()
266 return self._run_cmd()
267 except:
267 except:
268 import traceback
268 import traceback
269 traceback.print_exc()
269 traceback.print_exc()
270 return 1 # signal failure
270 return 1 # signal failure
271
271
272 def __del__(self):
272 def __del__(self):
273 """Cleanup on exit by killing any leftover processes."""
273 """Cleanup on exit by killing any leftover processes."""
274
274
275 if not hasattr(os, 'kill'):
275 if not hasattr(os, 'kill'):
276 return
276 return
277
277
278 for pid in self.pids:
278 for pid in self.pids:
279 try:
279 try:
280 print 'Cleaning stale PID:', pid
280 print 'Cleaning stale PID:', pid
281 os.kill(pid, signal.SIGKILL)
281 os.kill(pid, signal.SIGKILL)
282 except OSError:
282 except OSError:
283 # This is just a best effort, if we fail or the process was
283 # This is just a best effort, if we fail or the process was
284 # really gone, ignore it.
284 # really gone, ignore it.
285 pass
285 pass
286
286
287
287
288 def make_runners():
288 def make_runners():
289 """Define the top-level packages that need to be tested.
289 """Define the top-level packages that need to be tested.
290 """
290 """
291
291
292 # Packages to be tested via nose, that only depend on the stdlib
292 # Packages to be tested via nose, that only depend on the stdlib
293 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
293 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
294 'scripts', 'testing', 'utils' ]
294 'scripts', 'testing', 'utils' ]
295 # The machinery in kernel needs twisted for real testing
295 # The machinery in kernel needs twisted for real testing
296 trial_pkg_names = []
296 trial_pkg_names = []
297
297
298 # And add twisted ones if conditions are met
298 # And add twisted ones if conditions are met
299 if have['zope.interface'] and have['twisted'] and have['foolscap']:
299 if have['zope.interface'] and have['twisted'] and have['foolscap']:
300 # We only list IPython.kernel for testing using twisted.trial as
300 # We only list IPython.kernel for testing using twisted.trial as
301 # nose and twisted.trial have conflicts that make the testing system
301 # nose and twisted.trial have conflicts that make the testing system
302 # unstable.
302 # unstable.
303 trial_pkg_names.append('kernel')
303 trial_pkg_names.append('kernel')
304
304
305 # For debugging this code, only load quick stuff
305 # For debugging this code, only load quick stuff
306 #nose_pkg_names = ['core', 'extensions'] # dbg
306 #nose_pkg_names = ['core', 'extensions'] # dbg
307 #trial_pkg_names = [] # dbg
307 #trial_pkg_names = [] # dbg
308
308
309 # Make fully qualified package names prepending 'IPython.' to our name lists
309 # Make fully qualified package names prepending 'IPython.' to our name lists
310 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
310 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
311 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
311 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
312
312
313 # Make runners
313 # Make runners
314 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
314 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
315 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
315 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
316
316
317 return runners
317 return runners
318
318
319
319
320 def run_iptest():
320 def run_iptest():
321 """Run the IPython test suite using nose.
321 """Run the IPython test suite using nose.
322
322
323 This function is called when this script is **not** called with the form
323 This function is called when this script is **not** called with the form
324 `iptest all`. It simply calls nose with appropriate command line flags
324 `iptest all`. It simply calls nose with appropriate command line flags
325 and accepts all of the standard nose arguments.
325 and accepts all of the standard nose arguments.
326 """
326 """
327
327
328 warnings.filterwarnings('ignore',
328 warnings.filterwarnings('ignore',
329 'This will be removed soon. Use IPython.testing.util instead')
329 'This will be removed soon. Use IPython.testing.util instead')
330
330
331 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
331 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
332
332
333 # Loading ipdoctest causes problems with Twisted, but
333 # Loading ipdoctest causes problems with Twisted, but
334 # our test suite runner now separates things and runs
334 # our test suite runner now separates things and runs
335 # all Twisted tests with trial.
335 # all Twisted tests with trial.
336 '--with-ipdoctest',
336 '--with-ipdoctest',
337 '--ipdoctest-tests','--ipdoctest-extension=txt',
337 '--ipdoctest-tests','--ipdoctest-extension=txt',
338
338
339 # We add --exe because of setuptools' imbecility (it
339 # We add --exe because of setuptools' imbecility (it
340 # blindly does chmod +x on ALL files). Nose does the
340 # blindly does chmod +x on ALL files). Nose does the
341 # right thing and it tries to avoid executables,
341 # right thing and it tries to avoid executables,
342 # setuptools unfortunately forces our hand here. This
342 # setuptools unfortunately forces our hand here. This
343 # has been discussed on the distutils list and the
343 # has been discussed on the distutils list and the
344 # setuptools devs refuse to fix this problem!
344 # setuptools devs refuse to fix this problem!
345 '--exe',
345 '--exe',
346 ]
346 ]
347
347
348 if nose.__version__ >= '0.11':
348 if nose.__version__ >= '0.11':
349 # I don't fully understand why we need this one, but depending on what
349 # I don't fully understand why we need this one, but depending on what
350 # directory the test suite is run from, if we don't give it, 0 tests
350 # directory the test suite is run from, if we don't give it, 0 tests
351 # get run. Specifically, if the test suite is run from the source dir
351 # get run. Specifically, if the test suite is run from the source dir
352 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
352 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
353 # even if the same call done in this directory works fine). It appears
353 # even if the same call done in this directory works fine). It appears
354 # that if the requested package is in the current dir, nose bails early
354 # that if the requested package is in the current dir, nose bails early
355 # by default. Since it's otherwise harmless, leave it in by default
355 # by default. Since it's otherwise harmless, leave it in by default
356 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
356 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
357 argv.append('--traverse-namespace')
357 argv.append('--traverse-namespace')
358
358
359 # Construct list of plugins, omitting the existing doctest plugin, which
359 # Construct list of plugins, omitting the existing doctest plugin, which
360 # ours replaces (and extends).
360 # ours replaces (and extends).
361 plugins = [IPythonDoctest(make_exclude())]
361 plugins = [IPythonDoctest(make_exclude())]
362 for p in nose.plugins.builtin.plugins:
362 for p in nose.plugins.builtin.plugins:
363 plug = p()
363 plug = p()
364 if plug.name == 'doctest':
364 if plug.name == 'doctest':
365 continue
365 continue
366 plugins.append(plug)
366 plugins.append(plug)
367
367
368 # We need a global ipython running in this process
368 # We need a global ipython running in this process
369 globalipapp.start_ipython()
369 globalipapp.start_ipython()
370 # Now nose can run
370 # Now nose can run
371 TestProgram(argv=argv, plugins=plugins)
371 TestProgram(argv=argv, plugins=plugins)
372
372
373
373
374 def run_iptestall():
374 def run_iptestall():
375 """Run the entire IPython test suite by calling nose and trial.
375 """Run the entire IPython test suite by calling nose and trial.
376
376
377 This function constructs :class:`IPTester` instances for all IPython
377 This function constructs :class:`IPTester` instances for all IPython
378 modules and package and then runs each of them. This causes the modules
378 modules and package and then runs each of them. This causes the modules
379 and packages of IPython to be tested each in their own subprocess using
379 and packages of IPython to be tested each in their own subprocess using
380 nose or twisted.trial appropriately.
380 nose or twisted.trial appropriately.
381 """
381 """
382
382
383 runners = make_runners()
383 runners = make_runners()
384
384
385 # Run the test runners in a temporary dir so we can nuke it when finished
385 # Run the test runners in a temporary dir so we can nuke it when finished
386 # to clean up any junk files left over by accident. This also makes it
386 # to clean up any junk files left over by accident. This also makes it
387 # robust against being run in non-writeable directories by mistake, as the
387 # robust against being run in non-writeable directories by mistake, as the
388 # temp dir will always be user-writeable.
388 # temp dir will always be user-writeable.
389 curdir = os.getcwd()
389 curdir = os.getcwd()
390 testdir = tempfile.gettempdir()
390 testdir = tempfile.gettempdir()
391 os.chdir(testdir)
391 os.chdir(testdir)
392
392
393 # Run all test runners, tracking execution time
393 # Run all test runners, tracking execution time
394 failed = []
394 failed = []
395 t_start = time.time()
395 t_start = time.time()
396 try:
396 try:
397 for (name, runner) in runners:
397 for (name, runner) in runners:
398 print '*'*70
398 print '*'*70
399 print 'IPython test group:',name
399 print 'IPython test group:',name
400 res = runner.run()
400 res = runner.run()
401 if res:
401 if res:
402 failed.append( (name, runner) )
402 failed.append( (name, runner) )
403 finally:
403 finally:
404 os.chdir(curdir)
404 os.chdir(curdir)
405 t_end = time.time()
405 t_end = time.time()
406 t_tests = t_end - t_start
406 t_tests = t_end - t_start
407 nrunners = len(runners)
407 nrunners = len(runners)
408 nfail = len(failed)
408 nfail = len(failed)
409 # summarize results
409 # summarize results
410 print
410 print
411 print '*'*70
411 print '*'*70
412 print 'Test suite completed for system with the following information:'
412 print 'Test suite completed for system with the following information:'
413 print report()
413 print report()
414 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
414 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
415 print
415 print
416 print 'Status:'
416 print 'Status:'
417 if not failed:
417 if not failed:
418 print 'OK'
418 print 'OK'
419 else:
419 else:
420 # If anything went wrong, point out what command to rerun manually to
420 # If anything went wrong, point out what command to rerun manually to
421 # see the actual errors and individual summary
421 # see the actual errors and individual summary
422 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
422 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
423 for name, failed_runner in failed:
423 for name, failed_runner in failed:
424 print '-'*40
424 print '-'*40
425 print 'Runner failed:',name
425 print 'Runner failed:',name
426 print 'You may wish to rerun this one individually, with:'
426 print 'You may wish to rerun this one individually, with:'
427 print ' '.join(failed_runner.call_args)
427 print ' '.join(failed_runner.call_args)
428 print
428 print
429
429
430
430
431 def main():
431 def main():
432 for arg in sys.argv[1:]:
432 for arg in sys.argv[1:]:
433 if arg.startswith('IPython'):
433 if arg.startswith('IPython'):
434 # This is in-process
434 # This is in-process
435 run_iptest()
435 run_iptest()
436 else:
436 else:
437 # This starts subprocesses
437 # This starts subprocesses
438 run_iptestall()
438 run_iptestall()
439
439
440
440
441 if __name__ == '__main__':
441 if __name__ == '__main__':
442 main()
442 main()
@@ -1,64 +1,58 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Generic functions for extending IPython.
2 """Generic functions for extending IPython.
3
3
4 See http://cheeseshop.python.org/pypi/simplegeneric.
4 See http://cheeseshop.python.org/pypi/simplegeneric.
5
5
6 Here is an example from IPython.utils.text::
6 Here is an example from IPython.utils.text::
7
7
8 def print_lsstring(arg):
8 def print_lsstring(arg):
9 "Prettier (non-repr-like) and more informative printer for LSString"
9 "Prettier (non-repr-like) and more informative printer for LSString"
10 print "LSString (.p, .n, .l, .s available). Value:"
10 print "LSString (.p, .n, .l, .s available). Value:"
11 print arg
11 print arg
12
12
13 print_lsstring = result_display.when_type(LSString)(print_lsstring)
13 print_lsstring = result_display.when_type(LSString)(print_lsstring)
14 """
14 """
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2009 The IPython Development Team
17 # Copyright (C) 2008-2009 The IPython Development Team
18 #
18 #
19 # Distributed under the terms of the BSD License. The full license is in
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Imports
24 # Imports
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 from IPython.core.error import TryNext
27 from IPython.core.error import TryNext
28 from IPython.external.simplegeneric import generic
28 from IPython.external.simplegeneric import generic
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Imports
31 # Imports
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34
34
35 @generic
35 @generic
36 def result_display(result):
37 """Print the result of computation."""
38 raise TryNext
39
40
41 @generic
42 def inspect_object(obj):
36 def inspect_object(obj):
43 """Called when you do obj?"""
37 """Called when you do obj?"""
44 raise TryNext
38 raise TryNext
45
39
46
40
47 @generic
41 @generic
48 def complete_object(obj, prev_completions):
42 def complete_object(obj, prev_completions):
49 """Custom completer dispatching for python objects.
43 """Custom completer dispatching for python objects.
50
44
51 Parameters
45 Parameters
52 ----------
46 ----------
53 obj : object
47 obj : object
54 The object to complete.
48 The object to complete.
55 prev_completions : list
49 prev_completions : list
56 List of attributes discovered so far.
50 List of attributes discovered so far.
57
51
58 This should return the list of attributes in obj. If you only wish to
52 This should return the list of attributes in obj. If you only wish to
59 add to the attributes already discovered normally, return
53 add to the attributes already discovered normally, return
60 own_attrs + prev_completions.
54 own_attrs + prev_completions.
61 """
55 """
62 raise TryNext
56 raise TryNext
63
57
64
58
@@ -1,484 +1,489 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with strings and text.
3 Utilities for working with strings and text.
4 """
4 """
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 __main__
17 import __main__
18
18
19 import os
19 import os
20 import re
20 import re
21 import shutil
21 import shutil
22 import types
22 import types
23
23
24 from IPython.external.path import path
24 from IPython.external.path import path
25
25
26 from IPython.utils.generics import result_display
27 from IPython.utils.io import nlprint
26 from IPython.utils.io import nlprint
28 from IPython.utils.data import flatten
27 from IPython.utils.data import flatten
29
28
30 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
31 # Code
30 # Code
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33
32
34 StringTypes = types.StringTypes
33 StringTypes = types.StringTypes
35
34
36
35
37 def unquote_ends(istr):
36 def unquote_ends(istr):
38 """Remove a single pair of quotes from the endpoints of a string."""
37 """Remove a single pair of quotes from the endpoints of a string."""
39
38
40 if not istr:
39 if not istr:
41 return istr
40 return istr
42 if (istr[0]=="'" and istr[-1]=="'") or \
41 if (istr[0]=="'" and istr[-1]=="'") or \
43 (istr[0]=='"' and istr[-1]=='"'):
42 (istr[0]=='"' and istr[-1]=='"'):
44 return istr[1:-1]
43 return istr[1:-1]
45 else:
44 else:
46 return istr
45 return istr
47
46
48
47
49 class LSString(str):
48 class LSString(str):
50 """String derivative with a special access attributes.
49 """String derivative with a special access attributes.
51
50
52 These are normal strings, but with the special attributes:
51 These are normal strings, but with the special attributes:
53
52
54 .l (or .list) : value as list (split on newlines).
53 .l (or .list) : value as list (split on newlines).
55 .n (or .nlstr): original value (the string itself).
54 .n (or .nlstr): original value (the string itself).
56 .s (or .spstr): value as whitespace-separated string.
55 .s (or .spstr): value as whitespace-separated string.
57 .p (or .paths): list of path objects
56 .p (or .paths): list of path objects
58
57
59 Any values which require transformations are computed only once and
58 Any values which require transformations are computed only once and
60 cached.
59 cached.
61
60
62 Such strings are very useful to efficiently interact with the shell, which
61 Such strings are very useful to efficiently interact with the shell, which
63 typically only understands whitespace-separated options for commands."""
62 typically only understands whitespace-separated options for commands."""
64
63
65 def get_list(self):
64 def get_list(self):
66 try:
65 try:
67 return self.__list
66 return self.__list
68 except AttributeError:
67 except AttributeError:
69 self.__list = self.split('\n')
68 self.__list = self.split('\n')
70 return self.__list
69 return self.__list
71
70
72 l = list = property(get_list)
71 l = list = property(get_list)
73
72
74 def get_spstr(self):
73 def get_spstr(self):
75 try:
74 try:
76 return self.__spstr
75 return self.__spstr
77 except AttributeError:
76 except AttributeError:
78 self.__spstr = self.replace('\n',' ')
77 self.__spstr = self.replace('\n',' ')
79 return self.__spstr
78 return self.__spstr
80
79
81 s = spstr = property(get_spstr)
80 s = spstr = property(get_spstr)
82
81
83 def get_nlstr(self):
82 def get_nlstr(self):
84 return self
83 return self
85
84
86 n = nlstr = property(get_nlstr)
85 n = nlstr = property(get_nlstr)
87
86
88 def get_paths(self):
87 def get_paths(self):
89 try:
88 try:
90 return self.__paths
89 return self.__paths
91 except AttributeError:
90 except AttributeError:
92 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
91 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
93 return self.__paths
92 return self.__paths
94
93
95 p = paths = property(get_paths)
94 p = paths = property(get_paths)
96
95
96 # FIXME: We need to reimplement type specific displayhook and then add this
97 # back as a custom printer. This should also be moved outside utils into the
98 # core.
97
99
98 def print_lsstring(arg):
100 # def print_lsstring(arg):
99 """ Prettier (non-repr-like) and more informative printer for LSString """
101 # """ Prettier (non-repr-like) and more informative printer for LSString """
100 print "LSString (.p, .n, .l, .s available). Value:"
102 # print "LSString (.p, .n, .l, .s available). Value:"
101 print arg
103 # print arg
102
104 #
103
105 #
104 print_lsstring = result_display.when_type(LSString)(print_lsstring)
106 # print_lsstring = result_display.when_type(LSString)(print_lsstring)
105
107
106
108
107 class SList(list):
109 class SList(list):
108 """List derivative with a special access attributes.
110 """List derivative with a special access attributes.
109
111
110 These are normal lists, but with the special attributes:
112 These are normal lists, but with the special attributes:
111
113
112 .l (or .list) : value as list (the list itself).
114 .l (or .list) : value as list (the list itself).
113 .n (or .nlstr): value as a string, joined on newlines.
115 .n (or .nlstr): value as a string, joined on newlines.
114 .s (or .spstr): value as a string, joined on spaces.
116 .s (or .spstr): value as a string, joined on spaces.
115 .p (or .paths): list of path objects
117 .p (or .paths): list of path objects
116
118
117 Any values which require transformations are computed only once and
119 Any values which require transformations are computed only once and
118 cached."""
120 cached."""
119
121
120 def get_list(self):
122 def get_list(self):
121 return self
123 return self
122
124
123 l = list = property(get_list)
125 l = list = property(get_list)
124
126
125 def get_spstr(self):
127 def get_spstr(self):
126 try:
128 try:
127 return self.__spstr
129 return self.__spstr
128 except AttributeError:
130 except AttributeError:
129 self.__spstr = ' '.join(self)
131 self.__spstr = ' '.join(self)
130 return self.__spstr
132 return self.__spstr
131
133
132 s = spstr = property(get_spstr)
134 s = spstr = property(get_spstr)
133
135
134 def get_nlstr(self):
136 def get_nlstr(self):
135 try:
137 try:
136 return self.__nlstr
138 return self.__nlstr
137 except AttributeError:
139 except AttributeError:
138 self.__nlstr = '\n'.join(self)
140 self.__nlstr = '\n'.join(self)
139 return self.__nlstr
141 return self.__nlstr
140
142
141 n = nlstr = property(get_nlstr)
143 n = nlstr = property(get_nlstr)
142
144
143 def get_paths(self):
145 def get_paths(self):
144 try:
146 try:
145 return self.__paths
147 return self.__paths
146 except AttributeError:
148 except AttributeError:
147 self.__paths = [path(p) for p in self if os.path.exists(p)]
149 self.__paths = [path(p) for p in self if os.path.exists(p)]
148 return self.__paths
150 return self.__paths
149
151
150 p = paths = property(get_paths)
152 p = paths = property(get_paths)
151
153
152 def grep(self, pattern, prune = False, field = None):
154 def grep(self, pattern, prune = False, field = None):
153 """ Return all strings matching 'pattern' (a regex or callable)
155 """ Return all strings matching 'pattern' (a regex or callable)
154
156
155 This is case-insensitive. If prune is true, return all items
157 This is case-insensitive. If prune is true, return all items
156 NOT matching the pattern.
158 NOT matching the pattern.
157
159
158 If field is specified, the match must occur in the specified
160 If field is specified, the match must occur in the specified
159 whitespace-separated field.
161 whitespace-separated field.
160
162
161 Examples::
163 Examples::
162
164
163 a.grep( lambda x: x.startswith('C') )
165 a.grep( lambda x: x.startswith('C') )
164 a.grep('Cha.*log', prune=1)
166 a.grep('Cha.*log', prune=1)
165 a.grep('chm', field=-1)
167 a.grep('chm', field=-1)
166 """
168 """
167
169
168 def match_target(s):
170 def match_target(s):
169 if field is None:
171 if field is None:
170 return s
172 return s
171 parts = s.split()
173 parts = s.split()
172 try:
174 try:
173 tgt = parts[field]
175 tgt = parts[field]
174 return tgt
176 return tgt
175 except IndexError:
177 except IndexError:
176 return ""
178 return ""
177
179
178 if isinstance(pattern, basestring):
180 if isinstance(pattern, basestring):
179 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
181 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
180 else:
182 else:
181 pred = pattern
183 pred = pattern
182 if not prune:
184 if not prune:
183 return SList([el for el in self if pred(match_target(el))])
185 return SList([el for el in self if pred(match_target(el))])
184 else:
186 else:
185 return SList([el for el in self if not pred(match_target(el))])
187 return SList([el for el in self if not pred(match_target(el))])
186
188
187 def fields(self, *fields):
189 def fields(self, *fields):
188 """ Collect whitespace-separated fields from string list
190 """ Collect whitespace-separated fields from string list
189
191
190 Allows quick awk-like usage of string lists.
192 Allows quick awk-like usage of string lists.
191
193
192 Example data (in var a, created by 'a = !ls -l')::
194 Example data (in var a, created by 'a = !ls -l')::
193 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
195 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
194 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
196 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
195
197
196 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
198 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
197 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
199 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
198 (note the joining by space).
200 (note the joining by space).
199 a.fields(-1) is ['ChangeLog', 'IPython']
201 a.fields(-1) is ['ChangeLog', 'IPython']
200
202
201 IndexErrors are ignored.
203 IndexErrors are ignored.
202
204
203 Without args, fields() just split()'s the strings.
205 Without args, fields() just split()'s the strings.
204 """
206 """
205 if len(fields) == 0:
207 if len(fields) == 0:
206 return [el.split() for el in self]
208 return [el.split() for el in self]
207
209
208 res = SList()
210 res = SList()
209 for el in [f.split() for f in self]:
211 for el in [f.split() for f in self]:
210 lineparts = []
212 lineparts = []
211
213
212 for fd in fields:
214 for fd in fields:
213 try:
215 try:
214 lineparts.append(el[fd])
216 lineparts.append(el[fd])
215 except IndexError:
217 except IndexError:
216 pass
218 pass
217 if lineparts:
219 if lineparts:
218 res.append(" ".join(lineparts))
220 res.append(" ".join(lineparts))
219
221
220 return res
222 return res
221
223
222 def sort(self,field= None, nums = False):
224 def sort(self,field= None, nums = False):
223 """ sort by specified fields (see fields())
225 """ sort by specified fields (see fields())
224
226
225 Example::
227 Example::
226 a.sort(1, nums = True)
228 a.sort(1, nums = True)
227
229
228 Sorts a by second field, in numerical order (so that 21 > 3)
230 Sorts a by second field, in numerical order (so that 21 > 3)
229
231
230 """
232 """
231
233
232 #decorate, sort, undecorate
234 #decorate, sort, undecorate
233 if field is not None:
235 if field is not None:
234 dsu = [[SList([line]).fields(field), line] for line in self]
236 dsu = [[SList([line]).fields(field), line] for line in self]
235 else:
237 else:
236 dsu = [[line, line] for line in self]
238 dsu = [[line, line] for line in self]
237 if nums:
239 if nums:
238 for i in range(len(dsu)):
240 for i in range(len(dsu)):
239 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
241 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
240 try:
242 try:
241 n = int(numstr)
243 n = int(numstr)
242 except ValueError:
244 except ValueError:
243 n = 0;
245 n = 0;
244 dsu[i][0] = n
246 dsu[i][0] = n
245
247
246
248
247 dsu.sort()
249 dsu.sort()
248 return SList([t[1] for t in dsu])
250 return SList([t[1] for t in dsu])
249
251
250
252
251 def print_slist(arg):
253 # FIXME: We need to reimplement type specific displayhook and then add this
252 """ Prettier (non-repr-like) and more informative printer for SList """
254 # back as a custom printer. This should also be moved outside utils into the
253 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
255 # core.
254 if hasattr(arg, 'hideonce') and arg.hideonce:
256
255 arg.hideonce = False
257 # def print_slist(arg):
256 return
258 # """ Prettier (non-repr-like) and more informative printer for SList """
257
259 # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
258 nlprint(arg)
260 # if hasattr(arg, 'hideonce') and arg.hideonce:
259
261 # arg.hideonce = False
260
262 # return
261 print_slist = result_display.when_type(SList)(print_slist)
263 #
264 # nlprint(arg)
265 #
266 # print_slist = result_display.when_type(SList)(print_slist)
262
267
263
268
264 def esc_quotes(strng):
269 def esc_quotes(strng):
265 """Return the input string with single and double quotes escaped out"""
270 """Return the input string with single and double quotes escaped out"""
266
271
267 return strng.replace('"','\\"').replace("'","\\'")
272 return strng.replace('"','\\"').replace("'","\\'")
268
273
269
274
270 def make_quoted_expr(s):
275 def make_quoted_expr(s):
271 """Return string s in appropriate quotes, using raw string if possible.
276 """Return string s in appropriate quotes, using raw string if possible.
272
277
273 XXX - example removed because it caused encoding errors in documentation
278 XXX - example removed because it caused encoding errors in documentation
274 generation. We need a new example that doesn't contain invalid chars.
279 generation. We need a new example that doesn't contain invalid chars.
275
280
276 Note the use of raw string and padding at the end to allow trailing
281 Note the use of raw string and padding at the end to allow trailing
277 backslash.
282 backslash.
278 """
283 """
279
284
280 tail = ''
285 tail = ''
281 tailpadding = ''
286 tailpadding = ''
282 raw = ''
287 raw = ''
283 if "\\" in s:
288 if "\\" in s:
284 raw = 'r'
289 raw = 'r'
285 if s.endswith('\\'):
290 if s.endswith('\\'):
286 tail = '[:-1]'
291 tail = '[:-1]'
287 tailpadding = '_'
292 tailpadding = '_'
288 if '"' not in s:
293 if '"' not in s:
289 quote = '"'
294 quote = '"'
290 elif "'" not in s:
295 elif "'" not in s:
291 quote = "'"
296 quote = "'"
292 elif '"""' not in s and not s.endswith('"'):
297 elif '"""' not in s and not s.endswith('"'):
293 quote = '"""'
298 quote = '"""'
294 elif "'''" not in s and not s.endswith("'"):
299 elif "'''" not in s and not s.endswith("'"):
295 quote = "'''"
300 quote = "'''"
296 else:
301 else:
297 # give up, backslash-escaped string will do
302 # give up, backslash-escaped string will do
298 return '"%s"' % esc_quotes(s)
303 return '"%s"' % esc_quotes(s)
299 res = raw + quote + s + tailpadding + quote + tail
304 res = raw + quote + s + tailpadding + quote + tail
300 return res
305 return res
301
306
302
307
303 def qw(words,flat=0,sep=None,maxsplit=-1):
308 def qw(words,flat=0,sep=None,maxsplit=-1):
304 """Similar to Perl's qw() operator, but with some more options.
309 """Similar to Perl's qw() operator, but with some more options.
305
310
306 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
311 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
307
312
308 words can also be a list itself, and with flat=1, the output will be
313 words can also be a list itself, and with flat=1, the output will be
309 recursively flattened.
314 recursively flattened.
310
315
311 Examples:
316 Examples:
312
317
313 >>> qw('1 2')
318 >>> qw('1 2')
314 ['1', '2']
319 ['1', '2']
315
320
316 >>> qw(['a b','1 2',['m n','p q']])
321 >>> qw(['a b','1 2',['m n','p q']])
317 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
322 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
318
323
319 >>> qw(['a b','1 2',['m n','p q']],flat=1)
324 >>> qw(['a b','1 2',['m n','p q']],flat=1)
320 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
325 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
321 """
326 """
322
327
323 if type(words) in StringTypes:
328 if type(words) in StringTypes:
324 return [word.strip() for word in words.split(sep,maxsplit)
329 return [word.strip() for word in words.split(sep,maxsplit)
325 if word and not word.isspace() ]
330 if word and not word.isspace() ]
326 if flat:
331 if flat:
327 return flatten(map(qw,words,[1]*len(words)))
332 return flatten(map(qw,words,[1]*len(words)))
328 return map(qw,words)
333 return map(qw,words)
329
334
330
335
331 def qwflat(words,sep=None,maxsplit=-1):
336 def qwflat(words,sep=None,maxsplit=-1):
332 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
337 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
333 return qw(words,1,sep,maxsplit)
338 return qw(words,1,sep,maxsplit)
334
339
335
340
336 def qw_lol(indata):
341 def qw_lol(indata):
337 """qw_lol('a b') -> [['a','b']],
342 """qw_lol('a b') -> [['a','b']],
338 otherwise it's just a call to qw().
343 otherwise it's just a call to qw().
339
344
340 We need this to make sure the modules_some keys *always* end up as a
345 We need this to make sure the modules_some keys *always* end up as a
341 list of lists."""
346 list of lists."""
342
347
343 if type(indata) in StringTypes:
348 if type(indata) in StringTypes:
344 return [qw(indata)]
349 return [qw(indata)]
345 else:
350 else:
346 return qw(indata)
351 return qw(indata)
347
352
348
353
349 def grep(pat,list,case=1):
354 def grep(pat,list,case=1):
350 """Simple minded grep-like function.
355 """Simple minded grep-like function.
351 grep(pat,list) returns occurrences of pat in list, None on failure.
356 grep(pat,list) returns occurrences of pat in list, None on failure.
352
357
353 It only does simple string matching, with no support for regexps. Use the
358 It only does simple string matching, with no support for regexps. Use the
354 option case=0 for case-insensitive matching."""
359 option case=0 for case-insensitive matching."""
355
360
356 # This is pretty crude. At least it should implement copying only references
361 # This is pretty crude. At least it should implement copying only references
357 # to the original data in case it's big. Now it copies the data for output.
362 # to the original data in case it's big. Now it copies the data for output.
358 out=[]
363 out=[]
359 if case:
364 if case:
360 for term in list:
365 for term in list:
361 if term.find(pat)>-1: out.append(term)
366 if term.find(pat)>-1: out.append(term)
362 else:
367 else:
363 lpat=pat.lower()
368 lpat=pat.lower()
364 for term in list:
369 for term in list:
365 if term.lower().find(lpat)>-1: out.append(term)
370 if term.lower().find(lpat)>-1: out.append(term)
366
371
367 if len(out): return out
372 if len(out): return out
368 else: return None
373 else: return None
369
374
370
375
371 def dgrep(pat,*opts):
376 def dgrep(pat,*opts):
372 """Return grep() on dir()+dir(__builtins__).
377 """Return grep() on dir()+dir(__builtins__).
373
378
374 A very common use of grep() when working interactively."""
379 A very common use of grep() when working interactively."""
375
380
376 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
381 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
377
382
378
383
379 def idgrep(pat):
384 def idgrep(pat):
380 """Case-insensitive dgrep()"""
385 """Case-insensitive dgrep()"""
381
386
382 return dgrep(pat,0)
387 return dgrep(pat,0)
383
388
384
389
385 def igrep(pat,list):
390 def igrep(pat,list):
386 """Synonym for case-insensitive grep."""
391 """Synonym for case-insensitive grep."""
387
392
388 return grep(pat,list,case=0)
393 return grep(pat,list,case=0)
389
394
390
395
391 def indent(str,nspaces=4,ntabs=0):
396 def indent(str,nspaces=4,ntabs=0):
392 """Indent a string a given number of spaces or tabstops.
397 """Indent a string a given number of spaces or tabstops.
393
398
394 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
399 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
395 """
400 """
396 if str is None:
401 if str is None:
397 return
402 return
398 ind = '\t'*ntabs+' '*nspaces
403 ind = '\t'*ntabs+' '*nspaces
399 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
404 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
400 if outstr.endswith(os.linesep+ind):
405 if outstr.endswith(os.linesep+ind):
401 return outstr[:-len(ind)]
406 return outstr[:-len(ind)]
402 else:
407 else:
403 return outstr
408 return outstr
404
409
405 def native_line_ends(filename,backup=1):
410 def native_line_ends(filename,backup=1):
406 """Convert (in-place) a file to line-ends native to the current OS.
411 """Convert (in-place) a file to line-ends native to the current OS.
407
412
408 If the optional backup argument is given as false, no backup of the
413 If the optional backup argument is given as false, no backup of the
409 original file is left. """
414 original file is left. """
410
415
411 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
416 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
412
417
413 bak_filename = filename + backup_suffixes[os.name]
418 bak_filename = filename + backup_suffixes[os.name]
414
419
415 original = open(filename).read()
420 original = open(filename).read()
416 shutil.copy2(filename,bak_filename)
421 shutil.copy2(filename,bak_filename)
417 try:
422 try:
418 new = open(filename,'wb')
423 new = open(filename,'wb')
419 new.write(os.linesep.join(original.splitlines()))
424 new.write(os.linesep.join(original.splitlines()))
420 new.write(os.linesep) # ALWAYS put an eol at the end of the file
425 new.write(os.linesep) # ALWAYS put an eol at the end of the file
421 new.close()
426 new.close()
422 except:
427 except:
423 os.rename(bak_filename,filename)
428 os.rename(bak_filename,filename)
424 if not backup:
429 if not backup:
425 try:
430 try:
426 os.remove(bak_filename)
431 os.remove(bak_filename)
427 except:
432 except:
428 pass
433 pass
429
434
430
435
431 def list_strings(arg):
436 def list_strings(arg):
432 """Always return a list of strings, given a string or list of strings
437 """Always return a list of strings, given a string or list of strings
433 as input.
438 as input.
434
439
435 :Examples:
440 :Examples:
436
441
437 In [7]: list_strings('A single string')
442 In [7]: list_strings('A single string')
438 Out[7]: ['A single string']
443 Out[7]: ['A single string']
439
444
440 In [8]: list_strings(['A single string in a list'])
445 In [8]: list_strings(['A single string in a list'])
441 Out[8]: ['A single string in a list']
446 Out[8]: ['A single string in a list']
442
447
443 In [9]: list_strings(['A','list','of','strings'])
448 In [9]: list_strings(['A','list','of','strings'])
444 Out[9]: ['A', 'list', 'of', 'strings']
449 Out[9]: ['A', 'list', 'of', 'strings']
445 """
450 """
446
451
447 if isinstance(arg,basestring): return [arg]
452 if isinstance(arg,basestring): return [arg]
448 else: return arg
453 else: return arg
449
454
450
455
451 def marquee(txt='',width=78,mark='*'):
456 def marquee(txt='',width=78,mark='*'):
452 """Return the input string centered in a 'marquee'.
457 """Return the input string centered in a 'marquee'.
453
458
454 :Examples:
459 :Examples:
455
460
456 In [16]: marquee('A test',40)
461 In [16]: marquee('A test',40)
457 Out[16]: '**************** A test ****************'
462 Out[16]: '**************** A test ****************'
458
463
459 In [17]: marquee('A test',40,'-')
464 In [17]: marquee('A test',40,'-')
460 Out[17]: '---------------- A test ----------------'
465 Out[17]: '---------------- A test ----------------'
461
466
462 In [18]: marquee('A test',40,' ')
467 In [18]: marquee('A test',40,' ')
463 Out[18]: ' A test '
468 Out[18]: ' A test '
464
469
465 """
470 """
466 if not txt:
471 if not txt:
467 return (mark*width)[:width]
472 return (mark*width)[:width]
468 nmark = (width-len(txt)-2)/len(mark)/2
473 nmark = (width-len(txt)-2)/len(mark)/2
469 if nmark < 0: nmark =0
474 if nmark < 0: nmark =0
470 marks = mark*nmark
475 marks = mark*nmark
471 return '%s %s %s' % (marks,txt,marks)
476 return '%s %s %s' % (marks,txt,marks)
472
477
473
478
474 ini_spaces_re = re.compile(r'^(\s+)')
479 ini_spaces_re = re.compile(r'^(\s+)')
475
480
476 def num_ini_spaces(strng):
481 def num_ini_spaces(strng):
477 """Return the number of initial spaces in a string"""
482 """Return the number of initial spaces in a string"""
478
483
479 ini_spaces = ini_spaces_re.match(strng)
484 ini_spaces = ini_spaces_re.match(strng)
480 if ini_spaces:
485 if ini_spaces:
481 return ini_spaces.end()
486 return ini_spaces.end()
482 else:
487 else:
483 return 0
488 return 0
484
489
@@ -1,31 +1,31 b''
1 import sys
1 import sys
2 from subprocess import Popen, PIPE
2 from subprocess import Popen, PIPE
3 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
3 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
4
4
5
5
6 class ZMQInteractiveShell(InteractiveShell):
6 class ZMQInteractiveShell(InteractiveShell):
7 """A subclass of InteractiveShell for ZMQ."""
7 """A subclass of InteractiveShell for ZMQ."""
8
8
9 def system(self, cmd):
9 def system(self, cmd):
10 cmd = self.var_expand(cmd, depth=2)
10 cmd = self.var_expand(cmd, depth=2)
11 sys.stdout.flush()
11 sys.stdout.flush()
12 sys.stderr.flush()
12 sys.stderr.flush()
13 p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
13 p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
14 for line in p.stdout.read().split('\n'):
14 for line in p.stdout.read().split('\n'):
15 if len(line) > 0:
15 if len(line) > 0:
16 print line
16 print line
17 for line in p.stderr.read().split('\n'):
17 for line in p.stderr.read().split('\n'):
18 if len(line) > 0:
18 if len(line) > 0:
19 print line
19 print line
20 return p.wait()
20 p.wait()
21
21
22 def init_io(self):
22 def init_io(self):
23 # This will just use sys.stdout and sys.stderr. If you want to
23 # This will just use sys.stdout and sys.stderr. If you want to
24 # override sys.stdout and sys.stderr themselves, you need to do that
24 # override sys.stdout and sys.stderr themselves, you need to do that
25 # *before* instantiating this class, because Term holds onto
25 # *before* instantiating this class, because Term holds onto
26 # references to the underlying streams.
26 # references to the underlying streams.
27 import IPython.utils.io
27 import IPython.utils.io
28 Term = IPython.utils.io.IOTerm()
28 Term = IPython.utils.io.IOTerm()
29 IPython.utils.io.Term = Term
29 IPython.utils.io.Term = Term
30
30
31 InteractiveShellABC.register(ZMQInteractiveShell)
31 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now