##// END OF EJS Templates
Refactor multiline input and prompt management.
Fernando Perez -
Show More
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
@@ -1,288 +1,297 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian Granger
7 * Brian Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2010 The IPython Development Team
11 # Copyright (C) 2008-2010 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import __builtin__
22 import __builtin__
23 from pprint import PrettyPrinter
23 from pprint import PrettyPrinter
24 pformat = PrettyPrinter().pformat
24 pformat = PrettyPrinter().pformat
25
25
26 from IPython.config.configurable import Configurable
26 from IPython.config.configurable import Configurable
27 from IPython.core import prompts
27 from IPython.core import prompts
28 import IPython.utils.generics
28 import IPython.utils.generics
29 import IPython.utils.io
29 import IPython.utils.io
30 from IPython.utils.traitlets import Instance, Int
30 from IPython.utils.traitlets import Instance, Int
31 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Main displayhook class
34 # Main displayhook class
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37 # TODO: The DisplayHook class should be split into two classes, one that
37 # TODO: The DisplayHook class should be split into two classes, one that
38 # manages the prompts and their synchronization and another that just does the
38 # manages the prompts and their synchronization and another that just does the
39 # displayhook logic and calls into the prompt manager.
39 # displayhook logic and calls into the prompt manager.
40
40
41 # TODO: Move the various attributes (cache_size, colors, input_sep,
41 # TODO: Move the various attributes (cache_size, colors, input_sep,
42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
43 # attributes of InteractiveShell. They should be on ONE object only and the
43 # attributes of InteractiveShell. They should be on ONE object only and the
44 # other objects should ask that one object for their values.
44 # other objects should ask that one object for their values.
45
45
46 class DisplayHook(Configurable):
46 class DisplayHook(Configurable):
47 """The custom IPython displayhook to replace sys.displayhook.
47 """The custom IPython displayhook to replace sys.displayhook.
48
48
49 This class does many things, but the basic idea is that it is a callable
49 This class does many things, but the basic idea is that it is a callable
50 that gets called anytime user code returns a value.
50 that gets called anytime user code returns a value.
51
51
52 Currently this class does more than just the displayhook logic and that
52 Currently this class does more than just the displayhook logic and that
53 extra logic should eventually be moved out of here.
53 extra logic should eventually be moved out of here.
54 """
54 """
55
55
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
57
57 # Each call to the In[] prompt raises it by 1, even the first.
58 # Each call to the In[] prompt raises it by 1, even the first.
58 prompt_count = Int(0)
59 #prompt_count = Int(0)
59
60
60 def __init__(self, shell=None, cache_size=1000,
61 def __init__(self, shell=None, cache_size=1000,
61 colors='NoColor', input_sep='\n',
62 colors='NoColor', input_sep='\n',
62 output_sep='\n', output_sep2='',
63 output_sep='\n', output_sep2='',
63 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
64 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
64 config=None):
65 config=None):
65 super(DisplayHook, self).__init__(shell=shell, config=config)
66 super(DisplayHook, self).__init__(shell=shell, config=config)
66
67
67 cache_size_min = 3
68 cache_size_min = 3
68 if cache_size <= 0:
69 if cache_size <= 0:
69 self.do_full_cache = 0
70 self.do_full_cache = 0
70 cache_size = 0
71 cache_size = 0
71 elif cache_size < cache_size_min:
72 elif cache_size < cache_size_min:
72 self.do_full_cache = 0
73 self.do_full_cache = 0
73 cache_size = 0
74 cache_size = 0
74 warn('caching was disabled (min value for cache size is %s).' %
75 warn('caching was disabled (min value for cache size is %s).' %
75 cache_size_min,level=3)
76 cache_size_min,level=3)
76 else:
77 else:
77 self.do_full_cache = 1
78 self.do_full_cache = 1
78
79
79 self.cache_size = cache_size
80 self.cache_size = cache_size
80 self.input_sep = input_sep
81 self.input_sep = input_sep
81
82
82 # we need a reference to the user-level namespace
83 # we need a reference to the user-level namespace
83 self.shell = shell
84 self.shell = shell
84
85
85 # Set input prompt strings and colors
86 # Set input prompt strings and colors
86 if cache_size == 0:
87 if cache_size == 0:
87 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
88 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
88 or ps1.find(r'\N') > -1:
89 or ps1.find(r'\N') > -1:
89 ps1 = '>>> '
90 ps1 = '>>> '
90 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
91 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
91 or ps2.find(r'\N') > -1:
92 or ps2.find(r'\N') > -1:
92 ps2 = '... '
93 ps2 = '... '
93 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
94 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
94 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
95 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
95 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
96 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
96
97
97 self.color_table = prompts.PromptColors
98 self.color_table = prompts.PromptColors
98 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
99 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
99 pad_left=pad_left)
100 pad_left=pad_left)
100 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
101 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
101 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
102 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
102 pad_left=pad_left)
103 pad_left=pad_left)
103 self.set_colors(colors)
104 self.set_colors(colors)
104
105
105 # Store the last prompt string each time, we need it for aligning
106 # Store the last prompt string each time, we need it for aligning
106 # continuation and auto-rewrite prompts
107 # continuation and auto-rewrite prompts
107 self.last_prompt = ''
108 self.last_prompt = ''
108 self.output_sep = output_sep
109 self.output_sep = output_sep
109 self.output_sep2 = output_sep2
110 self.output_sep2 = output_sep2
110 self._,self.__,self.___ = '','',''
111 self._,self.__,self.___ = '','',''
111 self.pprint_types = map(type,[(),[],{}])
112 self.pprint_types = map(type,[(),[],{}])
112
113
113 # these are deliberately global:
114 # these are deliberately global:
114 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
115 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
115 self.shell.user_ns.update(to_user_ns)
116 self.shell.user_ns.update(to_user_ns)
116
117
118 @property
119 def prompt_count(self):
120 return self.shell.execution_count
121
122 @prompt_count.setter
123 def _set_prompt_count(self, val):
124 raise ValueError('prompt count is read only')
125
117 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
126 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
118 if p_str is None:
127 if p_str is None:
119 if self.do_full_cache:
128 if self.do_full_cache:
120 return cache_def
129 return cache_def
121 else:
130 else:
122 return no_cache_def
131 return no_cache_def
123 else:
132 else:
124 return p_str
133 return p_str
125
134
126 def set_colors(self, colors):
135 def set_colors(self, colors):
127 """Set the active color scheme and configure colors for the three
136 """Set the active color scheme and configure colors for the three
128 prompt subsystems."""
137 prompt subsystems."""
129
138
130 # FIXME: This modifying of the global prompts.prompt_specials needs
139 # FIXME: This modifying of the global prompts.prompt_specials needs
131 # to be fixed. We need to refactor all of the prompts stuff to use
140 # to be fixed. We need to refactor all of the prompts stuff to use
132 # proper configuration and traits notifications.
141 # proper configuration and traits notifications.
133 if colors.lower()=='nocolor':
142 if colors.lower()=='nocolor':
134 prompts.prompt_specials = prompts.prompt_specials_nocolor
143 prompts.prompt_specials = prompts.prompt_specials_nocolor
135 else:
144 else:
136 prompts.prompt_specials = prompts.prompt_specials_color
145 prompts.prompt_specials = prompts.prompt_specials_color
137
146
138 self.color_table.set_active_scheme(colors)
147 self.color_table.set_active_scheme(colors)
139 self.prompt1.set_colors()
148 self.prompt1.set_colors()
140 self.prompt2.set_colors()
149 self.prompt2.set_colors()
141 self.prompt_out.set_colors()
150 self.prompt_out.set_colors()
142
151
143 #-------------------------------------------------------------------------
152 #-------------------------------------------------------------------------
144 # Methods used in __call__. Override these methods to modify the behavior
153 # Methods used in __call__. Override these methods to modify the behavior
145 # of the displayhook.
154 # of the displayhook.
146 #-------------------------------------------------------------------------
155 #-------------------------------------------------------------------------
147
156
148 def check_for_underscore(self):
157 def check_for_underscore(self):
149 """Check if the user has set the '_' variable by hand."""
158 """Check if the user has set the '_' variable by hand."""
150 # If something injected a '_' variable in __builtin__, delete
159 # If something injected a '_' variable in __builtin__, delete
151 # ipython's automatic one so we don't clobber that. gettext() in
160 # ipython's automatic one so we don't clobber that. gettext() in
152 # particular uses _, so we need to stay away from it.
161 # particular uses _, so we need to stay away from it.
153 if '_' in __builtin__.__dict__:
162 if '_' in __builtin__.__dict__:
154 try:
163 try:
155 del self.shell.user_ns['_']
164 del self.shell.user_ns['_']
156 except KeyError:
165 except KeyError:
157 pass
166 pass
158
167
159 def quiet(self):
168 def quiet(self):
160 """Should we silence the display hook because of ';'?"""
169 """Should we silence the display hook because of ';'?"""
161 # do not print output if input ends in ';'
170 # do not print output if input ends in ';'
162 try:
171 try:
163 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
172 if self.shell.input_hist[self.prompt_count].endswith(';\n'):
164 return True
173 return True
165 except IndexError:
174 except IndexError:
166 # some uses of ipshellembed may fail here
175 # some uses of ipshellembed may fail here
167 pass
176 pass
168 return False
177 return False
169
178
170 def start_displayhook(self):
179 def start_displayhook(self):
171 """Start the displayhook, initializing resources."""
180 """Start the displayhook, initializing resources."""
172 pass
181 pass
173
182
174 def write_output_prompt(self):
183 def write_output_prompt(self):
175 """Write the output prompt."""
184 """Write the output prompt."""
176 # Use write, not print which adds an extra space.
185 # Use write, not print which adds an extra space.
177 IPython.utils.io.Term.cout.write(self.output_sep)
186 IPython.utils.io.Term.cout.write(self.output_sep)
178 outprompt = str(self.prompt_out)
187 outprompt = str(self.prompt_out)
179 if self.do_full_cache:
188 if self.do_full_cache:
180 IPython.utils.io.Term.cout.write(outprompt)
189 IPython.utils.io.Term.cout.write(outprompt)
181
190
182 # TODO: Make this method an extension point. The previous implementation
191 # TODO: Make this method an extension point. The previous implementation
183 # has both a result_display hook as well as a result_display generic
192 # has both a result_display hook as well as a result_display generic
184 # function to customize the repr on a per class basis. We need to rethink
193 # function to customize the repr on a per class basis. We need to rethink
185 # the hooks mechanism before doing this though.
194 # the hooks mechanism before doing this though.
186 def compute_result_repr(self, result):
195 def compute_result_repr(self, result):
187 """Compute and return the repr of the object to be displayed.
196 """Compute and return the repr of the object to be displayed.
188
197
189 This method only compute the string form of the repr and should NOT
198 This method only compute the string form of the repr and should NOT
190 actual print or write that to a stream. This method may also transform
199 actual print or write that to a stream. This method may also transform
191 the result itself, but the default implementation passes the original
200 the result itself, but the default implementation passes the original
192 through.
201 through.
193 """
202 """
194 try:
203 try:
195 if self.shell.pprint:
204 if self.shell.pprint:
196 result_repr = pformat(result)
205 result_repr = pformat(result)
197 if '\n' in result_repr:
206 if '\n' in result_repr:
198 # So that multi-line strings line up with the left column of
207 # So that multi-line strings line up with the left column of
199 # the screen, instead of having the output prompt mess up
208 # the screen, instead of having the output prompt mess up
200 # their first line.
209 # their first line.
201 result_repr = '\n' + result_repr
210 result_repr = '\n' + result_repr
202 else:
211 else:
203 result_repr = repr(result)
212 result_repr = repr(result)
204 except TypeError:
213 except TypeError:
205 # This happens when result.__repr__ doesn't return a string,
214 # This happens when result.__repr__ doesn't return a string,
206 # such as when it returns None.
215 # such as when it returns None.
207 result_repr = '\n'
216 result_repr = '\n'
208 return result, result_repr
217 return result, result_repr
209
218
210 def write_result_repr(self, result_repr):
219 def write_result_repr(self, result_repr):
211 # We want to print because we want to always make sure we have a
220 # We want to print because we want to always make sure we have a
212 # newline, even if all the prompt separators are ''. This is the
221 # newline, even if all the prompt separators are ''. This is the
213 # standard IPython behavior.
222 # standard IPython behavior.
214 print >>IPython.utils.io.Term.cout, result_repr
223 print >>IPython.utils.io.Term.cout, result_repr
215
224
216 def update_user_ns(self, result):
225 def update_user_ns(self, result):
217 """Update user_ns with various things like _, __, _1, etc."""
226 """Update user_ns with various things like _, __, _1, etc."""
218
227
219 # Avoid recursive reference when displaying _oh/Out
228 # Avoid recursive reference when displaying _oh/Out
220 if result is not self.shell.user_ns['_oh']:
229 if result is not self.shell.user_ns['_oh']:
221 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
230 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
222 warn('Output cache limit (currently '+
231 warn('Output cache limit (currently '+
223 `self.cache_size`+' entries) hit.\n'
232 `self.cache_size`+' entries) hit.\n'
224 'Flushing cache and resetting history counter...\n'
233 'Flushing cache and resetting history counter...\n'
225 'The only history variables available will be _,__,___ and _1\n'
234 'The only history variables available will be _,__,___ and _1\n'
226 'with the current result.')
235 'with the current result.')
227
236
228 self.flush()
237 self.flush()
229 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
238 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
230 # we cause buggy behavior for things like gettext).
239 # we cause buggy behavior for things like gettext).
231 if '_' not in __builtin__.__dict__:
240 if '_' not in __builtin__.__dict__:
232 self.___ = self.__
241 self.___ = self.__
233 self.__ = self._
242 self.__ = self._
234 self._ = result
243 self._ = result
235 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
244 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
236
245
237 # hackish access to top-level namespace to create _1,_2... dynamically
246 # hackish access to top-level namespace to create _1,_2... dynamically
238 to_main = {}
247 to_main = {}
239 if self.do_full_cache:
248 if self.do_full_cache:
240 new_result = '_'+`self.prompt_count`
249 new_result = '_'+`self.prompt_count`
241 to_main[new_result] = result
250 to_main[new_result] = result
242 self.shell.user_ns.update(to_main)
251 self.shell.user_ns.update(to_main)
243 self.shell.user_ns['_oh'][self.prompt_count] = result
252 self.shell.user_ns['_oh'][self.prompt_count] = result
244
253
245 def log_output(self, result):
254 def log_output(self, result):
246 """Log the output."""
255 """Log the output."""
247 if self.shell.logger.log_output:
256 if self.shell.logger.log_output:
248 self.shell.logger.log_write(repr(result),'output')
257 self.shell.logger.log_write(repr(result),'output')
249
258
250 def finish_displayhook(self):
259 def finish_displayhook(self):
251 """Finish up all displayhook activities."""
260 """Finish up all displayhook activities."""
252 IPython.utils.io.Term.cout.write(self.output_sep2)
261 IPython.utils.io.Term.cout.write(self.output_sep2)
253 IPython.utils.io.Term.cout.flush()
262 IPython.utils.io.Term.cout.flush()
254
263
255 def __call__(self, result=None):
264 def __call__(self, result=None):
256 """Printing with history cache management.
265 """Printing with history cache management.
257
266
258 This is invoked everytime the interpreter needs to print, and is
267 This is invoked everytime the interpreter needs to print, and is
259 activated by setting the variable sys.displayhook to it.
268 activated by setting the variable sys.displayhook to it.
260 """
269 """
261 self.check_for_underscore()
270 self.check_for_underscore()
262 if result is not None and not self.quiet():
271 if result is not None and not self.quiet():
263 self.start_displayhook()
272 self.start_displayhook()
264 self.write_output_prompt()
273 self.write_output_prompt()
265 result, result_repr = self.compute_result_repr(result)
274 result, result_repr = self.compute_result_repr(result)
266 self.write_result_repr(result_repr)
275 self.write_result_repr(result_repr)
267 self.update_user_ns(result)
276 self.update_user_ns(result)
268 self.log_output(result)
277 self.log_output(result)
269 self.finish_displayhook()
278 self.finish_displayhook()
270
279
271 def flush(self):
280 def flush(self):
272 if not self.do_full_cache:
281 if not self.do_full_cache:
273 raise ValueError,"You shouldn't have reached the cache flush "\
282 raise ValueError,"You shouldn't have reached the cache flush "\
274 "if full caching is not enabled!"
283 "if full caching is not enabled!"
275 # delete auto-generated vars from global namespace
284 # delete auto-generated vars from global namespace
276
285
277 for n in range(1,self.prompt_count + 1):
286 for n in range(1,self.prompt_count + 1):
278 key = '_'+`n`
287 key = '_'+`n`
279 try:
288 try:
280 del self.shell.user_ns[key]
289 del self.shell.user_ns[key]
281 except: pass
290 except: pass
282 self.shell.user_ns['_oh'].clear()
291 self.shell.user_ns['_oh'].clear()
283
292
284 if '_' not in __builtin__.__dict__:
293 if '_' not in __builtin__.__dict__:
285 self.shell.user_ns.update({'_':None,'__':None, '___':None})
294 self.shell.user_ns.update({'_':None,'__':None, '___':None})
286 import gc
295 import gc
287 gc.collect() # xxx needed?
296 gc.collect() # xxx needed?
288
297
@@ -1,2586 +1,2619 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.inputlist import InputList
48 from IPython.core.inputlist import InputList
49 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
51 from IPython.core.magic import Magic
51 from IPython.core.magic import Magic
52 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
53 from IPython.core.plugin import PluginManager
53 from IPython.core.plugin import PluginManager
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
56 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
57 from IPython.utils import io
57 from IPython.utils import io
58 from IPython.utils import pickleshare
58 from IPython.utils import pickleshare
59 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 from IPython.utils.process import system, getoutput
63 from IPython.utils.process import system, getoutput
64 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 List, Unicode, Instance, Type)
68 List, Unicode, Instance, Type)
69 from IPython.utils.warn import warn, error, fatal
69 from IPython.utils.warn import warn, error, fatal
70 import IPython.core.hooks
70 import IPython.core.hooks
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 def softspace(file, newvalue):
87 def softspace(file, newvalue):
88 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
89
89
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102
102
103 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
104
104
105 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(exceptions.Exception): pass
106
106
107 class Bunch: pass
107 class Bunch: pass
108
108
109
109
110 def get_default_colors():
110 def get_default_colors():
111 if sys.platform=='darwin':
111 if sys.platform=='darwin':
112 return "LightBG"
112 return "LightBG"
113 elif os.name=='nt':
113 elif os.name=='nt':
114 return 'Linux'
114 return 'Linux'
115 else:
115 else:
116 return 'Linux'
116 return 'Linux'
117
117
118
118
119 class SeparateStr(Str):
119 class SeparateStr(Str):
120 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
121
121
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 """
123 """
124
124
125 def validate(self, obj, value):
125 def validate(self, obj, value):
126 if value == '0': value = ''
126 if value == '0': value = ''
127 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
128 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
129
129
130 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
131 pass
131 pass
132
132
133
133
134 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
135 # Main IPython class
135 # Main IPython class
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137
137
138
138
139 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
141
141
142 _instance = None
142 _instance = None
143 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
144 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
145 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
146 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
147 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
148 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
149 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
152 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 displayhook_class = Type(DisplayHook)
154 displayhook_class = Type(DisplayHook)
155 exit_now = CBool(False)
155 exit_now = CBool(False)
156 filename = Str("<ipython console>")
156 filename = Str("<ipython console>")
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158
158
159 # Input splitter, to split entire cells of input into either individual
159 # Input splitter, to split entire cells of input into either individual
160 # interactive statements or whole blocks.
160 # interactive statements or whole blocks.
161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
161 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
162 (), {})
162 (), {})
163 logstart = CBool(False, config=True)
163 logstart = CBool(False, config=True)
164 logfile = Str('', config=True)
164 logfile = Str('', config=True)
165 logappend = Str('', config=True)
165 logappend = Str('', config=True)
166 object_info_string_level = Enum((0,1,2), default_value=0,
166 object_info_string_level = Enum((0,1,2), default_value=0,
167 config=True)
167 config=True)
168 pdb = CBool(False, config=True)
168 pdb = CBool(False, config=True)
169
169
170 pprint = CBool(True, config=True)
170 pprint = CBool(True, config=True)
171 profile = Str('', config=True)
171 profile = Str('', config=True)
172 prompt_in1 = Str('In [\\#]: ', config=True)
172 prompt_in1 = Str('In [\\#]: ', config=True)
173 prompt_in2 = Str(' .\\D.: ', config=True)
173 prompt_in2 = Str(' .\\D.: ', config=True)
174 prompt_out = Str('Out[\\#]: ', config=True)
174 prompt_out = Str('Out[\\#]: ', config=True)
175 prompts_pad_left = CBool(True, config=True)
175 prompts_pad_left = CBool(True, config=True)
176 quiet = CBool(False, config=True)
176 quiet = CBool(False, config=True)
177
177
178 # The readline stuff will eventually be moved to the terminal subclass
178 # The readline stuff will eventually be moved to the terminal subclass
179 # but for now, we can't do that as readline is welded in everywhere.
179 # but for now, we can't do that as readline is welded in everywhere.
180 readline_use = CBool(True, config=True)
180 readline_use = CBool(True, config=True)
181 readline_merge_completions = CBool(True, config=True)
181 readline_merge_completions = CBool(True, config=True)
182 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
182 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
183 readline_remove_delims = Str('-/~', config=True)
183 readline_remove_delims = Str('-/~', config=True)
184 readline_parse_and_bind = List([
184 readline_parse_and_bind = List([
185 'tab: complete',
185 'tab: complete',
186 '"\C-l": clear-screen',
186 '"\C-l": clear-screen',
187 'set show-all-if-ambiguous on',
187 'set show-all-if-ambiguous on',
188 '"\C-o": tab-insert',
188 '"\C-o": tab-insert',
189 '"\M-i": " "',
189 '"\M-i": " "',
190 '"\M-o": "\d\d\d\d"',
190 '"\M-o": "\d\d\d\d"',
191 '"\M-I": "\d\d\d\d"',
191 '"\M-I": "\d\d\d\d"',
192 '"\C-r": reverse-search-history',
192 '"\C-r": reverse-search-history',
193 '"\C-s": forward-search-history',
193 '"\C-s": forward-search-history',
194 '"\C-p": history-search-backward',
194 '"\C-p": history-search-backward',
195 '"\C-n": history-search-forward',
195 '"\C-n": history-search-forward',
196 '"\e[A": history-search-backward',
196 '"\e[A": history-search-backward',
197 '"\e[B": history-search-forward',
197 '"\e[B": history-search-forward',
198 '"\C-k": kill-line',
198 '"\C-k": kill-line',
199 '"\C-u": unix-line-discard',
199 '"\C-u": unix-line-discard',
200 ], allow_none=False, config=True)
200 ], allow_none=False, config=True)
201
201
202 # TODO: this part of prompt management should be moved to the frontends.
202 # TODO: this part of prompt management should be moved to the frontends.
203 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
203 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
204 separate_in = SeparateStr('\n', config=True)
204 separate_in = SeparateStr('\n', config=True)
205 separate_out = SeparateStr('', config=True)
205 separate_out = SeparateStr('', config=True)
206 separate_out2 = SeparateStr('', config=True)
206 separate_out2 = SeparateStr('', config=True)
207 wildcards_case_sensitive = CBool(True, config=True)
207 wildcards_case_sensitive = CBool(True, config=True)
208 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
208 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
209 default_value='Context', config=True)
209 default_value='Context', config=True)
210
210
211 # Subcomponents of InteractiveShell
211 # Subcomponents of InteractiveShell
212 alias_manager = Instance('IPython.core.alias.AliasManager')
212 alias_manager = Instance('IPython.core.alias.AliasManager')
213 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
213 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
214 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
214 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
215 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
215 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
216 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
216 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
217 plugin_manager = Instance('IPython.core.plugin.PluginManager')
217 plugin_manager = Instance('IPython.core.plugin.PluginManager')
218 payload_manager = Instance('IPython.core.payload.PayloadManager')
218 payload_manager = Instance('IPython.core.payload.PayloadManager')
219
219
220 # Private interface
220 # Private interface
221 _post_execute = set()
221 _post_execute = set()
222
222
223 def __init__(self, config=None, ipython_dir=None,
223 def __init__(self, config=None, ipython_dir=None,
224 user_ns=None, user_global_ns=None,
224 user_ns=None, user_global_ns=None,
225 custom_exceptions=((), None)):
225 custom_exceptions=((), None)):
226
226
227 # This is where traits with a config_key argument are updated
227 # This is where traits with a config_key argument are updated
228 # from the values on config.
228 # from the values on config.
229 super(InteractiveShell, self).__init__(config=config)
229 super(InteractiveShell, self).__init__(config=config)
230
230
231 # These are relatively independent and stateless
231 # These are relatively independent and stateless
232 self.init_ipython_dir(ipython_dir)
232 self.init_ipython_dir(ipython_dir)
233 self.init_instance_attrs()
233 self.init_instance_attrs()
234 self.init_environment()
234 self.init_environment()
235
235
236 # Create namespaces (user_ns, user_global_ns, etc.)
236 # Create namespaces (user_ns, user_global_ns, etc.)
237 self.init_create_namespaces(user_ns, user_global_ns)
237 self.init_create_namespaces(user_ns, user_global_ns)
238 # This has to be done after init_create_namespaces because it uses
238 # This has to be done after init_create_namespaces because it uses
239 # something in self.user_ns, but before init_sys_modules, which
239 # something in self.user_ns, but before init_sys_modules, which
240 # is the first thing to modify sys.
240 # is the first thing to modify sys.
241 # TODO: When we override sys.stdout and sys.stderr before this class
241 # TODO: When we override sys.stdout and sys.stderr before this class
242 # is created, we are saving the overridden ones here. Not sure if this
242 # is created, we are saving the overridden ones here. Not sure if this
243 # is what we want to do.
243 # is what we want to do.
244 self.save_sys_module_state()
244 self.save_sys_module_state()
245 self.init_sys_modules()
245 self.init_sys_modules()
246
246
247 self.init_history()
247 self.init_history()
248 self.init_encoding()
248 self.init_encoding()
249 self.init_prefilter()
249 self.init_prefilter()
250
250
251 Magic.__init__(self, self)
251 Magic.__init__(self, self)
252
252
253 self.init_syntax_highlighting()
253 self.init_syntax_highlighting()
254 self.init_hooks()
254 self.init_hooks()
255 self.init_pushd_popd_magic()
255 self.init_pushd_popd_magic()
256 # self.init_traceback_handlers use to be here, but we moved it below
256 # self.init_traceback_handlers use to be here, but we moved it below
257 # because it and init_io have to come after init_readline.
257 # because it and init_io have to come after init_readline.
258 self.init_user_ns()
258 self.init_user_ns()
259 self.init_logger()
259 self.init_logger()
260 self.init_alias()
260 self.init_alias()
261 self.init_builtins()
261 self.init_builtins()
262
262
263 # pre_config_initialization
263 # pre_config_initialization
264 self.init_shadow_hist()
264 self.init_shadow_hist()
265
265
266 # The next section should contain everything that was in ipmaker.
266 # The next section should contain everything that was in ipmaker.
267 self.init_logstart()
267 self.init_logstart()
268
268
269 # The following was in post_config_initialization
269 # The following was in post_config_initialization
270 self.init_inspector()
270 self.init_inspector()
271 # init_readline() must come before init_io(), because init_io uses
271 # init_readline() must come before init_io(), because init_io uses
272 # readline related things.
272 # readline related things.
273 self.init_readline()
273 self.init_readline()
274 # init_completer must come after init_readline, because it needs to
274 # init_completer must come after init_readline, because it needs to
275 # know whether readline is present or not system-wide to configure the
275 # know whether readline is present or not system-wide to configure the
276 # completers, since the completion machinery can now operate
276 # completers, since the completion machinery can now operate
277 # independently of readline (e.g. over the network)
277 # independently of readline (e.g. over the network)
278 self.init_completer()
278 self.init_completer()
279 # TODO: init_io() needs to happen before init_traceback handlers
279 # TODO: init_io() needs to happen before init_traceback handlers
280 # because the traceback handlers hardcode the stdout/stderr streams.
280 # because the traceback handlers hardcode the stdout/stderr streams.
281 # This logic in in debugger.Pdb and should eventually be changed.
281 # This logic in in debugger.Pdb and should eventually be changed.
282 self.init_io()
282 self.init_io()
283 self.init_traceback_handlers(custom_exceptions)
283 self.init_traceback_handlers(custom_exceptions)
284 self.init_prompts()
284 self.init_prompts()
285 self.init_displayhook()
285 self.init_displayhook()
286 self.init_reload_doctest()
286 self.init_reload_doctest()
287 self.init_magics()
287 self.init_magics()
288 self.init_pdb()
288 self.init_pdb()
289 self.init_extension_manager()
289 self.init_extension_manager()
290 self.init_plugin_manager()
290 self.init_plugin_manager()
291 self.init_payload()
291 self.init_payload()
292 self.hooks.late_startup_hook()
292 self.hooks.late_startup_hook()
293 atexit.register(self.atexit_operations)
293 atexit.register(self.atexit_operations)
294
294
295 @classmethod
295 @classmethod
296 def instance(cls, *args, **kwargs):
296 def instance(cls, *args, **kwargs):
297 """Returns a global InteractiveShell instance."""
297 """Returns a global InteractiveShell instance."""
298 if cls._instance is None:
298 if cls._instance is None:
299 inst = cls(*args, **kwargs)
299 inst = cls(*args, **kwargs)
300 # Now make sure that the instance will also be returned by
300 # Now make sure that the instance will also be returned by
301 # the subclasses instance attribute.
301 # the subclasses instance attribute.
302 for subclass in cls.mro():
302 for subclass in cls.mro():
303 if issubclass(cls, subclass) and \
303 if issubclass(cls, subclass) and \
304 issubclass(subclass, InteractiveShell):
304 issubclass(subclass, InteractiveShell):
305 subclass._instance = inst
305 subclass._instance = inst
306 else:
306 else:
307 break
307 break
308 if isinstance(cls._instance, cls):
308 if isinstance(cls._instance, cls):
309 return cls._instance
309 return cls._instance
310 else:
310 else:
311 raise MultipleInstanceError(
311 raise MultipleInstanceError(
312 'Multiple incompatible subclass instances of '
312 'Multiple incompatible subclass instances of '
313 'InteractiveShell are being created.'
313 'InteractiveShell are being created.'
314 )
314 )
315
315
316 @classmethod
316 @classmethod
317 def initialized(cls):
317 def initialized(cls):
318 return hasattr(cls, "_instance")
318 return hasattr(cls, "_instance")
319
319
320 def get_ipython(self):
320 def get_ipython(self):
321 """Return the currently running IPython instance."""
321 """Return the currently running IPython instance."""
322 return self
322 return self
323
323
324 #-------------------------------------------------------------------------
324 #-------------------------------------------------------------------------
325 # Trait changed handlers
325 # Trait changed handlers
326 #-------------------------------------------------------------------------
326 #-------------------------------------------------------------------------
327
327
328 def _ipython_dir_changed(self, name, new):
328 def _ipython_dir_changed(self, name, new):
329 if not os.path.isdir(new):
329 if not os.path.isdir(new):
330 os.makedirs(new, mode = 0777)
330 os.makedirs(new, mode = 0777)
331
331
332 def set_autoindent(self,value=None):
332 def set_autoindent(self,value=None):
333 """Set the autoindent flag, checking for readline support.
333 """Set the autoindent flag, checking for readline support.
334
334
335 If called with no arguments, it acts as a toggle."""
335 If called with no arguments, it acts as a toggle."""
336
336
337 if not self.has_readline:
337 if not self.has_readline:
338 if os.name == 'posix':
338 if os.name == 'posix':
339 warn("The auto-indent feature requires the readline library")
339 warn("The auto-indent feature requires the readline library")
340 self.autoindent = 0
340 self.autoindent = 0
341 return
341 return
342 if value is None:
342 if value is None:
343 self.autoindent = not self.autoindent
343 self.autoindent = not self.autoindent
344 else:
344 else:
345 self.autoindent = value
345 self.autoindent = value
346
346
347 #-------------------------------------------------------------------------
347 #-------------------------------------------------------------------------
348 # init_* methods called by __init__
348 # init_* methods called by __init__
349 #-------------------------------------------------------------------------
349 #-------------------------------------------------------------------------
350
350
351 def init_ipython_dir(self, ipython_dir):
351 def init_ipython_dir(self, ipython_dir):
352 if ipython_dir is not None:
352 if ipython_dir is not None:
353 self.ipython_dir = ipython_dir
353 self.ipython_dir = ipython_dir
354 self.config.Global.ipython_dir = self.ipython_dir
354 self.config.Global.ipython_dir = self.ipython_dir
355 return
355 return
356
356
357 if hasattr(self.config.Global, 'ipython_dir'):
357 if hasattr(self.config.Global, 'ipython_dir'):
358 self.ipython_dir = self.config.Global.ipython_dir
358 self.ipython_dir = self.config.Global.ipython_dir
359 else:
359 else:
360 self.ipython_dir = get_ipython_dir()
360 self.ipython_dir = get_ipython_dir()
361
361
362 # All children can just read this
362 # All children can just read this
363 self.config.Global.ipython_dir = self.ipython_dir
363 self.config.Global.ipython_dir = self.ipython_dir
364
364
365 def init_instance_attrs(self):
365 def init_instance_attrs(self):
366 self.more = False
366 self.more = False
367
367
368 # command compiler
368 # command compiler
369 self.compile = codeop.CommandCompiler()
369 self.compile = codeop.CommandCompiler()
370
370
371 # User input buffer
371 # User input buffer
372 self.buffer = []
372 self.buffer = []
373
373
374 # Make an empty namespace, which extension writers can rely on both
374 # Make an empty namespace, which extension writers can rely on both
375 # existing and NEVER being used by ipython itself. This gives them a
375 # existing and NEVER being used by ipython itself. This gives them a
376 # convenient location for storing additional information and state
376 # convenient location for storing additional information and state
377 # their extensions may require, without fear of collisions with other
377 # their extensions may require, without fear of collisions with other
378 # ipython names that may develop later.
378 # ipython names that may develop later.
379 self.meta = Struct()
379 self.meta = Struct()
380
380
381 # Object variable to store code object waiting execution. This is
381 # Object variable to store code object waiting execution. This is
382 # used mainly by the multithreaded shells, but it can come in handy in
382 # used mainly by the multithreaded shells, but it can come in handy in
383 # other situations. No need to use a Queue here, since it's a single
383 # other situations. No need to use a Queue here, since it's a single
384 # item which gets cleared once run.
384 # item which gets cleared once run.
385 self.code_to_run = None
385 self.code_to_run = None
386
386
387 # Temporary files used for various purposes. Deleted at exit.
387 # Temporary files used for various purposes. Deleted at exit.
388 self.tempfiles = []
388 self.tempfiles = []
389
389
390 # Keep track of readline usage (later set by init_readline)
390 # Keep track of readline usage (later set by init_readline)
391 self.has_readline = False
391 self.has_readline = False
392
392
393 # keep track of where we started running (mainly for crash post-mortem)
393 # keep track of where we started running (mainly for crash post-mortem)
394 # This is not being used anywhere currently.
394 # This is not being used anywhere currently.
395 self.starting_dir = os.getcwd()
395 self.starting_dir = os.getcwd()
396
396
397 # Indentation management
397 # Indentation management
398 self.indent_current_nsp = 0
398 self.indent_current_nsp = 0
399
399
400 # Increasing execution counter
401 self.execution_count = 0
402
400 def init_environment(self):
403 def init_environment(self):
401 """Any changes we need to make to the user's environment."""
404 """Any changes we need to make to the user's environment."""
402 pass
405 pass
403
406
404 def init_encoding(self):
407 def init_encoding(self):
405 # Get system encoding at startup time. Certain terminals (like Emacs
408 # Get system encoding at startup time. Certain terminals (like Emacs
406 # under Win32 have it set to None, and we need to have a known valid
409 # under Win32 have it set to None, and we need to have a known valid
407 # encoding to use in the raw_input() method
410 # encoding to use in the raw_input() method
408 try:
411 try:
409 self.stdin_encoding = sys.stdin.encoding or 'ascii'
412 self.stdin_encoding = sys.stdin.encoding or 'ascii'
410 except AttributeError:
413 except AttributeError:
411 self.stdin_encoding = 'ascii'
414 self.stdin_encoding = 'ascii'
412
415
413 def init_syntax_highlighting(self):
416 def init_syntax_highlighting(self):
414 # Python source parser/formatter for syntax highlighting
417 # Python source parser/formatter for syntax highlighting
415 pyformat = PyColorize.Parser().format
418 pyformat = PyColorize.Parser().format
416 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
419 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
417
420
418 def init_pushd_popd_magic(self):
421 def init_pushd_popd_magic(self):
419 # for pushd/popd management
422 # for pushd/popd management
420 try:
423 try:
421 self.home_dir = get_home_dir()
424 self.home_dir = get_home_dir()
422 except HomeDirError, msg:
425 except HomeDirError, msg:
423 fatal(msg)
426 fatal(msg)
424
427
425 self.dir_stack = []
428 self.dir_stack = []
426
429
427 def init_logger(self):
430 def init_logger(self):
428 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
431 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
429 # local shortcut, this is used a LOT
432 # local shortcut, this is used a LOT
430 self.log = self.logger.log
433 self.log = self.logger.log
431
434
432 def init_logstart(self):
435 def init_logstart(self):
433 if self.logappend:
436 if self.logappend:
434 self.magic_logstart(self.logappend + ' append')
437 self.magic_logstart(self.logappend + ' append')
435 elif self.logfile:
438 elif self.logfile:
436 self.magic_logstart(self.logfile)
439 self.magic_logstart(self.logfile)
437 elif self.logstart:
440 elif self.logstart:
438 self.magic_logstart()
441 self.magic_logstart()
439
442
440 def init_builtins(self):
443 def init_builtins(self):
441 self.builtin_trap = BuiltinTrap(shell=self)
444 self.builtin_trap = BuiltinTrap(shell=self)
442
445
443 def init_inspector(self):
446 def init_inspector(self):
444 # Object inspector
447 # Object inspector
445 self.inspector = oinspect.Inspector(oinspect.InspectColors,
448 self.inspector = oinspect.Inspector(oinspect.InspectColors,
446 PyColorize.ANSICodeColors,
449 PyColorize.ANSICodeColors,
447 'NoColor',
450 'NoColor',
448 self.object_info_string_level)
451 self.object_info_string_level)
449
452
450 def init_io(self):
453 def init_io(self):
451 # This will just use sys.stdout and sys.stderr. If you want to
454 # This will just use sys.stdout and sys.stderr. If you want to
452 # override sys.stdout and sys.stderr themselves, you need to do that
455 # override sys.stdout and sys.stderr themselves, you need to do that
453 # *before* instantiating this class, because Term holds onto
456 # *before* instantiating this class, because Term holds onto
454 # references to the underlying streams.
457 # references to the underlying streams.
455 if sys.platform == 'win32' and self.has_readline:
458 if sys.platform == 'win32' and self.has_readline:
456 Term = io.IOTerm(cout=self.readline._outputfile,
459 Term = io.IOTerm(cout=self.readline._outputfile,
457 cerr=self.readline._outputfile)
460 cerr=self.readline._outputfile)
458 else:
461 else:
459 Term = io.IOTerm()
462 Term = io.IOTerm()
460 io.Term = Term
463 io.Term = Term
461
464
462 def init_prompts(self):
465 def init_prompts(self):
463 # TODO: This is a pass for now because the prompts are managed inside
466 # TODO: This is a pass for now because the prompts are managed inside
464 # the DisplayHook. Once there is a separate prompt manager, this
467 # the DisplayHook. Once there is a separate prompt manager, this
465 # will initialize that object and all prompt related information.
468 # will initialize that object and all prompt related information.
466 pass
469 pass
467
470
468 def init_displayhook(self):
471 def init_displayhook(self):
469 # Initialize displayhook, set in/out prompts and printing system
472 # Initialize displayhook, set in/out prompts and printing system
470 self.displayhook = self.displayhook_class(
473 self.displayhook = self.displayhook_class(
471 shell=self,
474 shell=self,
472 cache_size=self.cache_size,
475 cache_size=self.cache_size,
473 input_sep = self.separate_in,
476 input_sep = self.separate_in,
474 output_sep = self.separate_out,
477 output_sep = self.separate_out,
475 output_sep2 = self.separate_out2,
478 output_sep2 = self.separate_out2,
476 ps1 = self.prompt_in1,
479 ps1 = self.prompt_in1,
477 ps2 = self.prompt_in2,
480 ps2 = self.prompt_in2,
478 ps_out = self.prompt_out,
481 ps_out = self.prompt_out,
479 pad_left = self.prompts_pad_left
482 pad_left = self.prompts_pad_left
480 )
483 )
481 # This is a context manager that installs/revmoes the displayhook at
484 # This is a context manager that installs/revmoes the displayhook at
482 # the appropriate time.
485 # the appropriate time.
483 self.display_trap = DisplayTrap(hook=self.displayhook)
486 self.display_trap = DisplayTrap(hook=self.displayhook)
484
487
485 def init_reload_doctest(self):
488 def init_reload_doctest(self):
486 # Do a proper resetting of doctest, including the necessary displayhook
489 # Do a proper resetting of doctest, including the necessary displayhook
487 # monkeypatching
490 # monkeypatching
488 try:
491 try:
489 doctest_reload()
492 doctest_reload()
490 except ImportError:
493 except ImportError:
491 warn("doctest module does not exist.")
494 warn("doctest module does not exist.")
492
495
493 #-------------------------------------------------------------------------
496 #-------------------------------------------------------------------------
494 # Things related to injections into the sys module
497 # Things related to injections into the sys module
495 #-------------------------------------------------------------------------
498 #-------------------------------------------------------------------------
496
499
497 def save_sys_module_state(self):
500 def save_sys_module_state(self):
498 """Save the state of hooks in the sys module.
501 """Save the state of hooks in the sys module.
499
502
500 This has to be called after self.user_ns is created.
503 This has to be called after self.user_ns is created.
501 """
504 """
502 self._orig_sys_module_state = {}
505 self._orig_sys_module_state = {}
503 self._orig_sys_module_state['stdin'] = sys.stdin
506 self._orig_sys_module_state['stdin'] = sys.stdin
504 self._orig_sys_module_state['stdout'] = sys.stdout
507 self._orig_sys_module_state['stdout'] = sys.stdout
505 self._orig_sys_module_state['stderr'] = sys.stderr
508 self._orig_sys_module_state['stderr'] = sys.stderr
506 self._orig_sys_module_state['excepthook'] = sys.excepthook
509 self._orig_sys_module_state['excepthook'] = sys.excepthook
507 try:
510 try:
508 self._orig_sys_modules_main_name = self.user_ns['__name__']
511 self._orig_sys_modules_main_name = self.user_ns['__name__']
509 except KeyError:
512 except KeyError:
510 pass
513 pass
511
514
512 def restore_sys_module_state(self):
515 def restore_sys_module_state(self):
513 """Restore the state of the sys module."""
516 """Restore the state of the sys module."""
514 try:
517 try:
515 for k, v in self._orig_sys_module_state.items():
518 for k, v in self._orig_sys_module_state.items():
516 setattr(sys, k, v)
519 setattr(sys, k, v)
517 except AttributeError:
520 except AttributeError:
518 pass
521 pass
519 # Reset what what done in self.init_sys_modules
522 # Reset what what done in self.init_sys_modules
520 try:
523 try:
521 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
524 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
522 except (AttributeError, KeyError):
525 except (AttributeError, KeyError):
523 pass
526 pass
524
527
525 #-------------------------------------------------------------------------
528 #-------------------------------------------------------------------------
526 # Things related to hooks
529 # Things related to hooks
527 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
528
531
529 def init_hooks(self):
532 def init_hooks(self):
530 # hooks holds pointers used for user-side customizations
533 # hooks holds pointers used for user-side customizations
531 self.hooks = Struct()
534 self.hooks = Struct()
532
535
533 self.strdispatchers = {}
536 self.strdispatchers = {}
534
537
535 # Set all default hooks, defined in the IPython.hooks module.
538 # Set all default hooks, defined in the IPython.hooks module.
536 hooks = IPython.core.hooks
539 hooks = IPython.core.hooks
537 for hook_name in hooks.__all__:
540 for hook_name in hooks.__all__:
538 # default hooks have priority 100, i.e. low; user hooks should have
541 # default hooks have priority 100, i.e. low; user hooks should have
539 # 0-100 priority
542 # 0-100 priority
540 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
543 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
541
544
542 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
545 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
543 """set_hook(name,hook) -> sets an internal IPython hook.
546 """set_hook(name,hook) -> sets an internal IPython hook.
544
547
545 IPython exposes some of its internal API as user-modifiable hooks. By
548 IPython exposes some of its internal API as user-modifiable hooks. By
546 adding your function to one of these hooks, you can modify IPython's
549 adding your function to one of these hooks, you can modify IPython's
547 behavior to call at runtime your own routines."""
550 behavior to call at runtime your own routines."""
548
551
549 # At some point in the future, this should validate the hook before it
552 # At some point in the future, this should validate the hook before it
550 # accepts it. Probably at least check that the hook takes the number
553 # accepts it. Probably at least check that the hook takes the number
551 # of args it's supposed to.
554 # of args it's supposed to.
552
555
553 f = new.instancemethod(hook,self,self.__class__)
556 f = new.instancemethod(hook,self,self.__class__)
554
557
555 # check if the hook is for strdispatcher first
558 # check if the hook is for strdispatcher first
556 if str_key is not None:
559 if str_key is not None:
557 sdp = self.strdispatchers.get(name, StrDispatch())
560 sdp = self.strdispatchers.get(name, StrDispatch())
558 sdp.add_s(str_key, f, priority )
561 sdp.add_s(str_key, f, priority )
559 self.strdispatchers[name] = sdp
562 self.strdispatchers[name] = sdp
560 return
563 return
561 if re_key is not None:
564 if re_key is not None:
562 sdp = self.strdispatchers.get(name, StrDispatch())
565 sdp = self.strdispatchers.get(name, StrDispatch())
563 sdp.add_re(re.compile(re_key), f, priority )
566 sdp.add_re(re.compile(re_key), f, priority )
564 self.strdispatchers[name] = sdp
567 self.strdispatchers[name] = sdp
565 return
568 return
566
569
567 dp = getattr(self.hooks, name, None)
570 dp = getattr(self.hooks, name, None)
568 if name not in IPython.core.hooks.__all__:
571 if name not in IPython.core.hooks.__all__:
569 print "Warning! Hook '%s' is not one of %s" % \
572 print "Warning! Hook '%s' is not one of %s" % \
570 (name, IPython.core.hooks.__all__ )
573 (name, IPython.core.hooks.__all__ )
571 if not dp:
574 if not dp:
572 dp = IPython.core.hooks.CommandChainDispatcher()
575 dp = IPython.core.hooks.CommandChainDispatcher()
573
576
574 try:
577 try:
575 dp.add(f,priority)
578 dp.add(f,priority)
576 except AttributeError:
579 except AttributeError:
577 # it was not commandchain, plain old func - replace
580 # it was not commandchain, plain old func - replace
578 dp = f
581 dp = f
579
582
580 setattr(self.hooks,name, dp)
583 setattr(self.hooks,name, dp)
581
584
582 def register_post_execute(self, func):
585 def register_post_execute(self, func):
583 """Register a function for calling after code execution.
586 """Register a function for calling after code execution.
584 """
587 """
585 if not callable(func):
588 if not callable(func):
586 raise ValueError('argument %s must be callable' % func)
589 raise ValueError('argument %s must be callable' % func)
587 self._post_execute.add(func)
590 self._post_execute.add(func)
588
591
589 #-------------------------------------------------------------------------
592 #-------------------------------------------------------------------------
590 # Things related to the "main" module
593 # Things related to the "main" module
591 #-------------------------------------------------------------------------
594 #-------------------------------------------------------------------------
592
595
593 def new_main_mod(self,ns=None):
596 def new_main_mod(self,ns=None):
594 """Return a new 'main' module object for user code execution.
597 """Return a new 'main' module object for user code execution.
595 """
598 """
596 main_mod = self._user_main_module
599 main_mod = self._user_main_module
597 init_fakemod_dict(main_mod,ns)
600 init_fakemod_dict(main_mod,ns)
598 return main_mod
601 return main_mod
599
602
600 def cache_main_mod(self,ns,fname):
603 def cache_main_mod(self,ns,fname):
601 """Cache a main module's namespace.
604 """Cache a main module's namespace.
602
605
603 When scripts are executed via %run, we must keep a reference to the
606 When scripts are executed via %run, we must keep a reference to the
604 namespace of their __main__ module (a FakeModule instance) around so
607 namespace of their __main__ module (a FakeModule instance) around so
605 that Python doesn't clear it, rendering objects defined therein
608 that Python doesn't clear it, rendering objects defined therein
606 useless.
609 useless.
607
610
608 This method keeps said reference in a private dict, keyed by the
611 This method keeps said reference in a private dict, keyed by the
609 absolute path of the module object (which corresponds to the script
612 absolute path of the module object (which corresponds to the script
610 path). This way, for multiple executions of the same script we only
613 path). This way, for multiple executions of the same script we only
611 keep one copy of the namespace (the last one), thus preventing memory
614 keep one copy of the namespace (the last one), thus preventing memory
612 leaks from old references while allowing the objects from the last
615 leaks from old references while allowing the objects from the last
613 execution to be accessible.
616 execution to be accessible.
614
617
615 Note: we can not allow the actual FakeModule instances to be deleted,
618 Note: we can not allow the actual FakeModule instances to be deleted,
616 because of how Python tears down modules (it hard-sets all their
619 because of how Python tears down modules (it hard-sets all their
617 references to None without regard for reference counts). This method
620 references to None without regard for reference counts). This method
618 must therefore make a *copy* of the given namespace, to allow the
621 must therefore make a *copy* of the given namespace, to allow the
619 original module's __dict__ to be cleared and reused.
622 original module's __dict__ to be cleared and reused.
620
623
621
624
622 Parameters
625 Parameters
623 ----------
626 ----------
624 ns : a namespace (a dict, typically)
627 ns : a namespace (a dict, typically)
625
628
626 fname : str
629 fname : str
627 Filename associated with the namespace.
630 Filename associated with the namespace.
628
631
629 Examples
632 Examples
630 --------
633 --------
631
634
632 In [10]: import IPython
635 In [10]: import IPython
633
636
634 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
637 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
635
638
636 In [12]: IPython.__file__ in _ip._main_ns_cache
639 In [12]: IPython.__file__ in _ip._main_ns_cache
637 Out[12]: True
640 Out[12]: True
638 """
641 """
639 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
642 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
640
643
641 def clear_main_mod_cache(self):
644 def clear_main_mod_cache(self):
642 """Clear the cache of main modules.
645 """Clear the cache of main modules.
643
646
644 Mainly for use by utilities like %reset.
647 Mainly for use by utilities like %reset.
645
648
646 Examples
649 Examples
647 --------
650 --------
648
651
649 In [15]: import IPython
652 In [15]: import IPython
650
653
651 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
654 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
652
655
653 In [17]: len(_ip._main_ns_cache) > 0
656 In [17]: len(_ip._main_ns_cache) > 0
654 Out[17]: True
657 Out[17]: True
655
658
656 In [18]: _ip.clear_main_mod_cache()
659 In [18]: _ip.clear_main_mod_cache()
657
660
658 In [19]: len(_ip._main_ns_cache) == 0
661 In [19]: len(_ip._main_ns_cache) == 0
659 Out[19]: True
662 Out[19]: True
660 """
663 """
661 self._main_ns_cache.clear()
664 self._main_ns_cache.clear()
662
665
663 #-------------------------------------------------------------------------
666 #-------------------------------------------------------------------------
664 # Things related to debugging
667 # Things related to debugging
665 #-------------------------------------------------------------------------
668 #-------------------------------------------------------------------------
666
669
667 def init_pdb(self):
670 def init_pdb(self):
668 # Set calling of pdb on exceptions
671 # Set calling of pdb on exceptions
669 # self.call_pdb is a property
672 # self.call_pdb is a property
670 self.call_pdb = self.pdb
673 self.call_pdb = self.pdb
671
674
672 def _get_call_pdb(self):
675 def _get_call_pdb(self):
673 return self._call_pdb
676 return self._call_pdb
674
677
675 def _set_call_pdb(self,val):
678 def _set_call_pdb(self,val):
676
679
677 if val not in (0,1,False,True):
680 if val not in (0,1,False,True):
678 raise ValueError,'new call_pdb value must be boolean'
681 raise ValueError,'new call_pdb value must be boolean'
679
682
680 # store value in instance
683 # store value in instance
681 self._call_pdb = val
684 self._call_pdb = val
682
685
683 # notify the actual exception handlers
686 # notify the actual exception handlers
684 self.InteractiveTB.call_pdb = val
687 self.InteractiveTB.call_pdb = val
685
688
686 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
689 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
687 'Control auto-activation of pdb at exceptions')
690 'Control auto-activation of pdb at exceptions')
688
691
689 def debugger(self,force=False):
692 def debugger(self,force=False):
690 """Call the pydb/pdb debugger.
693 """Call the pydb/pdb debugger.
691
694
692 Keywords:
695 Keywords:
693
696
694 - force(False): by default, this routine checks the instance call_pdb
697 - force(False): by default, this routine checks the instance call_pdb
695 flag and does not actually invoke the debugger if the flag is false.
698 flag and does not actually invoke the debugger if the flag is false.
696 The 'force' option forces the debugger to activate even if the flag
699 The 'force' option forces the debugger to activate even if the flag
697 is false.
700 is false.
698 """
701 """
699
702
700 if not (force or self.call_pdb):
703 if not (force or self.call_pdb):
701 return
704 return
702
705
703 if not hasattr(sys,'last_traceback'):
706 if not hasattr(sys,'last_traceback'):
704 error('No traceback has been produced, nothing to debug.')
707 error('No traceback has been produced, nothing to debug.')
705 return
708 return
706
709
707 # use pydb if available
710 # use pydb if available
708 if debugger.has_pydb:
711 if debugger.has_pydb:
709 from pydb import pm
712 from pydb import pm
710 else:
713 else:
711 # fallback to our internal debugger
714 # fallback to our internal debugger
712 pm = lambda : self.InteractiveTB.debugger(force=True)
715 pm = lambda : self.InteractiveTB.debugger(force=True)
713 self.history_saving_wrapper(pm)()
716 self.history_saving_wrapper(pm)()
714
717
715 #-------------------------------------------------------------------------
718 #-------------------------------------------------------------------------
716 # Things related to IPython's various namespaces
719 # Things related to IPython's various namespaces
717 #-------------------------------------------------------------------------
720 #-------------------------------------------------------------------------
718
721
719 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
722 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
720 # Create the namespace where the user will operate. user_ns is
723 # Create the namespace where the user will operate. user_ns is
721 # normally the only one used, and it is passed to the exec calls as
724 # normally the only one used, and it is passed to the exec calls as
722 # the locals argument. But we do carry a user_global_ns namespace
725 # the locals argument. But we do carry a user_global_ns namespace
723 # given as the exec 'globals' argument, This is useful in embedding
726 # given as the exec 'globals' argument, This is useful in embedding
724 # situations where the ipython shell opens in a context where the
727 # situations where the ipython shell opens in a context where the
725 # distinction between locals and globals is meaningful. For
728 # distinction between locals and globals is meaningful. For
726 # non-embedded contexts, it is just the same object as the user_ns dict.
729 # non-embedded contexts, it is just the same object as the user_ns dict.
727
730
728 # FIXME. For some strange reason, __builtins__ is showing up at user
731 # FIXME. For some strange reason, __builtins__ is showing up at user
729 # level as a dict instead of a module. This is a manual fix, but I
732 # level as a dict instead of a module. This is a manual fix, but I
730 # should really track down where the problem is coming from. Alex
733 # should really track down where the problem is coming from. Alex
731 # Schmolck reported this problem first.
734 # Schmolck reported this problem first.
732
735
733 # A useful post by Alex Martelli on this topic:
736 # A useful post by Alex Martelli on this topic:
734 # Re: inconsistent value from __builtins__
737 # Re: inconsistent value from __builtins__
735 # Von: Alex Martelli <aleaxit@yahoo.com>
738 # Von: Alex Martelli <aleaxit@yahoo.com>
736 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
739 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
737 # Gruppen: comp.lang.python
740 # Gruppen: comp.lang.python
738
741
739 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
742 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
740 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
743 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
741 # > <type 'dict'>
744 # > <type 'dict'>
742 # > >>> print type(__builtins__)
745 # > >>> print type(__builtins__)
743 # > <type 'module'>
746 # > <type 'module'>
744 # > Is this difference in return value intentional?
747 # > Is this difference in return value intentional?
745
748
746 # Well, it's documented that '__builtins__' can be either a dictionary
749 # Well, it's documented that '__builtins__' can be either a dictionary
747 # or a module, and it's been that way for a long time. Whether it's
750 # or a module, and it's been that way for a long time. Whether it's
748 # intentional (or sensible), I don't know. In any case, the idea is
751 # intentional (or sensible), I don't know. In any case, the idea is
749 # that if you need to access the built-in namespace directly, you
752 # that if you need to access the built-in namespace directly, you
750 # should start with "import __builtin__" (note, no 's') which will
753 # should start with "import __builtin__" (note, no 's') which will
751 # definitely give you a module. Yeah, it's somewhat confusing:-(.
754 # definitely give you a module. Yeah, it's somewhat confusing:-(.
752
755
753 # These routines return properly built dicts as needed by the rest of
756 # These routines return properly built dicts as needed by the rest of
754 # the code, and can also be used by extension writers to generate
757 # the code, and can also be used by extension writers to generate
755 # properly initialized namespaces.
758 # properly initialized namespaces.
756 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
759 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
757 user_global_ns)
760 user_global_ns)
758
761
759 # Assign namespaces
762 # Assign namespaces
760 # This is the namespace where all normal user variables live
763 # This is the namespace where all normal user variables live
761 self.user_ns = user_ns
764 self.user_ns = user_ns
762 self.user_global_ns = user_global_ns
765 self.user_global_ns = user_global_ns
763
766
764 # An auxiliary namespace that checks what parts of the user_ns were
767 # An auxiliary namespace that checks what parts of the user_ns were
765 # loaded at startup, so we can list later only variables defined in
768 # loaded at startup, so we can list later only variables defined in
766 # actual interactive use. Since it is always a subset of user_ns, it
769 # actual interactive use. Since it is always a subset of user_ns, it
767 # doesn't need to be separately tracked in the ns_table.
770 # doesn't need to be separately tracked in the ns_table.
768 self.user_ns_hidden = {}
771 self.user_ns_hidden = {}
769
772
770 # A namespace to keep track of internal data structures to prevent
773 # A namespace to keep track of internal data structures to prevent
771 # them from cluttering user-visible stuff. Will be updated later
774 # them from cluttering user-visible stuff. Will be updated later
772 self.internal_ns = {}
775 self.internal_ns = {}
773
776
774 # Now that FakeModule produces a real module, we've run into a nasty
777 # Now that FakeModule produces a real module, we've run into a nasty
775 # problem: after script execution (via %run), the module where the user
778 # problem: after script execution (via %run), the module where the user
776 # code ran is deleted. Now that this object is a true module (needed
779 # code ran is deleted. Now that this object is a true module (needed
777 # so docetst and other tools work correctly), the Python module
780 # so docetst and other tools work correctly), the Python module
778 # teardown mechanism runs over it, and sets to None every variable
781 # teardown mechanism runs over it, and sets to None every variable
779 # present in that module. Top-level references to objects from the
782 # present in that module. Top-level references to objects from the
780 # script survive, because the user_ns is updated with them. However,
783 # script survive, because the user_ns is updated with them. However,
781 # calling functions defined in the script that use other things from
784 # calling functions defined in the script that use other things from
782 # the script will fail, because the function's closure had references
785 # the script will fail, because the function's closure had references
783 # to the original objects, which are now all None. So we must protect
786 # to the original objects, which are now all None. So we must protect
784 # these modules from deletion by keeping a cache.
787 # these modules from deletion by keeping a cache.
785 #
788 #
786 # To avoid keeping stale modules around (we only need the one from the
789 # To avoid keeping stale modules around (we only need the one from the
787 # last run), we use a dict keyed with the full path to the script, so
790 # last run), we use a dict keyed with the full path to the script, so
788 # only the last version of the module is held in the cache. Note,
791 # only the last version of the module is held in the cache. Note,
789 # however, that we must cache the module *namespace contents* (their
792 # however, that we must cache the module *namespace contents* (their
790 # __dict__). Because if we try to cache the actual modules, old ones
793 # __dict__). Because if we try to cache the actual modules, old ones
791 # (uncached) could be destroyed while still holding references (such as
794 # (uncached) could be destroyed while still holding references (such as
792 # those held by GUI objects that tend to be long-lived)>
795 # those held by GUI objects that tend to be long-lived)>
793 #
796 #
794 # The %reset command will flush this cache. See the cache_main_mod()
797 # The %reset command will flush this cache. See the cache_main_mod()
795 # and clear_main_mod_cache() methods for details on use.
798 # and clear_main_mod_cache() methods for details on use.
796
799
797 # This is the cache used for 'main' namespaces
800 # This is the cache used for 'main' namespaces
798 self._main_ns_cache = {}
801 self._main_ns_cache = {}
799 # And this is the single instance of FakeModule whose __dict__ we keep
802 # And this is the single instance of FakeModule whose __dict__ we keep
800 # copying and clearing for reuse on each %run
803 # copying and clearing for reuse on each %run
801 self._user_main_module = FakeModule()
804 self._user_main_module = FakeModule()
802
805
803 # A table holding all the namespaces IPython deals with, so that
806 # A table holding all the namespaces IPython deals with, so that
804 # introspection facilities can search easily.
807 # introspection facilities can search easily.
805 self.ns_table = {'user':user_ns,
808 self.ns_table = {'user':user_ns,
806 'user_global':user_global_ns,
809 'user_global':user_global_ns,
807 'internal':self.internal_ns,
810 'internal':self.internal_ns,
808 'builtin':__builtin__.__dict__
811 'builtin':__builtin__.__dict__
809 }
812 }
810
813
811 # Similarly, track all namespaces where references can be held and that
814 # Similarly, track all namespaces where references can be held and that
812 # we can safely clear (so it can NOT include builtin). This one can be
815 # we can safely clear (so it can NOT include builtin). This one can be
813 # a simple list.
816 # a simple list.
814 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
817 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
815 self.internal_ns, self._main_ns_cache ]
818 self.internal_ns, self._main_ns_cache ]
816
819
817 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
820 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
818 """Return a valid local and global user interactive namespaces.
821 """Return a valid local and global user interactive namespaces.
819
822
820 This builds a dict with the minimal information needed to operate as a
823 This builds a dict with the minimal information needed to operate as a
821 valid IPython user namespace, which you can pass to the various
824 valid IPython user namespace, which you can pass to the various
822 embedding classes in ipython. The default implementation returns the
825 embedding classes in ipython. The default implementation returns the
823 same dict for both the locals and the globals to allow functions to
826 same dict for both the locals and the globals to allow functions to
824 refer to variables in the namespace. Customized implementations can
827 refer to variables in the namespace. Customized implementations can
825 return different dicts. The locals dictionary can actually be anything
828 return different dicts. The locals dictionary can actually be anything
826 following the basic mapping protocol of a dict, but the globals dict
829 following the basic mapping protocol of a dict, but the globals dict
827 must be a true dict, not even a subclass. It is recommended that any
830 must be a true dict, not even a subclass. It is recommended that any
828 custom object for the locals namespace synchronize with the globals
831 custom object for the locals namespace synchronize with the globals
829 dict somehow.
832 dict somehow.
830
833
831 Raises TypeError if the provided globals namespace is not a true dict.
834 Raises TypeError if the provided globals namespace is not a true dict.
832
835
833 Parameters
836 Parameters
834 ----------
837 ----------
835 user_ns : dict-like, optional
838 user_ns : dict-like, optional
836 The current user namespace. The items in this namespace should
839 The current user namespace. The items in this namespace should
837 be included in the output. If None, an appropriate blank
840 be included in the output. If None, an appropriate blank
838 namespace should be created.
841 namespace should be created.
839 user_global_ns : dict, optional
842 user_global_ns : dict, optional
840 The current user global namespace. The items in this namespace
843 The current user global namespace. The items in this namespace
841 should be included in the output. If None, an appropriate
844 should be included in the output. If None, an appropriate
842 blank namespace should be created.
845 blank namespace should be created.
843
846
844 Returns
847 Returns
845 -------
848 -------
846 A pair of dictionary-like object to be used as the local namespace
849 A pair of dictionary-like object to be used as the local namespace
847 of the interpreter and a dict to be used as the global namespace.
850 of the interpreter and a dict to be used as the global namespace.
848 """
851 """
849
852
850
853
851 # We must ensure that __builtin__ (without the final 's') is always
854 # We must ensure that __builtin__ (without the final 's') is always
852 # available and pointing to the __builtin__ *module*. For more details:
855 # available and pointing to the __builtin__ *module*. For more details:
853 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
856 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
854
857
855 if user_ns is None:
858 if user_ns is None:
856 # Set __name__ to __main__ to better match the behavior of the
859 # Set __name__ to __main__ to better match the behavior of the
857 # normal interpreter.
860 # normal interpreter.
858 user_ns = {'__name__' :'__main__',
861 user_ns = {'__name__' :'__main__',
859 '__builtin__' : __builtin__,
862 '__builtin__' : __builtin__,
860 '__builtins__' : __builtin__,
863 '__builtins__' : __builtin__,
861 }
864 }
862 else:
865 else:
863 user_ns.setdefault('__name__','__main__')
866 user_ns.setdefault('__name__','__main__')
864 user_ns.setdefault('__builtin__',__builtin__)
867 user_ns.setdefault('__builtin__',__builtin__)
865 user_ns.setdefault('__builtins__',__builtin__)
868 user_ns.setdefault('__builtins__',__builtin__)
866
869
867 if user_global_ns is None:
870 if user_global_ns is None:
868 user_global_ns = user_ns
871 user_global_ns = user_ns
869 if type(user_global_ns) is not dict:
872 if type(user_global_ns) is not dict:
870 raise TypeError("user_global_ns must be a true dict; got %r"
873 raise TypeError("user_global_ns must be a true dict; got %r"
871 % type(user_global_ns))
874 % type(user_global_ns))
872
875
873 return user_ns, user_global_ns
876 return user_ns, user_global_ns
874
877
875 def init_sys_modules(self):
878 def init_sys_modules(self):
876 # We need to insert into sys.modules something that looks like a
879 # We need to insert into sys.modules something that looks like a
877 # module but which accesses the IPython namespace, for shelve and
880 # module but which accesses the IPython namespace, for shelve and
878 # pickle to work interactively. Normally they rely on getting
881 # pickle to work interactively. Normally they rely on getting
879 # everything out of __main__, but for embedding purposes each IPython
882 # everything out of __main__, but for embedding purposes each IPython
880 # instance has its own private namespace, so we can't go shoving
883 # instance has its own private namespace, so we can't go shoving
881 # everything into __main__.
884 # everything into __main__.
882
885
883 # note, however, that we should only do this for non-embedded
886 # note, however, that we should only do this for non-embedded
884 # ipythons, which really mimic the __main__.__dict__ with their own
887 # ipythons, which really mimic the __main__.__dict__ with their own
885 # namespace. Embedded instances, on the other hand, should not do
888 # namespace. Embedded instances, on the other hand, should not do
886 # this because they need to manage the user local/global namespaces
889 # this because they need to manage the user local/global namespaces
887 # only, but they live within a 'normal' __main__ (meaning, they
890 # only, but they live within a 'normal' __main__ (meaning, they
888 # shouldn't overtake the execution environment of the script they're
891 # shouldn't overtake the execution environment of the script they're
889 # embedded in).
892 # embedded in).
890
893
891 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
892
895
893 try:
896 try:
894 main_name = self.user_ns['__name__']
897 main_name = self.user_ns['__name__']
895 except KeyError:
898 except KeyError:
896 raise KeyError('user_ns dictionary MUST have a "__name__" key')
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
897 else:
900 else:
898 sys.modules[main_name] = FakeModule(self.user_ns)
901 sys.modules[main_name] = FakeModule(self.user_ns)
899
902
900 def init_user_ns(self):
903 def init_user_ns(self):
901 """Initialize all user-visible namespaces to their minimum defaults.
904 """Initialize all user-visible namespaces to their minimum defaults.
902
905
903 Certain history lists are also initialized here, as they effectively
906 Certain history lists are also initialized here, as they effectively
904 act as user namespaces.
907 act as user namespaces.
905
908
906 Notes
909 Notes
907 -----
910 -----
908 All data structures here are only filled in, they are NOT reset by this
911 All data structures here are only filled in, they are NOT reset by this
909 method. If they were not empty before, data will simply be added to
912 method. If they were not empty before, data will simply be added to
910 therm.
913 therm.
911 """
914 """
912 # This function works in two parts: first we put a few things in
915 # This function works in two parts: first we put a few things in
913 # user_ns, and we sync that contents into user_ns_hidden so that these
916 # user_ns, and we sync that contents into user_ns_hidden so that these
914 # initial variables aren't shown by %who. After the sync, we add the
917 # initial variables aren't shown by %who. After the sync, we add the
915 # rest of what we *do* want the user to see with %who even on a new
918 # rest of what we *do* want the user to see with %who even on a new
916 # session (probably nothing, so theye really only see their own stuff)
919 # session (probably nothing, so theye really only see their own stuff)
917
920
918 # The user dict must *always* have a __builtin__ reference to the
921 # The user dict must *always* have a __builtin__ reference to the
919 # Python standard __builtin__ namespace, which must be imported.
922 # Python standard __builtin__ namespace, which must be imported.
920 # This is so that certain operations in prompt evaluation can be
923 # This is so that certain operations in prompt evaluation can be
921 # reliably executed with builtins. Note that we can NOT use
924 # reliably executed with builtins. Note that we can NOT use
922 # __builtins__ (note the 's'), because that can either be a dict or a
925 # __builtins__ (note the 's'), because that can either be a dict or a
923 # module, and can even mutate at runtime, depending on the context
926 # module, and can even mutate at runtime, depending on the context
924 # (Python makes no guarantees on it). In contrast, __builtin__ is
927 # (Python makes no guarantees on it). In contrast, __builtin__ is
925 # always a module object, though it must be explicitly imported.
928 # always a module object, though it must be explicitly imported.
926
929
927 # For more details:
930 # For more details:
928 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
931 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
929 ns = dict(__builtin__ = __builtin__)
932 ns = dict(__builtin__ = __builtin__)
930
933
931 # Put 'help' in the user namespace
934 # Put 'help' in the user namespace
932 try:
935 try:
933 from site import _Helper
936 from site import _Helper
934 ns['help'] = _Helper()
937 ns['help'] = _Helper()
935 except ImportError:
938 except ImportError:
936 warn('help() not available - check site.py')
939 warn('help() not available - check site.py')
937
940
938 # make global variables for user access to the histories
941 # make global variables for user access to the histories
939 ns['_ih'] = self.input_hist
942 ns['_ih'] = self.input_hist
940 ns['_oh'] = self.output_hist
943 ns['_oh'] = self.output_hist
941 ns['_dh'] = self.dir_hist
944 ns['_dh'] = self.dir_hist
942
945
943 ns['_sh'] = shadowns
946 ns['_sh'] = shadowns
944
947
945 # user aliases to input and output histories. These shouldn't show up
948 # user aliases to input and output histories. These shouldn't show up
946 # in %who, as they can have very large reprs.
949 # in %who, as they can have very large reprs.
947 ns['In'] = self.input_hist
950 ns['In'] = self.input_hist
948 ns['Out'] = self.output_hist
951 ns['Out'] = self.output_hist
949
952
950 # Store myself as the public api!!!
953 # Store myself as the public api!!!
951 ns['get_ipython'] = self.get_ipython
954 ns['get_ipython'] = self.get_ipython
952
955
953 # Sync what we've added so far to user_ns_hidden so these aren't seen
956 # Sync what we've added so far to user_ns_hidden so these aren't seen
954 # by %who
957 # by %who
955 self.user_ns_hidden.update(ns)
958 self.user_ns_hidden.update(ns)
956
959
957 # Anything put into ns now would show up in %who. Think twice before
960 # Anything put into ns now would show up in %who. Think twice before
958 # putting anything here, as we really want %who to show the user their
961 # putting anything here, as we really want %who to show the user their
959 # stuff, not our variables.
962 # stuff, not our variables.
960
963
961 # Finally, update the real user's namespace
964 # Finally, update the real user's namespace
962 self.user_ns.update(ns)
965 self.user_ns.update(ns)
963
966
964
967
965 def reset(self):
968 def reset(self):
966 """Clear all internal namespaces.
969 """Clear all internal namespaces.
967
970
968 Note that this is much more aggressive than %reset, since it clears
971 Note that this is much more aggressive than %reset, since it clears
969 fully all namespaces, as well as all input/output lists.
972 fully all namespaces, as well as all input/output lists.
970 """
973 """
971 for ns in self.ns_refs_table:
974 for ns in self.ns_refs_table:
972 ns.clear()
975 ns.clear()
973
976
974 self.alias_manager.clear_aliases()
977 self.alias_manager.clear_aliases()
975
978
976 # Clear input and output histories
979 # Clear input and output histories
977 self.input_hist[:] = []
980 self.input_hist[:] = []
978 self.input_hist_raw[:] = []
981 self.input_hist_raw[:] = []
979 self.output_hist.clear()
982 self.output_hist.clear()
980
983
984 # Reset counter used to index all histories
985 self.execution_count = 0
986
981 # Restore the user namespaces to minimal usability
987 # Restore the user namespaces to minimal usability
982 self.init_user_ns()
988 self.init_user_ns()
983
989
984 # Restore the default and user aliases
990 # Restore the default and user aliases
985 self.alias_manager.init_aliases()
991 self.alias_manager.init_aliases()
986
992
987 def reset_selective(self, regex=None):
993 def reset_selective(self, regex=None):
988 """Clear selective variables from internal namespaces based on a
994 """Clear selective variables from internal namespaces based on a
989 specified regular expression.
995 specified regular expression.
990
996
991 Parameters
997 Parameters
992 ----------
998 ----------
993 regex : string or compiled pattern, optional
999 regex : string or compiled pattern, optional
994 A regular expression pattern that will be used in searching
1000 A regular expression pattern that will be used in searching
995 variable names in the users namespaces.
1001 variable names in the users namespaces.
996 """
1002 """
997 if regex is not None:
1003 if regex is not None:
998 try:
1004 try:
999 m = re.compile(regex)
1005 m = re.compile(regex)
1000 except TypeError:
1006 except TypeError:
1001 raise TypeError('regex must be a string or compiled pattern')
1007 raise TypeError('regex must be a string or compiled pattern')
1002 # Search for keys in each namespace that match the given regex
1008 # Search for keys in each namespace that match the given regex
1003 # If a match is found, delete the key/value pair.
1009 # If a match is found, delete the key/value pair.
1004 for ns in self.ns_refs_table:
1010 for ns in self.ns_refs_table:
1005 for var in ns:
1011 for var in ns:
1006 if m.search(var):
1012 if m.search(var):
1007 del ns[var]
1013 del ns[var]
1008
1014
1009 def push(self, variables, interactive=True):
1015 def push(self, variables, interactive=True):
1010 """Inject a group of variables into the IPython user namespace.
1016 """Inject a group of variables into the IPython user namespace.
1011
1017
1012 Parameters
1018 Parameters
1013 ----------
1019 ----------
1014 variables : dict, str or list/tuple of str
1020 variables : dict, str or list/tuple of str
1015 The variables to inject into the user's namespace. If a dict, a
1021 The variables to inject into the user's namespace. If a dict, a
1016 simple update is done. If a str, the string is assumed to have
1022 simple update is done. If a str, the string is assumed to have
1017 variable names separated by spaces. A list/tuple of str can also
1023 variable names separated by spaces. A list/tuple of str can also
1018 be used to give the variable names. If just the variable names are
1024 be used to give the variable names. If just the variable names are
1019 give (list/tuple/str) then the variable values looked up in the
1025 give (list/tuple/str) then the variable values looked up in the
1020 callers frame.
1026 callers frame.
1021 interactive : bool
1027 interactive : bool
1022 If True (default), the variables will be listed with the ``who``
1028 If True (default), the variables will be listed with the ``who``
1023 magic.
1029 magic.
1024 """
1030 """
1025 vdict = None
1031 vdict = None
1026
1032
1027 # We need a dict of name/value pairs to do namespace updates.
1033 # We need a dict of name/value pairs to do namespace updates.
1028 if isinstance(variables, dict):
1034 if isinstance(variables, dict):
1029 vdict = variables
1035 vdict = variables
1030 elif isinstance(variables, (basestring, list, tuple)):
1036 elif isinstance(variables, (basestring, list, tuple)):
1031 if isinstance(variables, basestring):
1037 if isinstance(variables, basestring):
1032 vlist = variables.split()
1038 vlist = variables.split()
1033 else:
1039 else:
1034 vlist = variables
1040 vlist = variables
1035 vdict = {}
1041 vdict = {}
1036 cf = sys._getframe(1)
1042 cf = sys._getframe(1)
1037 for name in vlist:
1043 for name in vlist:
1038 try:
1044 try:
1039 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1045 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1040 except:
1046 except:
1041 print ('Could not get variable %s from %s' %
1047 print ('Could not get variable %s from %s' %
1042 (name,cf.f_code.co_name))
1048 (name,cf.f_code.co_name))
1043 else:
1049 else:
1044 raise ValueError('variables must be a dict/str/list/tuple')
1050 raise ValueError('variables must be a dict/str/list/tuple')
1045
1051
1046 # Propagate variables to user namespace
1052 # Propagate variables to user namespace
1047 self.user_ns.update(vdict)
1053 self.user_ns.update(vdict)
1048
1054
1049 # And configure interactive visibility
1055 # And configure interactive visibility
1050 config_ns = self.user_ns_hidden
1056 config_ns = self.user_ns_hidden
1051 if interactive:
1057 if interactive:
1052 for name, val in vdict.iteritems():
1058 for name, val in vdict.iteritems():
1053 config_ns.pop(name, None)
1059 config_ns.pop(name, None)
1054 else:
1060 else:
1055 for name,val in vdict.iteritems():
1061 for name,val in vdict.iteritems():
1056 config_ns[name] = val
1062 config_ns[name] = val
1057
1063
1058 #-------------------------------------------------------------------------
1064 #-------------------------------------------------------------------------
1059 # Things related to object introspection
1065 # Things related to object introspection
1060 #-------------------------------------------------------------------------
1066 #-------------------------------------------------------------------------
1061
1067
1062 def _ofind(self, oname, namespaces=None):
1068 def _ofind(self, oname, namespaces=None):
1063 """Find an object in the available namespaces.
1069 """Find an object in the available namespaces.
1064
1070
1065 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1071 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1066
1072
1067 Has special code to detect magic functions.
1073 Has special code to detect magic functions.
1068 """
1074 """
1069 #oname = oname.strip()
1075 #oname = oname.strip()
1070 #print '1- oname: <%r>' % oname # dbg
1076 #print '1- oname: <%r>' % oname # dbg
1071 try:
1077 try:
1072 oname = oname.strip().encode('ascii')
1078 oname = oname.strip().encode('ascii')
1073 #print '2- oname: <%r>' % oname # dbg
1079 #print '2- oname: <%r>' % oname # dbg
1074 except UnicodeEncodeError:
1080 except UnicodeEncodeError:
1075 print 'Python identifiers can only contain ascii characters.'
1081 print 'Python identifiers can only contain ascii characters.'
1076 return dict(found=False)
1082 return dict(found=False)
1077
1083
1078 alias_ns = None
1084 alias_ns = None
1079 if namespaces is None:
1085 if namespaces is None:
1080 # Namespaces to search in:
1086 # Namespaces to search in:
1081 # Put them in a list. The order is important so that we
1087 # Put them in a list. The order is important so that we
1082 # find things in the same order that Python finds them.
1088 # find things in the same order that Python finds them.
1083 namespaces = [ ('Interactive', self.user_ns),
1089 namespaces = [ ('Interactive', self.user_ns),
1084 ('IPython internal', self.internal_ns),
1090 ('IPython internal', self.internal_ns),
1085 ('Python builtin', __builtin__.__dict__),
1091 ('Python builtin', __builtin__.__dict__),
1086 ('Alias', self.alias_manager.alias_table),
1092 ('Alias', self.alias_manager.alias_table),
1087 ]
1093 ]
1088 alias_ns = self.alias_manager.alias_table
1094 alias_ns = self.alias_manager.alias_table
1089
1095
1090 # initialize results to 'null'
1096 # initialize results to 'null'
1091 found = False; obj = None; ospace = None; ds = None;
1097 found = False; obj = None; ospace = None; ds = None;
1092 ismagic = False; isalias = False; parent = None
1098 ismagic = False; isalias = False; parent = None
1093
1099
1094 # We need to special-case 'print', which as of python2.6 registers as a
1100 # We need to special-case 'print', which as of python2.6 registers as a
1095 # function but should only be treated as one if print_function was
1101 # function but should only be treated as one if print_function was
1096 # loaded with a future import. In this case, just bail.
1102 # loaded with a future import. In this case, just bail.
1097 if (oname == 'print' and not (self.compile.compiler.flags &
1103 if (oname == 'print' and not (self.compile.compiler.flags &
1098 __future__.CO_FUTURE_PRINT_FUNCTION)):
1104 __future__.CO_FUTURE_PRINT_FUNCTION)):
1099 return {'found':found, 'obj':obj, 'namespace':ospace,
1105 return {'found':found, 'obj':obj, 'namespace':ospace,
1100 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1106 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1101
1107
1102 # Look for the given name by splitting it in parts. If the head is
1108 # Look for the given name by splitting it in parts. If the head is
1103 # found, then we look for all the remaining parts as members, and only
1109 # found, then we look for all the remaining parts as members, and only
1104 # declare success if we can find them all.
1110 # declare success if we can find them all.
1105 oname_parts = oname.split('.')
1111 oname_parts = oname.split('.')
1106 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1112 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1107 for nsname,ns in namespaces:
1113 for nsname,ns in namespaces:
1108 try:
1114 try:
1109 obj = ns[oname_head]
1115 obj = ns[oname_head]
1110 except KeyError:
1116 except KeyError:
1111 continue
1117 continue
1112 else:
1118 else:
1113 #print 'oname_rest:', oname_rest # dbg
1119 #print 'oname_rest:', oname_rest # dbg
1114 for part in oname_rest:
1120 for part in oname_rest:
1115 try:
1121 try:
1116 parent = obj
1122 parent = obj
1117 obj = getattr(obj,part)
1123 obj = getattr(obj,part)
1118 except:
1124 except:
1119 # Blanket except b/c some badly implemented objects
1125 # Blanket except b/c some badly implemented objects
1120 # allow __getattr__ to raise exceptions other than
1126 # allow __getattr__ to raise exceptions other than
1121 # AttributeError, which then crashes IPython.
1127 # AttributeError, which then crashes IPython.
1122 break
1128 break
1123 else:
1129 else:
1124 # If we finish the for loop (no break), we got all members
1130 # If we finish the for loop (no break), we got all members
1125 found = True
1131 found = True
1126 ospace = nsname
1132 ospace = nsname
1127 if ns == alias_ns:
1133 if ns == alias_ns:
1128 isalias = True
1134 isalias = True
1129 break # namespace loop
1135 break # namespace loop
1130
1136
1131 # Try to see if it's magic
1137 # Try to see if it's magic
1132 if not found:
1138 if not found:
1133 if oname.startswith(ESC_MAGIC):
1139 if oname.startswith(ESC_MAGIC):
1134 oname = oname[1:]
1140 oname = oname[1:]
1135 obj = getattr(self,'magic_'+oname,None)
1141 obj = getattr(self,'magic_'+oname,None)
1136 if obj is not None:
1142 if obj is not None:
1137 found = True
1143 found = True
1138 ospace = 'IPython internal'
1144 ospace = 'IPython internal'
1139 ismagic = True
1145 ismagic = True
1140
1146
1141 # Last try: special-case some literals like '', [], {}, etc:
1147 # Last try: special-case some literals like '', [], {}, etc:
1142 if not found and oname_head in ["''",'""','[]','{}','()']:
1148 if not found and oname_head in ["''",'""','[]','{}','()']:
1143 obj = eval(oname_head)
1149 obj = eval(oname_head)
1144 found = True
1150 found = True
1145 ospace = 'Interactive'
1151 ospace = 'Interactive'
1146
1152
1147 return {'found':found, 'obj':obj, 'namespace':ospace,
1153 return {'found':found, 'obj':obj, 'namespace':ospace,
1148 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1154 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1149
1155
1150 def _ofind_property(self, oname, info):
1156 def _ofind_property(self, oname, info):
1151 """Second part of object finding, to look for property details."""
1157 """Second part of object finding, to look for property details."""
1152 if info.found:
1158 if info.found:
1153 # Get the docstring of the class property if it exists.
1159 # Get the docstring of the class property if it exists.
1154 path = oname.split('.')
1160 path = oname.split('.')
1155 root = '.'.join(path[:-1])
1161 root = '.'.join(path[:-1])
1156 if info.parent is not None:
1162 if info.parent is not None:
1157 try:
1163 try:
1158 target = getattr(info.parent, '__class__')
1164 target = getattr(info.parent, '__class__')
1159 # The object belongs to a class instance.
1165 # The object belongs to a class instance.
1160 try:
1166 try:
1161 target = getattr(target, path[-1])
1167 target = getattr(target, path[-1])
1162 # The class defines the object.
1168 # The class defines the object.
1163 if isinstance(target, property):
1169 if isinstance(target, property):
1164 oname = root + '.__class__.' + path[-1]
1170 oname = root + '.__class__.' + path[-1]
1165 info = Struct(self._ofind(oname))
1171 info = Struct(self._ofind(oname))
1166 except AttributeError: pass
1172 except AttributeError: pass
1167 except AttributeError: pass
1173 except AttributeError: pass
1168
1174
1169 # We return either the new info or the unmodified input if the object
1175 # We return either the new info or the unmodified input if the object
1170 # hadn't been found
1176 # hadn't been found
1171 return info
1177 return info
1172
1178
1173 def _object_find(self, oname, namespaces=None):
1179 def _object_find(self, oname, namespaces=None):
1174 """Find an object and return a struct with info about it."""
1180 """Find an object and return a struct with info about it."""
1175 inf = Struct(self._ofind(oname, namespaces))
1181 inf = Struct(self._ofind(oname, namespaces))
1176 return Struct(self._ofind_property(oname, inf))
1182 return Struct(self._ofind_property(oname, inf))
1177
1183
1178 def _inspect(self, meth, oname, namespaces=None, **kw):
1184 def _inspect(self, meth, oname, namespaces=None, **kw):
1179 """Generic interface to the inspector system.
1185 """Generic interface to the inspector system.
1180
1186
1181 This function is meant to be called by pdef, pdoc & friends."""
1187 This function is meant to be called by pdef, pdoc & friends."""
1182 info = self._object_find(oname)
1188 info = self._object_find(oname)
1183 if info.found:
1189 if info.found:
1184 pmethod = getattr(self.inspector, meth)
1190 pmethod = getattr(self.inspector, meth)
1185 formatter = format_screen if info.ismagic else None
1191 formatter = format_screen if info.ismagic else None
1186 if meth == 'pdoc':
1192 if meth == 'pdoc':
1187 pmethod(info.obj, oname, formatter)
1193 pmethod(info.obj, oname, formatter)
1188 elif meth == 'pinfo':
1194 elif meth == 'pinfo':
1189 pmethod(info.obj, oname, formatter, info, **kw)
1195 pmethod(info.obj, oname, formatter, info, **kw)
1190 else:
1196 else:
1191 pmethod(info.obj, oname)
1197 pmethod(info.obj, oname)
1192 else:
1198 else:
1193 print 'Object `%s` not found.' % oname
1199 print 'Object `%s` not found.' % oname
1194 return 'not found' # so callers can take other action
1200 return 'not found' # so callers can take other action
1195
1201
1196 def object_inspect(self, oname):
1202 def object_inspect(self, oname):
1197 info = self._object_find(oname)
1203 info = self._object_find(oname)
1198 if info.found:
1204 if info.found:
1199 return self.inspector.info(info.obj, oname, info=info)
1205 return self.inspector.info(info.obj, oname, info=info)
1200 else:
1206 else:
1201 return oinspect.object_info(name=oname, found=False)
1207 return oinspect.object_info(name=oname, found=False)
1202
1208
1203 #-------------------------------------------------------------------------
1209 #-------------------------------------------------------------------------
1204 # Things related to history management
1210 # Things related to history management
1205 #-------------------------------------------------------------------------
1211 #-------------------------------------------------------------------------
1206
1212
1207 def init_history(self):
1213 def init_history(self):
1208 # List of input with multi-line handling.
1214 # List of input with multi-line handling.
1209 self.input_hist = InputList()
1215 self.input_hist = InputList()
1210 # This one will hold the 'raw' input history, without any
1216 # This one will hold the 'raw' input history, without any
1211 # pre-processing. This will allow users to retrieve the input just as
1217 # pre-processing. This will allow users to retrieve the input just as
1212 # it was exactly typed in by the user, with %hist -r.
1218 # it was exactly typed in by the user, with %hist -r.
1213 self.input_hist_raw = InputList()
1219 self.input_hist_raw = InputList()
1214
1220
1215 # list of visited directories
1221 # list of visited directories
1216 try:
1222 try:
1217 self.dir_hist = [os.getcwd()]
1223 self.dir_hist = [os.getcwd()]
1218 except OSError:
1224 except OSError:
1219 self.dir_hist = []
1225 self.dir_hist = []
1220
1226
1221 # dict of output history
1227 # dict of output history
1222 self.output_hist = {}
1228 self.output_hist = {}
1223
1229
1224 # Now the history file
1230 # Now the history file
1225 if self.profile:
1231 if self.profile:
1226 histfname = 'history-%s' % self.profile
1232 histfname = 'history-%s' % self.profile
1227 else:
1233 else:
1228 histfname = 'history'
1234 histfname = 'history'
1229 self.histfile = os.path.join(self.ipython_dir, histfname)
1235 self.histfile = os.path.join(self.ipython_dir, histfname)
1230
1236
1231 # Fill the history zero entry, user counter starts at 1
1237 # Fill the history zero entry, user counter starts at 1
1232 self.input_hist.append('\n')
1238 self.input_hist.append('\n')
1233 self.input_hist_raw.append('\n')
1239 self.input_hist_raw.append('\n')
1234
1240
1235 def init_shadow_hist(self):
1241 def init_shadow_hist(self):
1236 try:
1242 try:
1237 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1243 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1238 except exceptions.UnicodeDecodeError:
1244 except exceptions.UnicodeDecodeError:
1239 print "Your ipython_dir can't be decoded to unicode!"
1245 print "Your ipython_dir can't be decoded to unicode!"
1240 print "Please set HOME environment variable to something that"
1246 print "Please set HOME environment variable to something that"
1241 print r"only has ASCII characters, e.g. c:\home"
1247 print r"only has ASCII characters, e.g. c:\home"
1242 print "Now it is", self.ipython_dir
1248 print "Now it is", self.ipython_dir
1243 sys.exit()
1249 sys.exit()
1244 self.shadowhist = ipcorehist.ShadowHist(self.db)
1250 self.shadowhist = ipcorehist.ShadowHist(self.db)
1245
1251
1246 def savehist(self):
1252 def savehist(self):
1247 """Save input history to a file (via readline library)."""
1253 """Save input history to a file (via readline library)."""
1248
1254
1249 try:
1255 try:
1250 self.readline.write_history_file(self.histfile)
1256 self.readline.write_history_file(self.histfile)
1251 except:
1257 except:
1252 print 'Unable to save IPython command history to file: ' + \
1258 print 'Unable to save IPython command history to file: ' + \
1253 `self.histfile`
1259 `self.histfile`
1254
1260
1255 def reloadhist(self):
1261 def reloadhist(self):
1256 """Reload the input history from disk file."""
1262 """Reload the input history from disk file."""
1257
1263
1258 try:
1264 try:
1259 self.readline.clear_history()
1265 self.readline.clear_history()
1260 self.readline.read_history_file(self.shell.histfile)
1266 self.readline.read_history_file(self.shell.histfile)
1261 except AttributeError:
1267 except AttributeError:
1262 pass
1268 pass
1263
1269
1264 def history_saving_wrapper(self, func):
1270 def history_saving_wrapper(self, func):
1265 """ Wrap func for readline history saving
1271 """ Wrap func for readline history saving
1266
1272
1267 Convert func into callable that saves & restores
1273 Convert func into callable that saves & restores
1268 history around the call """
1274 history around the call """
1269
1275
1270 if self.has_readline:
1276 if self.has_readline:
1271 from IPython.utils import rlineimpl as readline
1277 from IPython.utils import rlineimpl as readline
1272 else:
1278 else:
1273 return func
1279 return func
1274
1280
1275 def wrapper():
1281 def wrapper():
1276 self.savehist()
1282 self.savehist()
1277 try:
1283 try:
1278 func()
1284 func()
1279 finally:
1285 finally:
1280 readline.read_history_file(self.histfile)
1286 readline.read_history_file(self.histfile)
1281 return wrapper
1287 return wrapper
1282
1288
1283 def get_history(self, index=None, raw=False, output=True):
1289 def get_history(self, index=None, raw=False, output=True):
1284 """Get the history list.
1290 """Get the history list.
1285
1291
1286 Get the input and output history.
1292 Get the input and output history.
1287
1293
1288 Parameters
1294 Parameters
1289 ----------
1295 ----------
1290 index : n or (n1, n2) or None
1296 index : n or (n1, n2) or None
1291 If n, then the last entries. If a tuple, then all in
1297 If n, then the last entries. If a tuple, then all in
1292 range(n1, n2). If None, then all entries. Raises IndexError if
1298 range(n1, n2). If None, then all entries. Raises IndexError if
1293 the format of index is incorrect.
1299 the format of index is incorrect.
1294 raw : bool
1300 raw : bool
1295 If True, return the raw input.
1301 If True, return the raw input.
1296 output : bool
1302 output : bool
1297 If True, then return the output as well.
1303 If True, then return the output as well.
1298
1304
1299 Returns
1305 Returns
1300 -------
1306 -------
1301 If output is True, then return a dict of tuples, keyed by the prompt
1307 If output is True, then return a dict of tuples, keyed by the prompt
1302 numbers and with values of (input, output). If output is False, then
1308 numbers and with values of (input, output). If output is False, then
1303 a dict, keyed by the prompt number with the values of input. Raises
1309 a dict, keyed by the prompt number with the values of input. Raises
1304 IndexError if no history is found.
1310 IndexError if no history is found.
1305 """
1311 """
1306 if raw:
1312 if raw:
1307 input_hist = self.input_hist_raw
1313 input_hist = self.input_hist_raw
1308 else:
1314 else:
1309 input_hist = self.input_hist
1315 input_hist = self.input_hist
1310 if output:
1316 if output:
1311 output_hist = self.user_ns['Out']
1317 output_hist = self.user_ns['Out']
1312 n = len(input_hist)
1318 n = len(input_hist)
1313 if index is None:
1319 if index is None:
1314 start=0; stop=n
1320 start=0; stop=n
1315 elif isinstance(index, int):
1321 elif isinstance(index, int):
1316 start=n-index; stop=n
1322 start=n-index; stop=n
1317 elif isinstance(index, tuple) and len(index) == 2:
1323 elif isinstance(index, tuple) and len(index) == 2:
1318 start=index[0]; stop=index[1]
1324 start=index[0]; stop=index[1]
1319 else:
1325 else:
1320 raise IndexError('Not a valid index for the input history: %r'
1326 raise IndexError('Not a valid index for the input history: %r'
1321 % index)
1327 % index)
1322 hist = {}
1328 hist = {}
1323 for i in range(start, stop):
1329 for i in range(start, stop):
1324 if output:
1330 if output:
1325 hist[i] = (input_hist[i], output_hist.get(i))
1331 hist[i] = (input_hist[i], output_hist.get(i))
1326 else:
1332 else:
1327 hist[i] = input_hist[i]
1333 hist[i] = input_hist[i]
1328 if len(hist)==0:
1334 if len(hist)==0:
1329 raise IndexError('No history for range of indices: %r' % index)
1335 raise IndexError('No history for range of indices: %r' % index)
1330 return hist
1336 return hist
1331
1337
1332 #-------------------------------------------------------------------------
1338 #-------------------------------------------------------------------------
1333 # Things related to exception handling and tracebacks (not debugging)
1339 # Things related to exception handling and tracebacks (not debugging)
1334 #-------------------------------------------------------------------------
1340 #-------------------------------------------------------------------------
1335
1341
1336 def init_traceback_handlers(self, custom_exceptions):
1342 def init_traceback_handlers(self, custom_exceptions):
1337 # Syntax error handler.
1343 # Syntax error handler.
1338 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1344 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1339
1345
1340 # The interactive one is initialized with an offset, meaning we always
1346 # The interactive one is initialized with an offset, meaning we always
1341 # want to remove the topmost item in the traceback, which is our own
1347 # want to remove the topmost item in the traceback, which is our own
1342 # internal code. Valid modes: ['Plain','Context','Verbose']
1348 # internal code. Valid modes: ['Plain','Context','Verbose']
1343 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1349 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1344 color_scheme='NoColor',
1350 color_scheme='NoColor',
1345 tb_offset = 1)
1351 tb_offset = 1)
1346
1352
1347 # The instance will store a pointer to the system-wide exception hook,
1353 # The instance will store a pointer to the system-wide exception hook,
1348 # so that runtime code (such as magics) can access it. This is because
1354 # so that runtime code (such as magics) can access it. This is because
1349 # during the read-eval loop, it may get temporarily overwritten.
1355 # during the read-eval loop, it may get temporarily overwritten.
1350 self.sys_excepthook = sys.excepthook
1356 self.sys_excepthook = sys.excepthook
1351
1357
1352 # and add any custom exception handlers the user may have specified
1358 # and add any custom exception handlers the user may have specified
1353 self.set_custom_exc(*custom_exceptions)
1359 self.set_custom_exc(*custom_exceptions)
1354
1360
1355 # Set the exception mode
1361 # Set the exception mode
1356 self.InteractiveTB.set_mode(mode=self.xmode)
1362 self.InteractiveTB.set_mode(mode=self.xmode)
1357
1363
1358 def set_custom_exc(self, exc_tuple, handler):
1364 def set_custom_exc(self, exc_tuple, handler):
1359 """set_custom_exc(exc_tuple,handler)
1365 """set_custom_exc(exc_tuple,handler)
1360
1366
1361 Set a custom exception handler, which will be called if any of the
1367 Set a custom exception handler, which will be called if any of the
1362 exceptions in exc_tuple occur in the mainloop (specifically, in the
1368 exceptions in exc_tuple occur in the mainloop (specifically, in the
1363 runcode() method.
1369 runcode() method.
1364
1370
1365 Inputs:
1371 Inputs:
1366
1372
1367 - exc_tuple: a *tuple* of valid exceptions to call the defined
1373 - exc_tuple: a *tuple* of valid exceptions to call the defined
1368 handler for. It is very important that you use a tuple, and NOT A
1374 handler for. It is very important that you use a tuple, and NOT A
1369 LIST here, because of the way Python's except statement works. If
1375 LIST here, because of the way Python's except statement works. If
1370 you only want to trap a single exception, use a singleton tuple:
1376 you only want to trap a single exception, use a singleton tuple:
1371
1377
1372 exc_tuple == (MyCustomException,)
1378 exc_tuple == (MyCustomException,)
1373
1379
1374 - handler: this must be defined as a function with the following
1380 - handler: this must be defined as a function with the following
1375 basic interface::
1381 basic interface::
1376
1382
1377 def my_handler(self, etype, value, tb, tb_offset=None)
1383 def my_handler(self, etype, value, tb, tb_offset=None)
1378 ...
1384 ...
1379 # The return value must be
1385 # The return value must be
1380 return structured_traceback
1386 return structured_traceback
1381
1387
1382 This will be made into an instance method (via new.instancemethod)
1388 This will be made into an instance method (via new.instancemethod)
1383 of IPython itself, and it will be called if any of the exceptions
1389 of IPython itself, and it will be called if any of the exceptions
1384 listed in the exc_tuple are caught. If the handler is None, an
1390 listed in the exc_tuple are caught. If the handler is None, an
1385 internal basic one is used, which just prints basic info.
1391 internal basic one is used, which just prints basic info.
1386
1392
1387 WARNING: by putting in your own exception handler into IPython's main
1393 WARNING: by putting in your own exception handler into IPython's main
1388 execution loop, you run a very good chance of nasty crashes. This
1394 execution loop, you run a very good chance of nasty crashes. This
1389 facility should only be used if you really know what you are doing."""
1395 facility should only be used if you really know what you are doing."""
1390
1396
1391 assert type(exc_tuple)==type(()) , \
1397 assert type(exc_tuple)==type(()) , \
1392 "The custom exceptions must be given AS A TUPLE."
1398 "The custom exceptions must be given AS A TUPLE."
1393
1399
1394 def dummy_handler(self,etype,value,tb):
1400 def dummy_handler(self,etype,value,tb):
1395 print '*** Simple custom exception handler ***'
1401 print '*** Simple custom exception handler ***'
1396 print 'Exception type :',etype
1402 print 'Exception type :',etype
1397 print 'Exception value:',value
1403 print 'Exception value:',value
1398 print 'Traceback :',tb
1404 print 'Traceback :',tb
1399 print 'Source code :','\n'.join(self.buffer)
1405 print 'Source code :','\n'.join(self.buffer)
1400
1406
1401 if handler is None: handler = dummy_handler
1407 if handler is None: handler = dummy_handler
1402
1408
1403 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1409 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1404 self.custom_exceptions = exc_tuple
1410 self.custom_exceptions = exc_tuple
1405
1411
1406 def excepthook(self, etype, value, tb):
1412 def excepthook(self, etype, value, tb):
1407 """One more defense for GUI apps that call sys.excepthook.
1413 """One more defense for GUI apps that call sys.excepthook.
1408
1414
1409 GUI frameworks like wxPython trap exceptions and call
1415 GUI frameworks like wxPython trap exceptions and call
1410 sys.excepthook themselves. I guess this is a feature that
1416 sys.excepthook themselves. I guess this is a feature that
1411 enables them to keep running after exceptions that would
1417 enables them to keep running after exceptions that would
1412 otherwise kill their mainloop. This is a bother for IPython
1418 otherwise kill their mainloop. This is a bother for IPython
1413 which excepts to catch all of the program exceptions with a try:
1419 which excepts to catch all of the program exceptions with a try:
1414 except: statement.
1420 except: statement.
1415
1421
1416 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1422 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1417 any app directly invokes sys.excepthook, it will look to the user like
1423 any app directly invokes sys.excepthook, it will look to the user like
1418 IPython crashed. In order to work around this, we can disable the
1424 IPython crashed. In order to work around this, we can disable the
1419 CrashHandler and replace it with this excepthook instead, which prints a
1425 CrashHandler and replace it with this excepthook instead, which prints a
1420 regular traceback using our InteractiveTB. In this fashion, apps which
1426 regular traceback using our InteractiveTB. In this fashion, apps which
1421 call sys.excepthook will generate a regular-looking exception from
1427 call sys.excepthook will generate a regular-looking exception from
1422 IPython, and the CrashHandler will only be triggered by real IPython
1428 IPython, and the CrashHandler will only be triggered by real IPython
1423 crashes.
1429 crashes.
1424
1430
1425 This hook should be used sparingly, only in places which are not likely
1431 This hook should be used sparingly, only in places which are not likely
1426 to be true IPython errors.
1432 to be true IPython errors.
1427 """
1433 """
1428 self.showtraceback((etype,value,tb),tb_offset=0)
1434 self.showtraceback((etype,value,tb),tb_offset=0)
1429
1435
1430 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1436 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1431 exception_only=False):
1437 exception_only=False):
1432 """Display the exception that just occurred.
1438 """Display the exception that just occurred.
1433
1439
1434 If nothing is known about the exception, this is the method which
1440 If nothing is known about the exception, this is the method which
1435 should be used throughout the code for presenting user tracebacks,
1441 should be used throughout the code for presenting user tracebacks,
1436 rather than directly invoking the InteractiveTB object.
1442 rather than directly invoking the InteractiveTB object.
1437
1443
1438 A specific showsyntaxerror() also exists, but this method can take
1444 A specific showsyntaxerror() also exists, but this method can take
1439 care of calling it if needed, so unless you are explicitly catching a
1445 care of calling it if needed, so unless you are explicitly catching a
1440 SyntaxError exception, don't try to analyze the stack manually and
1446 SyntaxError exception, don't try to analyze the stack manually and
1441 simply call this method."""
1447 simply call this method."""
1442
1448
1443 try:
1449 try:
1444 if exc_tuple is None:
1450 if exc_tuple is None:
1445 etype, value, tb = sys.exc_info()
1451 etype, value, tb = sys.exc_info()
1446 else:
1452 else:
1447 etype, value, tb = exc_tuple
1453 etype, value, tb = exc_tuple
1448
1454
1449 if etype is None:
1455 if etype is None:
1450 if hasattr(sys, 'last_type'):
1456 if hasattr(sys, 'last_type'):
1451 etype, value, tb = sys.last_type, sys.last_value, \
1457 etype, value, tb = sys.last_type, sys.last_value, \
1452 sys.last_traceback
1458 sys.last_traceback
1453 else:
1459 else:
1454 self.write_err('No traceback available to show.\n')
1460 self.write_err('No traceback available to show.\n')
1455 return
1461 return
1456
1462
1457 if etype is SyntaxError:
1463 if etype is SyntaxError:
1458 # Though this won't be called by syntax errors in the input
1464 # Though this won't be called by syntax errors in the input
1459 # line, there may be SyntaxError cases whith imported code.
1465 # line, there may be SyntaxError cases whith imported code.
1460 self.showsyntaxerror(filename)
1466 self.showsyntaxerror(filename)
1461 elif etype is UsageError:
1467 elif etype is UsageError:
1462 print "UsageError:", value
1468 print "UsageError:", value
1463 else:
1469 else:
1464 # WARNING: these variables are somewhat deprecated and not
1470 # WARNING: these variables are somewhat deprecated and not
1465 # necessarily safe to use in a threaded environment, but tools
1471 # necessarily safe to use in a threaded environment, but tools
1466 # like pdb depend on their existence, so let's set them. If we
1472 # like pdb depend on their existence, so let's set them. If we
1467 # find problems in the field, we'll need to revisit their use.
1473 # find problems in the field, we'll need to revisit their use.
1468 sys.last_type = etype
1474 sys.last_type = etype
1469 sys.last_value = value
1475 sys.last_value = value
1470 sys.last_traceback = tb
1476 sys.last_traceback = tb
1471
1477
1472 if etype in self.custom_exceptions:
1478 if etype in self.custom_exceptions:
1473 # FIXME: Old custom traceback objects may just return a
1479 # FIXME: Old custom traceback objects may just return a
1474 # string, in that case we just put it into a list
1480 # string, in that case we just put it into a list
1475 stb = self.CustomTB(etype, value, tb, tb_offset)
1481 stb = self.CustomTB(etype, value, tb, tb_offset)
1476 if isinstance(ctb, basestring):
1482 if isinstance(ctb, basestring):
1477 stb = [stb]
1483 stb = [stb]
1478 else:
1484 else:
1479 if exception_only:
1485 if exception_only:
1480 stb = ['An exception has occurred, use %tb to see '
1486 stb = ['An exception has occurred, use %tb to see '
1481 'the full traceback.\n']
1487 'the full traceback.\n']
1482 stb.extend(self.InteractiveTB.get_exception_only(etype,
1488 stb.extend(self.InteractiveTB.get_exception_only(etype,
1483 value))
1489 value))
1484 else:
1490 else:
1485 stb = self.InteractiveTB.structured_traceback(etype,
1491 stb = self.InteractiveTB.structured_traceback(etype,
1486 value, tb, tb_offset=tb_offset)
1492 value, tb, tb_offset=tb_offset)
1487 # FIXME: the pdb calling should be done by us, not by
1493 # FIXME: the pdb calling should be done by us, not by
1488 # the code computing the traceback.
1494 # the code computing the traceback.
1489 if self.InteractiveTB.call_pdb:
1495 if self.InteractiveTB.call_pdb:
1490 # pdb mucks up readline, fix it back
1496 # pdb mucks up readline, fix it back
1491 self.set_readline_completer()
1497 self.set_readline_completer()
1492
1498
1493 # Actually show the traceback
1499 # Actually show the traceback
1494 self._showtraceback(etype, value, stb)
1500 self._showtraceback(etype, value, stb)
1495
1501
1496 except KeyboardInterrupt:
1502 except KeyboardInterrupt:
1497 self.write_err("\nKeyboardInterrupt\n")
1503 self.write_err("\nKeyboardInterrupt\n")
1498
1504
1499 def _showtraceback(self, etype, evalue, stb):
1505 def _showtraceback(self, etype, evalue, stb):
1500 """Actually show a traceback.
1506 """Actually show a traceback.
1501
1507
1502 Subclasses may override this method to put the traceback on a different
1508 Subclasses may override this method to put the traceback on a different
1503 place, like a side channel.
1509 place, like a side channel.
1504 """
1510 """
1505 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1511 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1506
1512
1507 def showsyntaxerror(self, filename=None):
1513 def showsyntaxerror(self, filename=None):
1508 """Display the syntax error that just occurred.
1514 """Display the syntax error that just occurred.
1509
1515
1510 This doesn't display a stack trace because there isn't one.
1516 This doesn't display a stack trace because there isn't one.
1511
1517
1512 If a filename is given, it is stuffed in the exception instead
1518 If a filename is given, it is stuffed in the exception instead
1513 of what was there before (because Python's parser always uses
1519 of what was there before (because Python's parser always uses
1514 "<string>" when reading from a string).
1520 "<string>" when reading from a string).
1515 """
1521 """
1516 etype, value, last_traceback = sys.exc_info()
1522 etype, value, last_traceback = sys.exc_info()
1517
1523
1518 # See note about these variables in showtraceback() above
1524 # See note about these variables in showtraceback() above
1519 sys.last_type = etype
1525 sys.last_type = etype
1520 sys.last_value = value
1526 sys.last_value = value
1521 sys.last_traceback = last_traceback
1527 sys.last_traceback = last_traceback
1522
1528
1523 if filename and etype is SyntaxError:
1529 if filename and etype is SyntaxError:
1524 # Work hard to stuff the correct filename in the exception
1530 # Work hard to stuff the correct filename in the exception
1525 try:
1531 try:
1526 msg, (dummy_filename, lineno, offset, line) = value
1532 msg, (dummy_filename, lineno, offset, line) = value
1527 except:
1533 except:
1528 # Not the format we expect; leave it alone
1534 # Not the format we expect; leave it alone
1529 pass
1535 pass
1530 else:
1536 else:
1531 # Stuff in the right filename
1537 # Stuff in the right filename
1532 try:
1538 try:
1533 # Assume SyntaxError is a class exception
1539 # Assume SyntaxError is a class exception
1534 value = SyntaxError(msg, (filename, lineno, offset, line))
1540 value = SyntaxError(msg, (filename, lineno, offset, line))
1535 except:
1541 except:
1536 # If that failed, assume SyntaxError is a string
1542 # If that failed, assume SyntaxError is a string
1537 value = msg, (filename, lineno, offset, line)
1543 value = msg, (filename, lineno, offset, line)
1538 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1544 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1539 self._showtraceback(etype, value, stb)
1545 self._showtraceback(etype, value, stb)
1540
1546
1541 #-------------------------------------------------------------------------
1547 #-------------------------------------------------------------------------
1542 # Things related to readline
1548 # Things related to readline
1543 #-------------------------------------------------------------------------
1549 #-------------------------------------------------------------------------
1544
1550
1545 def init_readline(self):
1551 def init_readline(self):
1546 """Command history completion/saving/reloading."""
1552 """Command history completion/saving/reloading."""
1547
1553
1548 if self.readline_use:
1554 if self.readline_use:
1549 import IPython.utils.rlineimpl as readline
1555 import IPython.utils.rlineimpl as readline
1550
1556
1551 self.rl_next_input = None
1557 self.rl_next_input = None
1552 self.rl_do_indent = False
1558 self.rl_do_indent = False
1553
1559
1554 if not self.readline_use or not readline.have_readline:
1560 if not self.readline_use or not readline.have_readline:
1555 self.has_readline = False
1561 self.has_readline = False
1556 self.readline = None
1562 self.readline = None
1557 # Set a number of methods that depend on readline to be no-op
1563 # Set a number of methods that depend on readline to be no-op
1558 self.savehist = no_op
1564 self.savehist = no_op
1559 self.reloadhist = no_op
1565 self.reloadhist = no_op
1560 self.set_readline_completer = no_op
1566 self.set_readline_completer = no_op
1561 self.set_custom_completer = no_op
1567 self.set_custom_completer = no_op
1562 self.set_completer_frame = no_op
1568 self.set_completer_frame = no_op
1563 warn('Readline services not available or not loaded.')
1569 warn('Readline services not available or not loaded.')
1564 else:
1570 else:
1565 self.has_readline = True
1571 self.has_readline = True
1566 self.readline = readline
1572 self.readline = readline
1567 sys.modules['readline'] = readline
1573 sys.modules['readline'] = readline
1568
1574
1569 # Platform-specific configuration
1575 # Platform-specific configuration
1570 if os.name == 'nt':
1576 if os.name == 'nt':
1571 # FIXME - check with Frederick to see if we can harmonize
1577 # FIXME - check with Frederick to see if we can harmonize
1572 # naming conventions with pyreadline to avoid this
1578 # naming conventions with pyreadline to avoid this
1573 # platform-dependent check
1579 # platform-dependent check
1574 self.readline_startup_hook = readline.set_pre_input_hook
1580 self.readline_startup_hook = readline.set_pre_input_hook
1575 else:
1581 else:
1576 self.readline_startup_hook = readline.set_startup_hook
1582 self.readline_startup_hook = readline.set_startup_hook
1577
1583
1578 # Load user's initrc file (readline config)
1584 # Load user's initrc file (readline config)
1579 # Or if libedit is used, load editrc.
1585 # Or if libedit is used, load editrc.
1580 inputrc_name = os.environ.get('INPUTRC')
1586 inputrc_name = os.environ.get('INPUTRC')
1581 if inputrc_name is None:
1587 if inputrc_name is None:
1582 home_dir = get_home_dir()
1588 home_dir = get_home_dir()
1583 if home_dir is not None:
1589 if home_dir is not None:
1584 inputrc_name = '.inputrc'
1590 inputrc_name = '.inputrc'
1585 if readline.uses_libedit:
1591 if readline.uses_libedit:
1586 inputrc_name = '.editrc'
1592 inputrc_name = '.editrc'
1587 inputrc_name = os.path.join(home_dir, inputrc_name)
1593 inputrc_name = os.path.join(home_dir, inputrc_name)
1588 if os.path.isfile(inputrc_name):
1594 if os.path.isfile(inputrc_name):
1589 try:
1595 try:
1590 readline.read_init_file(inputrc_name)
1596 readline.read_init_file(inputrc_name)
1591 except:
1597 except:
1592 warn('Problems reading readline initialization file <%s>'
1598 warn('Problems reading readline initialization file <%s>'
1593 % inputrc_name)
1599 % inputrc_name)
1594
1600
1595 # Configure readline according to user's prefs
1601 # Configure readline according to user's prefs
1596 # This is only done if GNU readline is being used. If libedit
1602 # This is only done if GNU readline is being used. If libedit
1597 # is being used (as on Leopard) the readline config is
1603 # is being used (as on Leopard) the readline config is
1598 # not run as the syntax for libedit is different.
1604 # not run as the syntax for libedit is different.
1599 if not readline.uses_libedit:
1605 if not readline.uses_libedit:
1600 for rlcommand in self.readline_parse_and_bind:
1606 for rlcommand in self.readline_parse_and_bind:
1601 #print "loading rl:",rlcommand # dbg
1607 #print "loading rl:",rlcommand # dbg
1602 readline.parse_and_bind(rlcommand)
1608 readline.parse_and_bind(rlcommand)
1603
1609
1604 # Remove some chars from the delimiters list. If we encounter
1610 # Remove some chars from the delimiters list. If we encounter
1605 # unicode chars, discard them.
1611 # unicode chars, discard them.
1606 delims = readline.get_completer_delims().encode("ascii", "ignore")
1612 delims = readline.get_completer_delims().encode("ascii", "ignore")
1607 delims = delims.translate(string._idmap,
1613 delims = delims.translate(string._idmap,
1608 self.readline_remove_delims)
1614 self.readline_remove_delims)
1609 delims = delims.replace(ESC_MAGIC, '')
1615 delims = delims.replace(ESC_MAGIC, '')
1610 readline.set_completer_delims(delims)
1616 readline.set_completer_delims(delims)
1611 # otherwise we end up with a monster history after a while:
1617 # otherwise we end up with a monster history after a while:
1612 readline.set_history_length(1000)
1618 readline.set_history_length(1000)
1613 try:
1619 try:
1614 #print '*** Reading readline history' # dbg
1620 #print '*** Reading readline history' # dbg
1615 readline.read_history_file(self.histfile)
1621 readline.read_history_file(self.histfile)
1616 except IOError:
1622 except IOError:
1617 pass # It doesn't exist yet.
1623 pass # It doesn't exist yet.
1618
1624
1619 # If we have readline, we want our history saved upon ipython
1625 # If we have readline, we want our history saved upon ipython
1620 # exiting.
1626 # exiting.
1621 atexit.register(self.savehist)
1627 atexit.register(self.savehist)
1622
1628
1623 # Configure auto-indent for all platforms
1629 # Configure auto-indent for all platforms
1624 self.set_autoindent(self.autoindent)
1630 self.set_autoindent(self.autoindent)
1625
1631
1626 def set_next_input(self, s):
1632 def set_next_input(self, s):
1627 """ Sets the 'default' input string for the next command line.
1633 """ Sets the 'default' input string for the next command line.
1628
1634
1629 Requires readline.
1635 Requires readline.
1630
1636
1631 Example:
1637 Example:
1632
1638
1633 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1639 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1634 [D:\ipython]|2> Hello Word_ # cursor is here
1640 [D:\ipython]|2> Hello Word_ # cursor is here
1635 """
1641 """
1636
1642
1637 self.rl_next_input = s
1643 self.rl_next_input = s
1638
1644
1639 # Maybe move this to the terminal subclass?
1645 # Maybe move this to the terminal subclass?
1640 def pre_readline(self):
1646 def pre_readline(self):
1641 """readline hook to be used at the start of each line.
1647 """readline hook to be used at the start of each line.
1642
1648
1643 Currently it handles auto-indent only."""
1649 Currently it handles auto-indent only."""
1644
1650
1645 if self.rl_do_indent:
1651 if self.rl_do_indent:
1646 self.readline.insert_text(self._indent_current_str())
1652 self.readline.insert_text(self._indent_current_str())
1647 if self.rl_next_input is not None:
1653 if self.rl_next_input is not None:
1648 self.readline.insert_text(self.rl_next_input)
1654 self.readline.insert_text(self.rl_next_input)
1649 self.rl_next_input = None
1655 self.rl_next_input = None
1650
1656
1651 def _indent_current_str(self):
1657 def _indent_current_str(self):
1652 """return the current level of indentation as a string"""
1658 """return the current level of indentation as a string"""
1653 return self.indent_current_nsp * ' '
1659 return self.indent_current_nsp * ' '
1654
1660
1655 #-------------------------------------------------------------------------
1661 #-------------------------------------------------------------------------
1656 # Things related to text completion
1662 # Things related to text completion
1657 #-------------------------------------------------------------------------
1663 #-------------------------------------------------------------------------
1658
1664
1659 def init_completer(self):
1665 def init_completer(self):
1660 """Initialize the completion machinery.
1666 """Initialize the completion machinery.
1661
1667
1662 This creates completion machinery that can be used by client code,
1668 This creates completion machinery that can be used by client code,
1663 either interactively in-process (typically triggered by the readline
1669 either interactively in-process (typically triggered by the readline
1664 library), programatically (such as in test suites) or out-of-prcess
1670 library), programatically (such as in test suites) or out-of-prcess
1665 (typically over the network by remote frontends).
1671 (typically over the network by remote frontends).
1666 """
1672 """
1667 from IPython.core.completer import IPCompleter
1673 from IPython.core.completer import IPCompleter
1668 from IPython.core.completerlib import (module_completer,
1674 from IPython.core.completerlib import (module_completer,
1669 magic_run_completer, cd_completer)
1675 magic_run_completer, cd_completer)
1670
1676
1671 self.Completer = IPCompleter(self,
1677 self.Completer = IPCompleter(self,
1672 self.user_ns,
1678 self.user_ns,
1673 self.user_global_ns,
1679 self.user_global_ns,
1674 self.readline_omit__names,
1680 self.readline_omit__names,
1675 self.alias_manager.alias_table,
1681 self.alias_manager.alias_table,
1676 self.has_readline)
1682 self.has_readline)
1677
1683
1678 # Add custom completers to the basic ones built into IPCompleter
1684 # Add custom completers to the basic ones built into IPCompleter
1679 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1685 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1680 self.strdispatchers['complete_command'] = sdisp
1686 self.strdispatchers['complete_command'] = sdisp
1681 self.Completer.custom_completers = sdisp
1687 self.Completer.custom_completers = sdisp
1682
1688
1683 self.set_hook('complete_command', module_completer, str_key = 'import')
1689 self.set_hook('complete_command', module_completer, str_key = 'import')
1684 self.set_hook('complete_command', module_completer, str_key = 'from')
1690 self.set_hook('complete_command', module_completer, str_key = 'from')
1685 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1691 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1686 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1692 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1687
1693
1688 # Only configure readline if we truly are using readline. IPython can
1694 # Only configure readline if we truly are using readline. IPython can
1689 # do tab-completion over the network, in GUIs, etc, where readline
1695 # do tab-completion over the network, in GUIs, etc, where readline
1690 # itself may be absent
1696 # itself may be absent
1691 if self.has_readline:
1697 if self.has_readline:
1692 self.set_readline_completer()
1698 self.set_readline_completer()
1693
1699
1694 def complete(self, text, line=None, cursor_pos=None):
1700 def complete(self, text, line=None, cursor_pos=None):
1695 """Return the completed text and a list of completions.
1701 """Return the completed text and a list of completions.
1696
1702
1697 Parameters
1703 Parameters
1698 ----------
1704 ----------
1699
1705
1700 text : string
1706 text : string
1701 A string of text to be completed on. It can be given as empty and
1707 A string of text to be completed on. It can be given as empty and
1702 instead a line/position pair are given. In this case, the
1708 instead a line/position pair are given. In this case, the
1703 completer itself will split the line like readline does.
1709 completer itself will split the line like readline does.
1704
1710
1705 line : string, optional
1711 line : string, optional
1706 The complete line that text is part of.
1712 The complete line that text is part of.
1707
1713
1708 cursor_pos : int, optional
1714 cursor_pos : int, optional
1709 The position of the cursor on the input line.
1715 The position of the cursor on the input line.
1710
1716
1711 Returns
1717 Returns
1712 -------
1718 -------
1713 text : string
1719 text : string
1714 The actual text that was completed.
1720 The actual text that was completed.
1715
1721
1716 matches : list
1722 matches : list
1717 A sorted list with all possible completions.
1723 A sorted list with all possible completions.
1718
1724
1719 The optional arguments allow the completion to take more context into
1725 The optional arguments allow the completion to take more context into
1720 account, and are part of the low-level completion API.
1726 account, and are part of the low-level completion API.
1721
1727
1722 This is a wrapper around the completion mechanism, similar to what
1728 This is a wrapper around the completion mechanism, similar to what
1723 readline does at the command line when the TAB key is hit. By
1729 readline does at the command line when the TAB key is hit. By
1724 exposing it as a method, it can be used by other non-readline
1730 exposing it as a method, it can be used by other non-readline
1725 environments (such as GUIs) for text completion.
1731 environments (such as GUIs) for text completion.
1726
1732
1727 Simple usage example:
1733 Simple usage example:
1728
1734
1729 In [1]: x = 'hello'
1735 In [1]: x = 'hello'
1730
1736
1731 In [2]: _ip.complete('x.l')
1737 In [2]: _ip.complete('x.l')
1732 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1738 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1733 """
1739 """
1734
1740
1735 # Inject names into __builtin__ so we can complete on the added names.
1741 # Inject names into __builtin__ so we can complete on the added names.
1736 with self.builtin_trap:
1742 with self.builtin_trap:
1737 return self.Completer.complete(text, line, cursor_pos)
1743 return self.Completer.complete(text, line, cursor_pos)
1738
1744
1739 def set_custom_completer(self, completer, pos=0):
1745 def set_custom_completer(self, completer, pos=0):
1740 """Adds a new custom completer function.
1746 """Adds a new custom completer function.
1741
1747
1742 The position argument (defaults to 0) is the index in the completers
1748 The position argument (defaults to 0) is the index in the completers
1743 list where you want the completer to be inserted."""
1749 list where you want the completer to be inserted."""
1744
1750
1745 newcomp = new.instancemethod(completer,self.Completer,
1751 newcomp = new.instancemethod(completer,self.Completer,
1746 self.Completer.__class__)
1752 self.Completer.__class__)
1747 self.Completer.matchers.insert(pos,newcomp)
1753 self.Completer.matchers.insert(pos,newcomp)
1748
1754
1749 def set_readline_completer(self):
1755 def set_readline_completer(self):
1750 """Reset readline's completer to be our own."""
1756 """Reset readline's completer to be our own."""
1751 self.readline.set_completer(self.Completer.rlcomplete)
1757 self.readline.set_completer(self.Completer.rlcomplete)
1752
1758
1753 def set_completer_frame(self, frame=None):
1759 def set_completer_frame(self, frame=None):
1754 """Set the frame of the completer."""
1760 """Set the frame of the completer."""
1755 if frame:
1761 if frame:
1756 self.Completer.namespace = frame.f_locals
1762 self.Completer.namespace = frame.f_locals
1757 self.Completer.global_namespace = frame.f_globals
1763 self.Completer.global_namespace = frame.f_globals
1758 else:
1764 else:
1759 self.Completer.namespace = self.user_ns
1765 self.Completer.namespace = self.user_ns
1760 self.Completer.global_namespace = self.user_global_ns
1766 self.Completer.global_namespace = self.user_global_ns
1761
1767
1762 #-------------------------------------------------------------------------
1768 #-------------------------------------------------------------------------
1763 # Things related to magics
1769 # Things related to magics
1764 #-------------------------------------------------------------------------
1770 #-------------------------------------------------------------------------
1765
1771
1766 def init_magics(self):
1772 def init_magics(self):
1767 # FIXME: Move the color initialization to the DisplayHook, which
1773 # FIXME: Move the color initialization to the DisplayHook, which
1768 # should be split into a prompt manager and displayhook. We probably
1774 # should be split into a prompt manager and displayhook. We probably
1769 # even need a centralize colors management object.
1775 # even need a centralize colors management object.
1770 self.magic_colors(self.colors)
1776 self.magic_colors(self.colors)
1771 # History was moved to a separate module
1777 # History was moved to a separate module
1772 from . import history
1778 from . import history
1773 history.init_ipython(self)
1779 history.init_ipython(self)
1774
1780
1775 def magic(self,arg_s):
1781 def magic(self,arg_s):
1776 """Call a magic function by name.
1782 """Call a magic function by name.
1777
1783
1778 Input: a string containing the name of the magic function to call and
1784 Input: a string containing the name of the magic function to call and
1779 any additional arguments to be passed to the magic.
1785 any additional arguments to be passed to the magic.
1780
1786
1781 magic('name -opt foo bar') is equivalent to typing at the ipython
1787 magic('name -opt foo bar') is equivalent to typing at the ipython
1782 prompt:
1788 prompt:
1783
1789
1784 In[1]: %name -opt foo bar
1790 In[1]: %name -opt foo bar
1785
1791
1786 To call a magic without arguments, simply use magic('name').
1792 To call a magic without arguments, simply use magic('name').
1787
1793
1788 This provides a proper Python function to call IPython's magics in any
1794 This provides a proper Python function to call IPython's magics in any
1789 valid Python code you can type at the interpreter, including loops and
1795 valid Python code you can type at the interpreter, including loops and
1790 compound statements.
1796 compound statements.
1791 """
1797 """
1792 args = arg_s.split(' ',1)
1798 args = arg_s.split(' ',1)
1793 magic_name = args[0]
1799 magic_name = args[0]
1794 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1800 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1795
1801
1796 try:
1802 try:
1797 magic_args = args[1]
1803 magic_args = args[1]
1798 except IndexError:
1804 except IndexError:
1799 magic_args = ''
1805 magic_args = ''
1800 fn = getattr(self,'magic_'+magic_name,None)
1806 fn = getattr(self,'magic_'+magic_name,None)
1801 if fn is None:
1807 if fn is None:
1802 error("Magic function `%s` not found." % magic_name)
1808 error("Magic function `%s` not found." % magic_name)
1803 else:
1809 else:
1804 magic_args = self.var_expand(magic_args,1)
1810 magic_args = self.var_expand(magic_args,1)
1805 with nested(self.builtin_trap,):
1811 with nested(self.builtin_trap,):
1806 result = fn(magic_args)
1812 result = fn(magic_args)
1807 return result
1813 return result
1808
1814
1809 def define_magic(self, magicname, func):
1815 def define_magic(self, magicname, func):
1810 """Expose own function as magic function for ipython
1816 """Expose own function as magic function for ipython
1811
1817
1812 def foo_impl(self,parameter_s=''):
1818 def foo_impl(self,parameter_s=''):
1813 'My very own magic!. (Use docstrings, IPython reads them).'
1819 'My very own magic!. (Use docstrings, IPython reads them).'
1814 print 'Magic function. Passed parameter is between < >:'
1820 print 'Magic function. Passed parameter is between < >:'
1815 print '<%s>' % parameter_s
1821 print '<%s>' % parameter_s
1816 print 'The self object is:',self
1822 print 'The self object is:',self
1817
1823
1818 self.define_magic('foo',foo_impl)
1824 self.define_magic('foo',foo_impl)
1819 """
1825 """
1820
1826
1821 import new
1827 import new
1822 im = new.instancemethod(func,self, self.__class__)
1828 im = new.instancemethod(func,self, self.__class__)
1823 old = getattr(self, "magic_" + magicname, None)
1829 old = getattr(self, "magic_" + magicname, None)
1824 setattr(self, "magic_" + magicname, im)
1830 setattr(self, "magic_" + magicname, im)
1825 return old
1831 return old
1826
1832
1827 #-------------------------------------------------------------------------
1833 #-------------------------------------------------------------------------
1828 # Things related to macros
1834 # Things related to macros
1829 #-------------------------------------------------------------------------
1835 #-------------------------------------------------------------------------
1830
1836
1831 def define_macro(self, name, themacro):
1837 def define_macro(self, name, themacro):
1832 """Define a new macro
1838 """Define a new macro
1833
1839
1834 Parameters
1840 Parameters
1835 ----------
1841 ----------
1836 name : str
1842 name : str
1837 The name of the macro.
1843 The name of the macro.
1838 themacro : str or Macro
1844 themacro : str or Macro
1839 The action to do upon invoking the macro. If a string, a new
1845 The action to do upon invoking the macro. If a string, a new
1840 Macro object is created by passing the string to it.
1846 Macro object is created by passing the string to it.
1841 """
1847 """
1842
1848
1843 from IPython.core import macro
1849 from IPython.core import macro
1844
1850
1845 if isinstance(themacro, basestring):
1851 if isinstance(themacro, basestring):
1846 themacro = macro.Macro(themacro)
1852 themacro = macro.Macro(themacro)
1847 if not isinstance(themacro, macro.Macro):
1853 if not isinstance(themacro, macro.Macro):
1848 raise ValueError('A macro must be a string or a Macro instance.')
1854 raise ValueError('A macro must be a string or a Macro instance.')
1849 self.user_ns[name] = themacro
1855 self.user_ns[name] = themacro
1850
1856
1851 #-------------------------------------------------------------------------
1857 #-------------------------------------------------------------------------
1852 # Things related to the running of system commands
1858 # Things related to the running of system commands
1853 #-------------------------------------------------------------------------
1859 #-------------------------------------------------------------------------
1854
1860
1855 def system(self, cmd):
1861 def system(self, cmd):
1856 """Call the given cmd in a subprocess.
1862 """Call the given cmd in a subprocess.
1857
1863
1858 Parameters
1864 Parameters
1859 ----------
1865 ----------
1860 cmd : str
1866 cmd : str
1861 Command to execute (can not end in '&', as bacground processes are
1867 Command to execute (can not end in '&', as bacground processes are
1862 not supported.
1868 not supported.
1863 """
1869 """
1864 # We do not support backgrounding processes because we either use
1870 # We do not support backgrounding processes because we either use
1865 # pexpect or pipes to read from. Users can always just call
1871 # pexpect or pipes to read from. Users can always just call
1866 # os.system() if they really want a background process.
1872 # os.system() if they really want a background process.
1867 if cmd.endswith('&'):
1873 if cmd.endswith('&'):
1868 raise OSError("Background processes not supported.")
1874 raise OSError("Background processes not supported.")
1869
1875
1870 return system(self.var_expand(cmd, depth=2))
1876 return system(self.var_expand(cmd, depth=2))
1871
1877
1872 def getoutput(self, cmd, split=True):
1878 def getoutput(self, cmd, split=True):
1873 """Get output (possibly including stderr) from a subprocess.
1879 """Get output (possibly including stderr) from a subprocess.
1874
1880
1875 Parameters
1881 Parameters
1876 ----------
1882 ----------
1877 cmd : str
1883 cmd : str
1878 Command to execute (can not end in '&', as background processes are
1884 Command to execute (can not end in '&', as background processes are
1879 not supported.
1885 not supported.
1880 split : bool, optional
1886 split : bool, optional
1881
1887
1882 If True, split the output into an IPython SList. Otherwise, an
1888 If True, split the output into an IPython SList. Otherwise, an
1883 IPython LSString is returned. These are objects similar to normal
1889 IPython LSString is returned. These are objects similar to normal
1884 lists and strings, with a few convenience attributes for easier
1890 lists and strings, with a few convenience attributes for easier
1885 manipulation of line-based output. You can use '?' on them for
1891 manipulation of line-based output. You can use '?' on them for
1886 details.
1892 details.
1887 """
1893 """
1888 if cmd.endswith('&'):
1894 if cmd.endswith('&'):
1889 raise OSError("Background processes not supported.")
1895 raise OSError("Background processes not supported.")
1890 out = getoutput(self.var_expand(cmd, depth=2))
1896 out = getoutput(self.var_expand(cmd, depth=2))
1891 if split:
1897 if split:
1892 out = SList(out.splitlines())
1898 out = SList(out.splitlines())
1893 else:
1899 else:
1894 out = LSString(out)
1900 out = LSString(out)
1895 return out
1901 return out
1896
1902
1897 #-------------------------------------------------------------------------
1903 #-------------------------------------------------------------------------
1898 # Things related to aliases
1904 # Things related to aliases
1899 #-------------------------------------------------------------------------
1905 #-------------------------------------------------------------------------
1900
1906
1901 def init_alias(self):
1907 def init_alias(self):
1902 self.alias_manager = AliasManager(shell=self, config=self.config)
1908 self.alias_manager = AliasManager(shell=self, config=self.config)
1903 self.ns_table['alias'] = self.alias_manager.alias_table,
1909 self.ns_table['alias'] = self.alias_manager.alias_table,
1904
1910
1905 #-------------------------------------------------------------------------
1911 #-------------------------------------------------------------------------
1906 # Things related to extensions and plugins
1912 # Things related to extensions and plugins
1907 #-------------------------------------------------------------------------
1913 #-------------------------------------------------------------------------
1908
1914
1909 def init_extension_manager(self):
1915 def init_extension_manager(self):
1910 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1916 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1911
1917
1912 def init_plugin_manager(self):
1918 def init_plugin_manager(self):
1913 self.plugin_manager = PluginManager(config=self.config)
1919 self.plugin_manager = PluginManager(config=self.config)
1914
1920
1915 #-------------------------------------------------------------------------
1921 #-------------------------------------------------------------------------
1916 # Things related to payloads
1922 # Things related to payloads
1917 #-------------------------------------------------------------------------
1923 #-------------------------------------------------------------------------
1918
1924
1919 def init_payload(self):
1925 def init_payload(self):
1920 self.payload_manager = PayloadManager(config=self.config)
1926 self.payload_manager = PayloadManager(config=self.config)
1921
1927
1922 #-------------------------------------------------------------------------
1928 #-------------------------------------------------------------------------
1923 # Things related to the prefilter
1929 # Things related to the prefilter
1924 #-------------------------------------------------------------------------
1930 #-------------------------------------------------------------------------
1925
1931
1926 def init_prefilter(self):
1932 def init_prefilter(self):
1927 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1933 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1928 # Ultimately this will be refactored in the new interpreter code, but
1934 # Ultimately this will be refactored in the new interpreter code, but
1929 # for now, we should expose the main prefilter method (there's legacy
1935 # for now, we should expose the main prefilter method (there's legacy
1930 # code out there that may rely on this).
1936 # code out there that may rely on this).
1931 self.prefilter = self.prefilter_manager.prefilter_lines
1937 self.prefilter = self.prefilter_manager.prefilter_lines
1932
1938
1933
1939
1934 def auto_rewrite_input(self, cmd):
1940 def auto_rewrite_input(self, cmd):
1935 """Print to the screen the rewritten form of the user's command.
1941 """Print to the screen the rewritten form of the user's command.
1936
1942
1937 This shows visual feedback by rewriting input lines that cause
1943 This shows visual feedback by rewriting input lines that cause
1938 automatic calling to kick in, like::
1944 automatic calling to kick in, like::
1939
1945
1940 /f x
1946 /f x
1941
1947
1942 into::
1948 into::
1943
1949
1944 ------> f(x)
1950 ------> f(x)
1945
1951
1946 after the user's input prompt. This helps the user understand that the
1952 after the user's input prompt. This helps the user understand that the
1947 input line was transformed automatically by IPython.
1953 input line was transformed automatically by IPython.
1948 """
1954 """
1949 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1955 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1950
1956
1951 try:
1957 try:
1952 # plain ascii works better w/ pyreadline, on some machines, so
1958 # plain ascii works better w/ pyreadline, on some machines, so
1953 # we use it and only print uncolored rewrite if we have unicode
1959 # we use it and only print uncolored rewrite if we have unicode
1954 rw = str(rw)
1960 rw = str(rw)
1955 print >> IPython.utils.io.Term.cout, rw
1961 print >> IPython.utils.io.Term.cout, rw
1956 except UnicodeEncodeError:
1962 except UnicodeEncodeError:
1957 print "------> " + cmd
1963 print "------> " + cmd
1958
1964
1959 #-------------------------------------------------------------------------
1965 #-------------------------------------------------------------------------
1960 # Things related to extracting values/expressions from kernel and user_ns
1966 # Things related to extracting values/expressions from kernel and user_ns
1961 #-------------------------------------------------------------------------
1967 #-------------------------------------------------------------------------
1962
1968
1963 def _simple_error(self):
1969 def _simple_error(self):
1964 etype, value = sys.exc_info()[:2]
1970 etype, value = sys.exc_info()[:2]
1965 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1971 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1966
1972
1967 def user_variables(self, names):
1973 def user_variables(self, names):
1968 """Get a list of variable names from the user's namespace.
1974 """Get a list of variable names from the user's namespace.
1969
1975
1970 Parameters
1976 Parameters
1971 ----------
1977 ----------
1972 names : list of strings
1978 names : list of strings
1973 A list of names of variables to be read from the user namespace.
1979 A list of names of variables to be read from the user namespace.
1974
1980
1975 Returns
1981 Returns
1976 -------
1982 -------
1977 A dict, keyed by the input names and with the repr() of each value.
1983 A dict, keyed by the input names and with the repr() of each value.
1978 """
1984 """
1979 out = {}
1985 out = {}
1980 user_ns = self.user_ns
1986 user_ns = self.user_ns
1981 for varname in names:
1987 for varname in names:
1982 try:
1988 try:
1983 value = repr(user_ns[varname])
1989 value = repr(user_ns[varname])
1984 except:
1990 except:
1985 value = self._simple_error()
1991 value = self._simple_error()
1986 out[varname] = value
1992 out[varname] = value
1987 return out
1993 return out
1988
1994
1989 def user_expressions(self, expressions):
1995 def user_expressions(self, expressions):
1990 """Evaluate a dict of expressions in the user's namespace.
1996 """Evaluate a dict of expressions in the user's namespace.
1991
1997
1992 Parameters
1998 Parameters
1993 ----------
1999 ----------
1994 expressions : dict
2000 expressions : dict
1995 A dict with string keys and string values. The expression values
2001 A dict with string keys and string values. The expression values
1996 should be valid Python expressions, each of which will be evaluated
2002 should be valid Python expressions, each of which will be evaluated
1997 in the user namespace.
2003 in the user namespace.
1998
2004
1999 Returns
2005 Returns
2000 -------
2006 -------
2001 A dict, keyed like the input expressions dict, with the repr() of each
2007 A dict, keyed like the input expressions dict, with the repr() of each
2002 value.
2008 value.
2003 """
2009 """
2004 out = {}
2010 out = {}
2005 user_ns = self.user_ns
2011 user_ns = self.user_ns
2006 global_ns = self.user_global_ns
2012 global_ns = self.user_global_ns
2007 for key, expr in expressions.iteritems():
2013 for key, expr in expressions.iteritems():
2008 try:
2014 try:
2009 value = repr(eval(expr, global_ns, user_ns))
2015 value = repr(eval(expr, global_ns, user_ns))
2010 except:
2016 except:
2011 value = self._simple_error()
2017 value = self._simple_error()
2012 out[key] = value
2018 out[key] = value
2013 return out
2019 return out
2014
2020
2015 #-------------------------------------------------------------------------
2021 #-------------------------------------------------------------------------
2016 # Things related to the running of code
2022 # Things related to the running of code
2017 #-------------------------------------------------------------------------
2023 #-------------------------------------------------------------------------
2018
2024
2019 def ex(self, cmd):
2025 def ex(self, cmd):
2020 """Execute a normal python statement in user namespace."""
2026 """Execute a normal python statement in user namespace."""
2021 with nested(self.builtin_trap,):
2027 with nested(self.builtin_trap,):
2022 exec cmd in self.user_global_ns, self.user_ns
2028 exec cmd in self.user_global_ns, self.user_ns
2023
2029
2024 def ev(self, expr):
2030 def ev(self, expr):
2025 """Evaluate python expression expr in user namespace.
2031 """Evaluate python expression expr in user namespace.
2026
2032
2027 Returns the result of evaluation
2033 Returns the result of evaluation
2028 """
2034 """
2029 with nested(self.builtin_trap,):
2035 with nested(self.builtin_trap,):
2030 return eval(expr, self.user_global_ns, self.user_ns)
2036 return eval(expr, self.user_global_ns, self.user_ns)
2031
2037
2032 def safe_execfile(self, fname, *where, **kw):
2038 def safe_execfile(self, fname, *where, **kw):
2033 """A safe version of the builtin execfile().
2039 """A safe version of the builtin execfile().
2034
2040
2035 This version will never throw an exception, but instead print
2041 This version will never throw an exception, but instead print
2036 helpful error messages to the screen. This only works on pure
2042 helpful error messages to the screen. This only works on pure
2037 Python files with the .py extension.
2043 Python files with the .py extension.
2038
2044
2039 Parameters
2045 Parameters
2040 ----------
2046 ----------
2041 fname : string
2047 fname : string
2042 The name of the file to be executed.
2048 The name of the file to be executed.
2043 where : tuple
2049 where : tuple
2044 One or two namespaces, passed to execfile() as (globals,locals).
2050 One or two namespaces, passed to execfile() as (globals,locals).
2045 If only one is given, it is passed as both.
2051 If only one is given, it is passed as both.
2046 exit_ignore : bool (False)
2052 exit_ignore : bool (False)
2047 If True, then silence SystemExit for non-zero status (it is always
2053 If True, then silence SystemExit for non-zero status (it is always
2048 silenced for zero status, as it is so common).
2054 silenced for zero status, as it is so common).
2049 """
2055 """
2050 kw.setdefault('exit_ignore', False)
2056 kw.setdefault('exit_ignore', False)
2051
2057
2052 fname = os.path.abspath(os.path.expanduser(fname))
2058 fname = os.path.abspath(os.path.expanduser(fname))
2053
2059
2054 # Make sure we have a .py file
2060 # Make sure we have a .py file
2055 if not fname.endswith('.py'):
2061 if not fname.endswith('.py'):
2056 warn('File must end with .py to be run using execfile: <%s>' % fname)
2062 warn('File must end with .py to be run using execfile: <%s>' % fname)
2057
2063
2058 # Make sure we can open the file
2064 # Make sure we can open the file
2059 try:
2065 try:
2060 with open(fname) as thefile:
2066 with open(fname) as thefile:
2061 pass
2067 pass
2062 except:
2068 except:
2063 warn('Could not open file <%s> for safe execution.' % fname)
2069 warn('Could not open file <%s> for safe execution.' % fname)
2064 return
2070 return
2065
2071
2066 # Find things also in current directory. This is needed to mimic the
2072 # Find things also in current directory. This is needed to mimic the
2067 # behavior of running a script from the system command line, where
2073 # behavior of running a script from the system command line, where
2068 # Python inserts the script's directory into sys.path
2074 # Python inserts the script's directory into sys.path
2069 dname = os.path.dirname(fname)
2075 dname = os.path.dirname(fname)
2070
2076
2071 with prepended_to_syspath(dname):
2077 with prepended_to_syspath(dname):
2072 try:
2078 try:
2073 execfile(fname,*where)
2079 execfile(fname,*where)
2074 except SystemExit, status:
2080 except SystemExit, status:
2075 # If the call was made with 0 or None exit status (sys.exit(0)
2081 # If the call was made with 0 or None exit status (sys.exit(0)
2076 # or sys.exit() ), don't bother showing a traceback, as both of
2082 # or sys.exit() ), don't bother showing a traceback, as both of
2077 # these are considered normal by the OS:
2083 # these are considered normal by the OS:
2078 # > python -c'import sys;sys.exit(0)'; echo $?
2084 # > python -c'import sys;sys.exit(0)'; echo $?
2079 # 0
2085 # 0
2080 # > python -c'import sys;sys.exit()'; echo $?
2086 # > python -c'import sys;sys.exit()'; echo $?
2081 # 0
2087 # 0
2082 # For other exit status, we show the exception unless
2088 # For other exit status, we show the exception unless
2083 # explicitly silenced, but only in short form.
2089 # explicitly silenced, but only in short form.
2084 if status.code not in (0, None) and not kw['exit_ignore']:
2090 if status.code not in (0, None) and not kw['exit_ignore']:
2085 self.showtraceback(exception_only=True)
2091 self.showtraceback(exception_only=True)
2086 except:
2092 except:
2087 self.showtraceback()
2093 self.showtraceback()
2088
2094
2089 def safe_execfile_ipy(self, fname):
2095 def safe_execfile_ipy(self, fname):
2090 """Like safe_execfile, but for .ipy files with IPython syntax.
2096 """Like safe_execfile, but for .ipy files with IPython syntax.
2091
2097
2092 Parameters
2098 Parameters
2093 ----------
2099 ----------
2094 fname : str
2100 fname : str
2095 The name of the file to execute. The filename must have a
2101 The name of the file to execute. The filename must have a
2096 .ipy extension.
2102 .ipy extension.
2097 """
2103 """
2098 fname = os.path.abspath(os.path.expanduser(fname))
2104 fname = os.path.abspath(os.path.expanduser(fname))
2099
2105
2100 # Make sure we have a .py file
2106 # Make sure we have a .py file
2101 if not fname.endswith('.ipy'):
2107 if not fname.endswith('.ipy'):
2102 warn('File must end with .py to be run using execfile: <%s>' % fname)
2108 warn('File must end with .py to be run using execfile: <%s>' % fname)
2103
2109
2104 # Make sure we can open the file
2110 # Make sure we can open the file
2105 try:
2111 try:
2106 with open(fname) as thefile:
2112 with open(fname) as thefile:
2107 pass
2113 pass
2108 except:
2114 except:
2109 warn('Could not open file <%s> for safe execution.' % fname)
2115 warn('Could not open file <%s> for safe execution.' % fname)
2110 return
2116 return
2111
2117
2112 # Find things also in current directory. This is needed to mimic the
2118 # Find things also in current directory. This is needed to mimic the
2113 # behavior of running a script from the system command line, where
2119 # behavior of running a script from the system command line, where
2114 # Python inserts the script's directory into sys.path
2120 # Python inserts the script's directory into sys.path
2115 dname = os.path.dirname(fname)
2121 dname = os.path.dirname(fname)
2116
2122
2117 with prepended_to_syspath(dname):
2123 with prepended_to_syspath(dname):
2118 try:
2124 try:
2119 with open(fname) as thefile:
2125 with open(fname) as thefile:
2120 script = thefile.read()
2126 script = thefile.read()
2121 # self.runlines currently captures all exceptions
2127 # self.runlines currently captures all exceptions
2122 # raise in user code. It would be nice if there were
2128 # raise in user code. It would be nice if there were
2123 # versions of runlines, execfile that did raise, so
2129 # versions of runlines, execfile that did raise, so
2124 # we could catch the errors.
2130 # we could catch the errors.
2125 self.runlines(script, clean=True)
2131 self.runlines(script, clean=True)
2126 except:
2132 except:
2127 self.showtraceback()
2133 self.showtraceback()
2128 warn('Unknown failure executing file: <%s>' % fname)
2134 warn('Unknown failure executing file: <%s>' % fname)
2129
2135
2130 def run_cell(self, cell):
2136 def run_cell(self, cell):
2131 """Run the contents of an entire multiline 'cell' of code.
2137 """Run the contents of an entire multiline 'cell' of code.
2132
2138
2133 The cell is split into separate blocks which can be executed
2139 The cell is split into separate blocks which can be executed
2134 individually. Then, based on how many blocks there are, they are
2140 individually. Then, based on how many blocks there are, they are
2135 executed as follows:
2141 executed as follows:
2136
2142
2137 - A single block: 'single' mode.
2143 - A single block: 'single' mode.
2138
2144
2139 If there's more than one block, it depends:
2145 If there's more than one block, it depends:
2140
2146
2141 - if the last one is no more than two lines long, run all but the last
2147 - if the last one is no more than two lines long, run all but the last
2142 in 'exec' mode and the very last one in 'single' mode. This makes it
2148 in 'exec' mode and the very last one in 'single' mode. This makes it
2143 easy to type simple expressions at the end to see computed values. -
2149 easy to type simple expressions at the end to see computed values. -
2144 otherwise (last one is also multiline), run all in 'exec' mode
2150 otherwise (last one is also multiline), run all in 'exec' mode
2145
2151
2146 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2152 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2147 results are displayed and output prompts are computed. In 'exec' mode,
2153 results are displayed and output prompts are computed. In 'exec' mode,
2148 no results are displayed unless :func:`print` is called explicitly;
2154 no results are displayed unless :func:`print` is called explicitly;
2149 this mode is more akin to running a script.
2155 this mode is more akin to running a script.
2150
2156
2151 Parameters
2157 Parameters
2152 ----------
2158 ----------
2153 cell : str
2159 cell : str
2154 A single or multiline string.
2160 A single or multiline string.
2155 """
2161 """
2156 #################################################################
2162 #################################################################
2157 # FIXME
2163 # FIXME
2158 # =====
2164 # =====
2159 # This execution logic should stop calling runlines altogether, and
2165 # This execution logic should stop calling runlines altogether, and
2160 # instead we should do what runlines does, in a controlled manner, here
2166 # instead we should do what runlines does, in a controlled manner, here
2161 # (runlines mutates lots of state as it goes calling sub-methods that
2167 # (runlines mutates lots of state as it goes calling sub-methods that
2162 # also mutate state). Basically we should:
2168 # also mutate state). Basically we should:
2163 # - apply dynamic transforms for single-line input (the ones that
2169 # - apply dynamic transforms for single-line input (the ones that
2164 # split_blocks won't apply since they need context).
2170 # split_blocks won't apply since they need context).
2165 # - increment the global execution counter (we need to pull that out
2171 # - increment the global execution counter (we need to pull that out
2166 # from outputcache's control; outputcache should instead read it from
2172 # from outputcache's control; outputcache should instead read it from
2167 # the main object).
2173 # the main object).
2168 # - do any logging of input
2174 # - do any logging of input
2169 # - update histories (raw/translated)
2175 # - update histories (raw/translated)
2170 # - then, call plain runsource (for single blocks, so displayhook is
2176 # - then, call plain runsource (for single blocks, so displayhook is
2171 # triggered) or runcode (for multiline blocks in exec mode).
2177 # triggered) or runcode (for multiline blocks in exec mode).
2172 #
2178 #
2173 # Once this is done, we'll be able to stop using runlines and we'll
2179 # Once this is done, we'll be able to stop using runlines and we'll
2174 # also have a much cleaner separation of logging, input history and
2180 # also have a much cleaner separation of logging, input history and
2175 # output cache management.
2181 # output cache management.
2176 #################################################################
2182 #################################################################
2177
2183
2178 # We need to break up the input into executable blocks that can be run
2184 # We need to break up the input into executable blocks that can be run
2179 # in 'single' mode, to provide comfortable user behavior.
2185 # in 'single' mode, to provide comfortable user behavior.
2180 blocks = self.input_splitter.split_blocks(cell)
2186 blocks = self.input_splitter.split_blocks(cell)
2181
2187
2182 if not blocks:
2188 if not blocks:
2183 return
2189 return
2184
2190
2185 # Store the 'ipython' version of the cell as well, since that's what
2191 # Store the 'ipython' version of the cell as well, since that's what
2186 # needs to go into the translated history and get executed (the
2192 # needs to go into the translated history and get executed (the
2187 # original cell may contain non-python syntax).
2193 # original cell may contain non-python syntax).
2188 ipy_cell = ''.join(blocks)
2194 ipy_cell = ''.join(blocks)
2189
2190 # Single-block input should behave like an interactive prompt
2191 if len(blocks) == 1:
2192 self.runlines(blocks[0])
2193 return
2194
2195
2195 # In multi-block input, if the last block is a simple (one-two lines)
2196 # Each cell is a *single* input, regardless of how many lines it has
2196 # expression, run it in single mode so it produces output. Otherwise
2197 self.execution_count += 1
2197 # just feed the whole thing to runcode.
2198
2198 # This seems like a reasonable usability design.
2199 # Store raw and processed history
2199 last = blocks[-1]
2200 self.input_hist_raw.append(cell)
2200 last_nlines = len(last.splitlines())
2201 self.input_hist.append(ipy_cell)
2201
2202
2202 # Note: below, whenever we call runcode, we must sync history
2203 # All user code execution must happen with our context managers active
2203 # ourselves, because runcode is NOT meant to manage history at all.
2204 with nested(self.builtin_trap, self.display_trap):
2204 if last_nlines < 2:
2205 # Single-block input should behave like an interactive prompt
2205 # Here we consider the cell split between 'body' and 'last', store
2206 if len(blocks) == 1:
2206 # all history and execute 'body', and if successful, then proceed
2207 return self.run_one_block(blocks[0])
2207 # to execute 'last'.
2208
2208
2209 # In multi-block input, if the last block is a simple (one-two
2209 # Raw history must contain the unmodified cell
2210 # lines) expression, run it in single mode so it produces output.
2210 raw_body = '\n'.join(cell.splitlines()[:-last_nlines])+'\n'
2211 # Otherwise just feed the whole thing to runcode. This seems like
2211 self.input_hist_raw.append(raw_body)
2212 # a reasonable usability design.
2212 # Get the main body to run as a cell
2213 last = blocks[-1]
2213 ipy_body = ''.join(blocks[:-1])
2214 last_nlines = len(last.splitlines())
2214 self.input_hist.append(ipy_body)
2215
2215 retcode = self.runcode(ipy_body, post_execute=False)
2216 # Note: below, whenever we call runcode, we must sync history
2216 if retcode==0:
2217 # ourselves, because runcode is NOT meant to manage history at all.
2217 # And the last expression via runlines so it produces output
2218 if last_nlines < 2:
2218 self.runlines(last)
2219 # Here we consider the cell split between 'body' and 'last',
2220 # store all history and execute 'body', and if successful, then
2221 # proceed to execute 'last'.
2222
2223 # Get the main body to run as a cell
2224 ipy_body = ''.join(blocks[:-1])
2225 retcode = self.runcode(ipy_body, post_execute=False)
2226 if retcode==0:
2227 # And the last expression via runlines so it produces output
2228 self.run_one_block(last)
2229 else:
2230 # Run the whole cell as one entity, storing both raw and
2231 # processed input in history
2232 self.runcode(ipy_cell)
2233
2234 def run_one_block(self, block):
2235 """Run a single interactive block.
2236
2237 If the block is single-line, dynamic transformations are applied to it
2238 (like automagics, autocall and alias recognition).
2239 """
2240 if len(block.splitlines()) <= 1:
2241 out = self.run_single_line(block)
2219 else:
2242 else:
2220 # Run the whole cell as one entity, storing both raw and processed
2243 out = self.runcode(block)
2221 # input in history
2244 return out
2222 self.input_hist_raw.append(cell)
2245
2223 self.input_hist.append(ipy_cell)
2246 def run_single_line(self, line):
2224 self.runcode(ipy_cell)
2247 """Run a single-line interactive statement.
2248
2249 This assumes the input has been transformed to IPython syntax by
2250 applying all static transformations (those with an explicit prefix like
2251 % or !), but it will further try to apply the dynamic ones.
2252
2253 It does not update history.
2254 """
2255 tline = self.prefilter_manager.prefilter_line(line)
2256 return self.runsource(tline)
2225
2257
2226 def runlines(self, lines, clean=False):
2258 def runlines(self, lines, clean=False):
2227 """Run a string of one or more lines of source.
2259 """Run a string of one or more lines of source.
2228
2260
2229 This method is capable of running a string containing multiple source
2261 This method is capable of running a string containing multiple source
2230 lines, as if they had been entered at the IPython prompt. Since it
2262 lines, as if they had been entered at the IPython prompt. Since it
2231 exposes IPython's processing machinery, the given strings can contain
2263 exposes IPython's processing machinery, the given strings can contain
2232 magic calls (%magic), special shell access (!cmd), etc.
2264 magic calls (%magic), special shell access (!cmd), etc.
2233 """
2265 """
2234
2266
2235 if isinstance(lines, (list, tuple)):
2267 if isinstance(lines, (list, tuple)):
2236 lines = '\n'.join(lines)
2268 lines = '\n'.join(lines)
2237
2269
2238 if clean:
2270 if clean:
2239 lines = self._cleanup_ipy_script(lines)
2271 lines = self._cleanup_ipy_script(lines)
2240
2272
2241 # We must start with a clean buffer, in case this is run from an
2273 # We must start with a clean buffer, in case this is run from an
2242 # interactive IPython session (via a magic, for example).
2274 # interactive IPython session (via a magic, for example).
2243 self.resetbuffer()
2275 self.resetbuffer()
2244 lines = lines.splitlines()
2276 lines = lines.splitlines()
2245 more = 0
2277 more = 0
2246 with nested(self.builtin_trap, self.display_trap):
2278 with nested(self.builtin_trap, self.display_trap):
2247 for line in lines:
2279 for line in lines:
2248 # skip blank lines so we don't mess up the prompt counter, but
2280 # skip blank lines so we don't mess up the prompt counter, but
2249 # do NOT skip even a blank line if we are in a code block (more
2281 # do NOT skip even a blank line if we are in a code block (more
2250 # is true)
2282 # is true)
2251
2283
2252 if line or more:
2284 if line or more:
2253 # push to raw history, so hist line numbers stay in sync
2285 # push to raw history, so hist line numbers stay in sync
2254 self.input_hist_raw.append(line + '\n')
2286 self.input_hist_raw.append(line + '\n')
2255 prefiltered = self.prefilter_manager.prefilter_lines(line,
2287 prefiltered = self.prefilter_manager.prefilter_lines(line,
2256 more)
2288 more)
2257 more = self.push_line(prefiltered)
2289 more = self.push_line(prefiltered)
2258 # IPython's runsource returns None if there was an error
2290 # IPython's runsource returns None if there was an error
2259 # compiling the code. This allows us to stop processing
2291 # compiling the code. This allows us to stop processing
2260 # right away, so the user gets the error message at the
2292 # right away, so the user gets the error message at the
2261 # right place.
2293 # right place.
2262 if more is None:
2294 if more is None:
2263 break
2295 break
2264 else:
2296 else:
2265 self.input_hist_raw.append("\n")
2297 self.input_hist_raw.append("\n")
2266 # final newline in case the input didn't have it, so that the code
2298 # final newline in case the input didn't have it, so that the code
2267 # actually does get executed
2299 # actually does get executed
2268 if more:
2300 if more:
2269 self.push_line('\n')
2301 self.push_line('\n')
2270
2302
2271 def runsource(self, source, filename='<input>', symbol='single'):
2303 def runsource(self, source, filename='<input>', symbol='single'):
2272 """Compile and run some source in the interpreter.
2304 """Compile and run some source in the interpreter.
2273
2305
2274 Arguments are as for compile_command().
2306 Arguments are as for compile_command().
2275
2307
2276 One several things can happen:
2308 One several things can happen:
2277
2309
2278 1) The input is incorrect; compile_command() raised an
2310 1) The input is incorrect; compile_command() raised an
2279 exception (SyntaxError or OverflowError). A syntax traceback
2311 exception (SyntaxError or OverflowError). A syntax traceback
2280 will be printed by calling the showsyntaxerror() method.
2312 will be printed by calling the showsyntaxerror() method.
2281
2313
2282 2) The input is incomplete, and more input is required;
2314 2) The input is incomplete, and more input is required;
2283 compile_command() returned None. Nothing happens.
2315 compile_command() returned None. Nothing happens.
2284
2316
2285 3) The input is complete; compile_command() returned a code
2317 3) The input is complete; compile_command() returned a code
2286 object. The code is executed by calling self.runcode() (which
2318 object. The code is executed by calling self.runcode() (which
2287 also handles run-time exceptions, except for SystemExit).
2319 also handles run-time exceptions, except for SystemExit).
2288
2320
2289 The return value is:
2321 The return value is:
2290
2322
2291 - True in case 2
2323 - True in case 2
2292
2324
2293 - False in the other cases, unless an exception is raised, where
2325 - False in the other cases, unless an exception is raised, where
2294 None is returned instead. This can be used by external callers to
2326 None is returned instead. This can be used by external callers to
2295 know whether to continue feeding input or not.
2327 know whether to continue feeding input or not.
2296
2328
2297 The return value can be used to decide whether to use sys.ps1 or
2329 The return value can be used to decide whether to use sys.ps1 or
2298 sys.ps2 to prompt the next line."""
2330 sys.ps2 to prompt the next line."""
2299
2331
2300 # We need to ensure that the source is unicode from here on.
2332 # We need to ensure that the source is unicode from here on.
2301 if type(source)==str:
2333 if type(source)==str:
2302 source = source.decode(self.stdin_encoding)
2334 source = source.decode(self.stdin_encoding)
2303
2335
2304 # if the source code has leading blanks, add 'if 1:\n' to it
2336 # if the source code has leading blanks, add 'if 1:\n' to it
2305 # this allows execution of indented pasted code. It is tempting
2337 # this allows execution of indented pasted code. It is tempting
2306 # to add '\n' at the end of source to run commands like ' a=1'
2338 # to add '\n' at the end of source to run commands like ' a=1'
2307 # directly, but this fails for more complicated scenarios
2339 # directly, but this fails for more complicated scenarios
2308
2340
2309 if source[:1] in [' ', '\t']:
2341 if source[:1] in [' ', '\t']:
2310 source = u'if 1:\n%s' % source
2342 source = u'if 1:\n%s' % source
2311
2343
2312 try:
2344 try:
2313 code = self.compile(source,filename,symbol)
2345 code = self.compile(source,filename,symbol)
2314 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2346 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2315 # Case 1
2347 # Case 1
2316 self.showsyntaxerror(filename)
2348 self.showsyntaxerror(filename)
2317 return None
2349 return None
2318
2350
2319 if code is None:
2351 if code is None:
2320 # Case 2
2352 # Case 2
2321 return True
2353 return True
2322
2354
2323 # Case 3
2355 # Case 3
2324 # We store the code object so that threaded shells and
2356 # We store the code object so that threaded shells and
2325 # custom exception handlers can access all this info if needed.
2357 # custom exception handlers can access all this info if needed.
2326 # The source corresponding to this can be obtained from the
2358 # The source corresponding to this can be obtained from the
2327 # buffer attribute as '\n'.join(self.buffer).
2359 # buffer attribute as '\n'.join(self.buffer).
2328 self.code_to_run = code
2360 self.code_to_run = code
2329 # now actually execute the code object
2361 # now actually execute the code object
2330 if self.runcode(code) == 0:
2362 if self.runcode(code) == 0:
2331 return False
2363 return False
2332 else:
2364 else:
2333 return None
2365 return None
2334
2366
2335 def runcode(self, code_obj, post_execute=True):
2367 def runcode(self, code_obj, post_execute=True):
2336 """Execute a code object.
2368 """Execute a code object.
2337
2369
2338 When an exception occurs, self.showtraceback() is called to display a
2370 When an exception occurs, self.showtraceback() is called to display a
2339 traceback.
2371 traceback.
2340
2372
2341 Return value: a flag indicating whether the code to be run completed
2373 Return value: a flag indicating whether the code to be run completed
2342 successfully:
2374 successfully:
2343
2375
2344 - 0: successful execution.
2376 - 0: successful execution.
2345 - 1: an error occurred.
2377 - 1: an error occurred.
2346 """
2378 """
2347
2379
2348 # Set our own excepthook in case the user code tries to call it
2380 # Set our own excepthook in case the user code tries to call it
2349 # directly, so that the IPython crash handler doesn't get triggered
2381 # directly, so that the IPython crash handler doesn't get triggered
2350 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2382 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2351
2383
2352 # we save the original sys.excepthook in the instance, in case config
2384 # we save the original sys.excepthook in the instance, in case config
2353 # code (such as magics) needs access to it.
2385 # code (such as magics) needs access to it.
2354 self.sys_excepthook = old_excepthook
2386 self.sys_excepthook = old_excepthook
2355 outflag = 1 # happens in more places, so it's easier as default
2387 outflag = 1 # happens in more places, so it's easier as default
2356 try:
2388 try:
2357 try:
2389 try:
2358 self.hooks.pre_runcode_hook()
2390 self.hooks.pre_runcode_hook()
2359 #rprint('Running code') # dbg
2391 #rprint('Running code') # dbg
2360 exec code_obj in self.user_global_ns, self.user_ns
2392 exec code_obj in self.user_global_ns, self.user_ns
2361 finally:
2393 finally:
2362 # Reset our crash handler in place
2394 # Reset our crash handler in place
2363 sys.excepthook = old_excepthook
2395 sys.excepthook = old_excepthook
2364 except SystemExit:
2396 except SystemExit:
2365 self.resetbuffer()
2397 self.resetbuffer()
2366 self.showtraceback(exception_only=True)
2398 self.showtraceback(exception_only=True)
2367 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2399 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2368 except self.custom_exceptions:
2400 except self.custom_exceptions:
2369 etype,value,tb = sys.exc_info()
2401 etype,value,tb = sys.exc_info()
2370 self.CustomTB(etype,value,tb)
2402 self.CustomTB(etype,value,tb)
2371 except:
2403 except:
2372 self.showtraceback()
2404 self.showtraceback()
2373 else:
2405 else:
2374 outflag = 0
2406 outflag = 0
2375 if softspace(sys.stdout, 0):
2407 if softspace(sys.stdout, 0):
2376 print
2408 print
2377
2409
2378 # Execute any registered post-execution functions. Here, any errors
2410 # Execute any registered post-execution functions. Here, any errors
2379 # are reported only minimally and just on the terminal, because the
2411 # are reported only minimally and just on the terminal, because the
2380 # main exception channel may be occupied with a user traceback.
2412 # main exception channel may be occupied with a user traceback.
2381 # FIXME: we need to think this mechanism a little more carefully.
2413 # FIXME: we need to think this mechanism a little more carefully.
2382 if post_execute:
2414 if post_execute:
2383 for func in self._post_execute:
2415 for func in self._post_execute:
2384 try:
2416 try:
2385 func()
2417 func()
2386 except:
2418 except:
2387 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2419 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2388 func
2420 func
2389 print >> io.Term.cout, head
2421 print >> io.Term.cout, head
2390 print >> io.Term.cout, self._simple_error()
2422 print >> io.Term.cout, self._simple_error()
2391 print >> io.Term.cout, 'Removing from post_execute'
2423 print >> io.Term.cout, 'Removing from post_execute'
2392 self._post_execute.remove(func)
2424 self._post_execute.remove(func)
2393
2425
2394 # Flush out code object which has been run (and source)
2426 # Flush out code object which has been run (and source)
2395 self.code_to_run = None
2427 self.code_to_run = None
2396 return outflag
2428 return outflag
2397
2429
2398 def push_line(self, line):
2430 def push_line(self, line):
2399 """Push a line to the interpreter.
2431 """Push a line to the interpreter.
2400
2432
2401 The line should not have a trailing newline; it may have
2433 The line should not have a trailing newline; it may have
2402 internal newlines. The line is appended to a buffer and the
2434 internal newlines. The line is appended to a buffer and the
2403 interpreter's runsource() method is called with the
2435 interpreter's runsource() method is called with the
2404 concatenated contents of the buffer as source. If this
2436 concatenated contents of the buffer as source. If this
2405 indicates that the command was executed or invalid, the buffer
2437 indicates that the command was executed or invalid, the buffer
2406 is reset; otherwise, the command is incomplete, and the buffer
2438 is reset; otherwise, the command is incomplete, and the buffer
2407 is left as it was after the line was appended. The return
2439 is left as it was after the line was appended. The return
2408 value is 1 if more input is required, 0 if the line was dealt
2440 value is 1 if more input is required, 0 if the line was dealt
2409 with in some way (this is the same as runsource()).
2441 with in some way (this is the same as runsource()).
2410 """
2442 """
2411
2443
2412 # autoindent management should be done here, and not in the
2444 # autoindent management should be done here, and not in the
2413 # interactive loop, since that one is only seen by keyboard input. We
2445 # interactive loop, since that one is only seen by keyboard input. We
2414 # need this done correctly even for code run via runlines (which uses
2446 # need this done correctly even for code run via runlines (which uses
2415 # push).
2447 # push).
2416
2448
2417 #print 'push line: <%s>' % line # dbg
2449 #print 'push line: <%s>' % line # dbg
2418 for subline in line.splitlines():
2450 for subline in line.splitlines():
2419 self._autoindent_update(subline)
2451 self._autoindent_update(subline)
2420 self.buffer.append(line)
2452 self.buffer.append(line)
2421 more = self.runsource('\n'.join(self.buffer), self.filename)
2453 more = self.runsource('\n'.join(self.buffer), self.filename)
2422 if not more:
2454 if not more:
2423 self.resetbuffer()
2455 self.resetbuffer()
2456 self.execution_count += 1
2424 return more
2457 return more
2425
2458
2426 def resetbuffer(self):
2459 def resetbuffer(self):
2427 """Reset the input buffer."""
2460 """Reset the input buffer."""
2428 self.buffer[:] = []
2461 self.buffer[:] = []
2429
2462
2430 def _is_secondary_block_start(self, s):
2463 def _is_secondary_block_start(self, s):
2431 if not s.endswith(':'):
2464 if not s.endswith(':'):
2432 return False
2465 return False
2433 if (s.startswith('elif') or
2466 if (s.startswith('elif') or
2434 s.startswith('else') or
2467 s.startswith('else') or
2435 s.startswith('except') or
2468 s.startswith('except') or
2436 s.startswith('finally')):
2469 s.startswith('finally')):
2437 return True
2470 return True
2438
2471
2439 def _cleanup_ipy_script(self, script):
2472 def _cleanup_ipy_script(self, script):
2440 """Make a script safe for self.runlines()
2473 """Make a script safe for self.runlines()
2441
2474
2442 Currently, IPython is lines based, with blocks being detected by
2475 Currently, IPython is lines based, with blocks being detected by
2443 empty lines. This is a problem for block based scripts that may
2476 empty lines. This is a problem for block based scripts that may
2444 not have empty lines after blocks. This script adds those empty
2477 not have empty lines after blocks. This script adds those empty
2445 lines to make scripts safe for running in the current line based
2478 lines to make scripts safe for running in the current line based
2446 IPython.
2479 IPython.
2447 """
2480 """
2448 res = []
2481 res = []
2449 lines = script.splitlines()
2482 lines = script.splitlines()
2450 level = 0
2483 level = 0
2451
2484
2452 for l in lines:
2485 for l in lines:
2453 lstripped = l.lstrip()
2486 lstripped = l.lstrip()
2454 stripped = l.strip()
2487 stripped = l.strip()
2455 if not stripped:
2488 if not stripped:
2456 continue
2489 continue
2457 newlevel = len(l) - len(lstripped)
2490 newlevel = len(l) - len(lstripped)
2458 if level > 0 and newlevel == 0 and \
2491 if level > 0 and newlevel == 0 and \
2459 not self._is_secondary_block_start(stripped):
2492 not self._is_secondary_block_start(stripped):
2460 # add empty line
2493 # add empty line
2461 res.append('')
2494 res.append('')
2462 res.append(l)
2495 res.append(l)
2463 level = newlevel
2496 level = newlevel
2464
2497
2465 return '\n'.join(res) + '\n'
2498 return '\n'.join(res) + '\n'
2466
2499
2467 def _autoindent_update(self,line):
2500 def _autoindent_update(self,line):
2468 """Keep track of the indent level."""
2501 """Keep track of the indent level."""
2469
2502
2470 #debugx('line')
2503 #debugx('line')
2471 #debugx('self.indent_current_nsp')
2504 #debugx('self.indent_current_nsp')
2472 if self.autoindent:
2505 if self.autoindent:
2473 if line:
2506 if line:
2474 inisp = num_ini_spaces(line)
2507 inisp = num_ini_spaces(line)
2475 if inisp < self.indent_current_nsp:
2508 if inisp < self.indent_current_nsp:
2476 self.indent_current_nsp = inisp
2509 self.indent_current_nsp = inisp
2477
2510
2478 if line[-1] == ':':
2511 if line[-1] == ':':
2479 self.indent_current_nsp += 4
2512 self.indent_current_nsp += 4
2480 elif dedent_re.match(line):
2513 elif dedent_re.match(line):
2481 self.indent_current_nsp -= 4
2514 self.indent_current_nsp -= 4
2482 else:
2515 else:
2483 self.indent_current_nsp = 0
2516 self.indent_current_nsp = 0
2484
2517
2485 #-------------------------------------------------------------------------
2518 #-------------------------------------------------------------------------
2486 # Things related to GUI support and pylab
2519 # Things related to GUI support and pylab
2487 #-------------------------------------------------------------------------
2520 #-------------------------------------------------------------------------
2488
2521
2489 def enable_pylab(self, gui=None):
2522 def enable_pylab(self, gui=None):
2490 raise NotImplementedError('Implement enable_pylab in a subclass')
2523 raise NotImplementedError('Implement enable_pylab in a subclass')
2491
2524
2492 #-------------------------------------------------------------------------
2525 #-------------------------------------------------------------------------
2493 # Utilities
2526 # Utilities
2494 #-------------------------------------------------------------------------
2527 #-------------------------------------------------------------------------
2495
2528
2496 def var_expand(self,cmd,depth=0):
2529 def var_expand(self,cmd,depth=0):
2497 """Expand python variables in a string.
2530 """Expand python variables in a string.
2498
2531
2499 The depth argument indicates how many frames above the caller should
2532 The depth argument indicates how many frames above the caller should
2500 be walked to look for the local namespace where to expand variables.
2533 be walked to look for the local namespace where to expand variables.
2501
2534
2502 The global namespace for expansion is always the user's interactive
2535 The global namespace for expansion is always the user's interactive
2503 namespace.
2536 namespace.
2504 """
2537 """
2505
2538
2506 return str(ItplNS(cmd,
2539 return str(ItplNS(cmd,
2507 self.user_ns, # globals
2540 self.user_ns, # globals
2508 # Skip our own frame in searching for locals:
2541 # Skip our own frame in searching for locals:
2509 sys._getframe(depth+1).f_locals # locals
2542 sys._getframe(depth+1).f_locals # locals
2510 ))
2543 ))
2511
2544
2512 def mktempfile(self,data=None):
2545 def mktempfile(self,data=None):
2513 """Make a new tempfile and return its filename.
2546 """Make a new tempfile and return its filename.
2514
2547
2515 This makes a call to tempfile.mktemp, but it registers the created
2548 This makes a call to tempfile.mktemp, but it registers the created
2516 filename internally so ipython cleans it up at exit time.
2549 filename internally so ipython cleans it up at exit time.
2517
2550
2518 Optional inputs:
2551 Optional inputs:
2519
2552
2520 - data(None): if data is given, it gets written out to the temp file
2553 - data(None): if data is given, it gets written out to the temp file
2521 immediately, and the file is closed again."""
2554 immediately, and the file is closed again."""
2522
2555
2523 filename = tempfile.mktemp('.py','ipython_edit_')
2556 filename = tempfile.mktemp('.py','ipython_edit_')
2524 self.tempfiles.append(filename)
2557 self.tempfiles.append(filename)
2525
2558
2526 if data:
2559 if data:
2527 tmp_file = open(filename,'w')
2560 tmp_file = open(filename,'w')
2528 tmp_file.write(data)
2561 tmp_file.write(data)
2529 tmp_file.close()
2562 tmp_file.close()
2530 return filename
2563 return filename
2531
2564
2532 # TODO: This should be removed when Term is refactored.
2565 # TODO: This should be removed when Term is refactored.
2533 def write(self,data):
2566 def write(self,data):
2534 """Write a string to the default output"""
2567 """Write a string to the default output"""
2535 io.Term.cout.write(data)
2568 io.Term.cout.write(data)
2536
2569
2537 # TODO: This should be removed when Term is refactored.
2570 # TODO: This should be removed when Term is refactored.
2538 def write_err(self,data):
2571 def write_err(self,data):
2539 """Write a string to the default error output"""
2572 """Write a string to the default error output"""
2540 io.Term.cerr.write(data)
2573 io.Term.cerr.write(data)
2541
2574
2542 def ask_yes_no(self,prompt,default=True):
2575 def ask_yes_no(self,prompt,default=True):
2543 if self.quiet:
2576 if self.quiet:
2544 return True
2577 return True
2545 return ask_yes_no(prompt,default)
2578 return ask_yes_no(prompt,default)
2546
2579
2547 def show_usage(self):
2580 def show_usage(self):
2548 """Show a usage message"""
2581 """Show a usage message"""
2549 page.page(IPython.core.usage.interactive_usage)
2582 page.page(IPython.core.usage.interactive_usage)
2550
2583
2551 #-------------------------------------------------------------------------
2584 #-------------------------------------------------------------------------
2552 # Things related to IPython exiting
2585 # Things related to IPython exiting
2553 #-------------------------------------------------------------------------
2586 #-------------------------------------------------------------------------
2554 def atexit_operations(self):
2587 def atexit_operations(self):
2555 """This will be executed at the time of exit.
2588 """This will be executed at the time of exit.
2556
2589
2557 Cleanup operations and saving of persistent data that is done
2590 Cleanup operations and saving of persistent data that is done
2558 unconditionally by IPython should be performed here.
2591 unconditionally by IPython should be performed here.
2559
2592
2560 For things that may depend on startup flags or platform specifics (such
2593 For things that may depend on startup flags or platform specifics (such
2561 as having readline or not), register a separate atexit function in the
2594 as having readline or not), register a separate atexit function in the
2562 code that has the appropriate information, rather than trying to
2595 code that has the appropriate information, rather than trying to
2563 clutter
2596 clutter
2564 """
2597 """
2565 # Cleanup all tempfiles left around
2598 # Cleanup all tempfiles left around
2566 for tfile in self.tempfiles:
2599 for tfile in self.tempfiles:
2567 try:
2600 try:
2568 os.unlink(tfile)
2601 os.unlink(tfile)
2569 except OSError:
2602 except OSError:
2570 pass
2603 pass
2571
2604
2572 # Clear all user namespaces to release all references cleanly.
2605 # Clear all user namespaces to release all references cleanly.
2573 self.reset()
2606 self.reset()
2574
2607
2575 # Run user hooks
2608 # Run user hooks
2576 self.hooks.shutdown_hook()
2609 self.hooks.shutdown_hook()
2577
2610
2578 def cleanup(self):
2611 def cleanup(self):
2579 self.restore_sys_module_state()
2612 self.restore_sys_module_state()
2580
2613
2581
2614
2582 class InteractiveShellABC(object):
2615 class InteractiveShellABC(object):
2583 """An abstract base class for InteractiveShell."""
2616 """An abstract base class for InteractiveShell."""
2584 __metaclass__ = abc.ABCMeta
2617 __metaclass__ = abc.ABCMeta
2585
2618
2586 InteractiveShellABC.register(InteractiveShell)
2619 InteractiveShellABC.register(InteractiveShell)
@@ -1,263 +1,265 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.displayhook.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.displayhook
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.displayhook.do_full_cache:
211 if self.shell.displayhook.do_full_cache:
212 in_num = self.shell.displayhook.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.displayhook.prompt_count = last_num
219 ## pass # dbg
220 ## #in_num = self.shell.execution_count = last_num
221
220 new_i = '_i%s' % in_num
222 new_i = '_i%s' % in_num
221 if continuation:
223 if continuation:
222 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
224 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line_mod)
223 input_hist[in_num] = self._i00
225 input_hist[in_num] = self._i00
224 to_main[new_i] = self._i00
226 to_main[new_i] = self._i00
225 self.shell.user_ns.update(to_main)
227 self.shell.user_ns.update(to_main)
226
228
227 # Write the log line, but decide which one according to the
229 # Write the log line, but decide which one according to the
228 # log_raw_input flag, set when the log is started.
230 # log_raw_input flag, set when the log is started.
229 if self.log_raw_input:
231 if self.log_raw_input:
230 self.log_write(line_ori)
232 self.log_write(line_ori)
231 else:
233 else:
232 self.log_write(line_mod)
234 self.log_write(line_mod)
233
235
234 def log_write(self,data,kind='input'):
236 def log_write(self,data,kind='input'):
235 """Write data to the log file, if active"""
237 """Write data to the log file, if active"""
236
238
237 #print 'data: %r' % data # dbg
239 #print 'data: %r' % data # dbg
238 if self.log_active and data:
240 if self.log_active and data:
239 write = self.logfile.write
241 write = self.logfile.write
240 if kind=='input':
242 if kind=='input':
241 if self.timestamp:
243 if self.timestamp:
242 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
244 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
243 time.localtime()))
245 time.localtime()))
244 write('%s\n' % data)
246 write('%s\n' % data)
245 elif kind=='output' and self.log_output:
247 elif kind=='output' and self.log_output:
246 odata = '\n'.join(['#[Out]# %s' % s
248 odata = '\n'.join(['#[Out]# %s' % s
247 for s in data.split('\n')])
249 for s in data.split('\n')])
248 write('%s\n' % odata)
250 write('%s\n' % odata)
249 self.logfile.flush()
251 self.logfile.flush()
250
252
251 def logstop(self):
253 def logstop(self):
252 """Fully stop logging and close log file.
254 """Fully stop logging and close log file.
253
255
254 In order to start logging again, a new logstart() call needs to be
256 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
257 made, possibly (though not necessarily) with a new filename, mode and
256 other options."""
258 other options."""
257
259
258 self.logfile.close()
260 self.logfile.close()
259 self.logfile = None
261 self.logfile = None
260 self.log_active = False
262 self.log_active = False
261
263
262 # For backwards compatibility, in case anyone was using this.
264 # For backwards compatibility, in case anyone was using this.
263 close_log = logstop
265 close_log = logstop
@@ -1,444 +1,436 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Classes for handling input/output prompts.
2 """Classes for handling input/output prompts.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian Granger
7 * Brian Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2010 The IPython Development Team
11 # Copyright (C) 2008-2010 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import os
22 import os
23 import re
23 import re
24 import socket
24 import socket
25 import sys
25 import sys
26
26
27 from IPython.core import release
27 from IPython.core import release
28 from IPython.external.Itpl import ItplNS
28 from IPython.external.Itpl import ItplNS
29 from IPython.utils import coloransi
29 from IPython.utils import coloransi
30
30
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32 # Color schemes for prompts
32 # Color schemes for prompts
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34
34
35 PromptColors = coloransi.ColorSchemeTable()
35 PromptColors = coloransi.ColorSchemeTable()
36 InputColors = coloransi.InputTermColors # just a shorthand
36 InputColors = coloransi.InputTermColors # just a shorthand
37 Colors = coloransi.TermColors # just a shorthand
37 Colors = coloransi.TermColors # just a shorthand
38
38
39 PromptColors.add_scheme(coloransi.ColorScheme(
39 PromptColors.add_scheme(coloransi.ColorScheme(
40 'NoColor',
40 'NoColor',
41 in_prompt = InputColors.NoColor, # Input prompt
41 in_prompt = InputColors.NoColor, # Input prompt
42 in_number = InputColors.NoColor, # Input prompt number
42 in_number = InputColors.NoColor, # Input prompt number
43 in_prompt2 = InputColors.NoColor, # Continuation prompt
43 in_prompt2 = InputColors.NoColor, # Continuation prompt
44 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
44 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
45
45
46 out_prompt = Colors.NoColor, # Output prompt
46 out_prompt = Colors.NoColor, # Output prompt
47 out_number = Colors.NoColor, # Output prompt number
47 out_number = Colors.NoColor, # Output prompt number
48
48
49 normal = Colors.NoColor # color off (usu. Colors.Normal)
49 normal = Colors.NoColor # color off (usu. Colors.Normal)
50 ))
50 ))
51
51
52 # make some schemes as instances so we can copy them for modification easily:
52 # make some schemes as instances so we can copy them for modification easily:
53 __PColLinux = coloransi.ColorScheme(
53 __PColLinux = coloransi.ColorScheme(
54 'Linux',
54 'Linux',
55 in_prompt = InputColors.Green,
55 in_prompt = InputColors.Green,
56 in_number = InputColors.LightGreen,
56 in_number = InputColors.LightGreen,
57 in_prompt2 = InputColors.Green,
57 in_prompt2 = InputColors.Green,
58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
58 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
59
59
60 out_prompt = Colors.Red,
60 out_prompt = Colors.Red,
61 out_number = Colors.LightRed,
61 out_number = Colors.LightRed,
62
62
63 normal = Colors.Normal
63 normal = Colors.Normal
64 )
64 )
65 # Don't forget to enter it into the table!
65 # Don't forget to enter it into the table!
66 PromptColors.add_scheme(__PColLinux)
66 PromptColors.add_scheme(__PColLinux)
67
67
68 # Slightly modified Linux for light backgrounds
68 # Slightly modified Linux for light backgrounds
69 __PColLightBG = __PColLinux.copy('LightBG')
69 __PColLightBG = __PColLinux.copy('LightBG')
70
70
71 __PColLightBG.colors.update(
71 __PColLightBG.colors.update(
72 in_prompt = InputColors.Blue,
72 in_prompt = InputColors.Blue,
73 in_number = InputColors.LightBlue,
73 in_number = InputColors.LightBlue,
74 in_prompt2 = InputColors.Blue
74 in_prompt2 = InputColors.Blue
75 )
75 )
76 PromptColors.add_scheme(__PColLightBG)
76 PromptColors.add_scheme(__PColLightBG)
77
77
78 del Colors,InputColors
78 del Colors,InputColors
79
79
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81 # Utilities
81 # Utilities
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83
83
84 def multiple_replace(dict, text):
84 def multiple_replace(dict, text):
85 """ Replace in 'text' all occurences of any key in the given
85 """ Replace in 'text' all occurences of any key in the given
86 dictionary by its corresponding value. Returns the new string."""
86 dictionary by its corresponding value. Returns the new string."""
87
87
88 # Function by Xavier Defrang, originally found at:
88 # Function by Xavier Defrang, originally found at:
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
89 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
90
90
91 # Create a regular expression from the dictionary keys
91 # Create a regular expression from the dictionary keys
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
92 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
93 # For each match, look-up corresponding value in dictionary
93 # For each match, look-up corresponding value in dictionary
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
94 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Special characters that can be used in prompt templates, mainly bash-like
97 # Special characters that can be used in prompt templates, mainly bash-like
98 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
99
99
100 # If $HOME isn't defined (Windows), make it an absurd string so that it can
100 # If $HOME isn't defined (Windows), make it an absurd string so that it can
101 # never be expanded out into '~'. Basically anything which can never be a
101 # never be expanded out into '~'. Basically anything which can never be a
102 # reasonable directory name will do, we just want the $HOME -> '~' operation
102 # reasonable directory name will do, we just want the $HOME -> '~' operation
103 # to become a no-op. We pre-compute $HOME here so it's not done on every
103 # to become a no-op. We pre-compute $HOME here so it's not done on every
104 # prompt call.
104 # prompt call.
105
105
106 # FIXME:
106 # FIXME:
107
107
108 # - This should be turned into a class which does proper namespace management,
108 # - This should be turned into a class which does proper namespace management,
109 # since the prompt specials need to be evaluated in a certain namespace.
109 # since the prompt specials need to be evaluated in a certain namespace.
110 # Currently it's just globals, which need to be managed manually by code
110 # Currently it's just globals, which need to be managed manually by code
111 # below.
111 # below.
112
112
113 # - I also need to split up the color schemes from the prompt specials
113 # - I also need to split up the color schemes from the prompt specials
114 # somehow. I don't have a clean design for that quite yet.
114 # somehow. I don't have a clean design for that quite yet.
115
115
116 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
116 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
117
117
118 # We precompute a few more strings here for the prompt_specials, which are
118 # We precompute a few more strings here for the prompt_specials, which are
119 # fixed once ipython starts. This reduces the runtime overhead of computing
119 # fixed once ipython starts. This reduces the runtime overhead of computing
120 # prompt strings.
120 # prompt strings.
121 USER = os.environ.get("USER")
121 USER = os.environ.get("USER")
122 HOSTNAME = socket.gethostname()
122 HOSTNAME = socket.gethostname()
123 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
123 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
124 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
124 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
125
125
126 prompt_specials_color = {
126 prompt_specials_color = {
127 # Prompt/history count
127 # Prompt/history count
128 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
128 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
129 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
130 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
130 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
131 # can get numbers displayed in whatever color they want.
131 # can get numbers displayed in whatever color they want.
132 r'\N': '${self.cache.prompt_count}',
132 r'\N': '${self.cache.prompt_count}',
133
133
134 # Prompt/history count, with the actual digits replaced by dots. Used
134 # Prompt/history count, with the actual digits replaced by dots. Used
135 # mainly in continuation prompts (prompt_in2)
135 # mainly in continuation prompts (prompt_in2)
136 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
136 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
137
137
138 # More robust form of the above expression, that uses the __builtin__
138 # More robust form of the above expression, that uses the __builtin__
139 # module. Note that we can NOT use __builtins__ (note the 's'), because
139 # module. Note that we can NOT use __builtins__ (note the 's'), because
140 # that can either be a dict or a module, and can even mutate at runtime,
140 # that can either be a dict or a module, and can even mutate at runtime,
141 # depending on the context (Python makes no guarantees on it). In
141 # depending on the context (Python makes no guarantees on it). In
142 # contrast, __builtin__ is always a module object, though it must be
142 # contrast, __builtin__ is always a module object, though it must be
143 # explicitly imported.
143 # explicitly imported.
144 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
144 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
145
145
146 # Current working directory
146 # Current working directory
147 r'\w': '${os.getcwd()}',
147 r'\w': '${os.getcwd()}',
148 # Current time
148 # Current time
149 r'\t' : '${time.strftime("%H:%M:%S")}',
149 r'\t' : '${time.strftime("%H:%M:%S")}',
150 # Basename of current working directory.
150 # Basename of current working directory.
151 # (use os.sep to make this portable across OSes)
151 # (use os.sep to make this portable across OSes)
152 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
152 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
153 # These X<N> are an extension to the normal bash prompts. They return
153 # These X<N> are an extension to the normal bash prompts. They return
154 # N terms of the path, after replacing $HOME with '~'
154 # N terms of the path, after replacing $HOME with '~'
155 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
155 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
156 r'\X1': '${self.cwd_filt(1)}',
156 r'\X1': '${self.cwd_filt(1)}',
157 r'\X2': '${self.cwd_filt(2)}',
157 r'\X2': '${self.cwd_filt(2)}',
158 r'\X3': '${self.cwd_filt(3)}',
158 r'\X3': '${self.cwd_filt(3)}',
159 r'\X4': '${self.cwd_filt(4)}',
159 r'\X4': '${self.cwd_filt(4)}',
160 r'\X5': '${self.cwd_filt(5)}',
160 r'\X5': '${self.cwd_filt(5)}',
161 # Y<N> are similar to X<N>, but they show '~' if it's the directory
161 # Y<N> are similar to X<N>, but they show '~' if it's the directory
162 # N+1 in the list. Somewhat like %cN in tcsh.
162 # N+1 in the list. Somewhat like %cN in tcsh.
163 r'\Y0': '${self.cwd_filt2(0)}',
163 r'\Y0': '${self.cwd_filt2(0)}',
164 r'\Y1': '${self.cwd_filt2(1)}',
164 r'\Y1': '${self.cwd_filt2(1)}',
165 r'\Y2': '${self.cwd_filt2(2)}',
165 r'\Y2': '${self.cwd_filt2(2)}',
166 r'\Y3': '${self.cwd_filt2(3)}',
166 r'\Y3': '${self.cwd_filt2(3)}',
167 r'\Y4': '${self.cwd_filt2(4)}',
167 r'\Y4': '${self.cwd_filt2(4)}',
168 r'\Y5': '${self.cwd_filt2(5)}',
168 r'\Y5': '${self.cwd_filt2(5)}',
169 # Hostname up to first .
169 # Hostname up to first .
170 r'\h': HOSTNAME_SHORT,
170 r'\h': HOSTNAME_SHORT,
171 # Full hostname
171 # Full hostname
172 r'\H': HOSTNAME,
172 r'\H': HOSTNAME,
173 # Username of current user
173 # Username of current user
174 r'\u': USER,
174 r'\u': USER,
175 # Escaped '\'
175 # Escaped '\'
176 '\\\\': '\\',
176 '\\\\': '\\',
177 # Newline
177 # Newline
178 r'\n': '\n',
178 r'\n': '\n',
179 # Carriage return
179 # Carriage return
180 r'\r': '\r',
180 r'\r': '\r',
181 # Release version
181 # Release version
182 r'\v': release.version,
182 r'\v': release.version,
183 # Root symbol ($ or #)
183 # Root symbol ($ or #)
184 r'\$': ROOT_SYMBOL,
184 r'\$': ROOT_SYMBOL,
185 }
185 }
186
186
187 # A copy of the prompt_specials dictionary but with all color escapes removed,
187 # A copy of the prompt_specials dictionary but with all color escapes removed,
188 # so we can correctly compute the prompt length for the auto_rewrite method.
188 # so we can correctly compute the prompt length for the auto_rewrite method.
189 prompt_specials_nocolor = prompt_specials_color.copy()
189 prompt_specials_nocolor = prompt_specials_color.copy()
190 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
190 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
191 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
191 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
192
192
193 # Add in all the InputTermColors color escapes as valid prompt characters.
193 # Add in all the InputTermColors color escapes as valid prompt characters.
194 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
194 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
195 # with a color name which may begin with a letter used by any other of the
195 # with a color name which may begin with a letter used by any other of the
196 # allowed specials. This of course means that \\C will never be allowed for
196 # allowed specials. This of course means that \\C will never be allowed for
197 # anything else.
197 # anything else.
198 input_colors = coloransi.InputTermColors
198 input_colors = coloransi.InputTermColors
199 for _color in dir(input_colors):
199 for _color in dir(input_colors):
200 if _color[0] != '_':
200 if _color[0] != '_':
201 c_name = r'\C_'+_color
201 c_name = r'\C_'+_color
202 prompt_specials_color[c_name] = getattr(input_colors,_color)
202 prompt_specials_color[c_name] = getattr(input_colors,_color)
203 prompt_specials_nocolor[c_name] = ''
203 prompt_specials_nocolor[c_name] = ''
204
204
205 # we default to no color for safety. Note that prompt_specials is a global
205 # we default to no color for safety. Note that prompt_specials is a global
206 # variable used by all prompt objects.
206 # variable used by all prompt objects.
207 prompt_specials = prompt_specials_nocolor
207 prompt_specials = prompt_specials_nocolor
208
208
209 #-----------------------------------------------------------------------------
209 #-----------------------------------------------------------------------------
210 # More utilities
210 # More utilities
211 #-----------------------------------------------------------------------------
211 #-----------------------------------------------------------------------------
212
212
213 def str_safe(arg):
213 def str_safe(arg):
214 """Convert to a string, without ever raising an exception.
214 """Convert to a string, without ever raising an exception.
215
215
216 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
216 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
217 error message."""
217 error message."""
218
218
219 try:
219 try:
220 out = str(arg)
220 out = str(arg)
221 except UnicodeError:
221 except UnicodeError:
222 try:
222 try:
223 out = arg.encode('utf_8','replace')
223 out = arg.encode('utf_8','replace')
224 except Exception,msg:
224 except Exception,msg:
225 # let's keep this little duplication here, so that the most common
225 # let's keep this little duplication here, so that the most common
226 # case doesn't suffer from a double try wrapping.
226 # case doesn't suffer from a double try wrapping.
227 out = '<ERROR: %s>' % msg
227 out = '<ERROR: %s>' % msg
228 except Exception,msg:
228 except Exception,msg:
229 out = '<ERROR: %s>' % msg
229 out = '<ERROR: %s>' % msg
230 #raise # dbg
230 #raise # dbg
231 return out
231 return out
232
232
233 #-----------------------------------------------------------------------------
233 #-----------------------------------------------------------------------------
234 # Prompt classes
234 # Prompt classes
235 #-----------------------------------------------------------------------------
235 #-----------------------------------------------------------------------------
236
236
237 class BasePrompt(object):
237 class BasePrompt(object):
238 """Interactive prompt similar to Mathematica's."""
238 """Interactive prompt similar to Mathematica's."""
239
239
240 def _get_p_template(self):
240 def _get_p_template(self):
241 return self._p_template
241 return self._p_template
242
242
243 def _set_p_template(self,val):
243 def _set_p_template(self,val):
244 self._p_template = val
244 self._p_template = val
245 self.set_p_str()
245 self.set_p_str()
246
246
247 p_template = property(_get_p_template,_set_p_template,
247 p_template = property(_get_p_template,_set_p_template,
248 doc='Template for prompt string creation')
248 doc='Template for prompt string creation')
249
249
250 def __init__(self, cache, sep, prompt, pad_left=False):
250 def __init__(self, cache, sep, prompt, pad_left=False):
251
251
252 # Hack: we access information about the primary prompt through the
252 # Hack: we access information about the primary prompt through the
253 # cache argument. We need this, because we want the secondary prompt
253 # cache argument. We need this, because we want the secondary prompt
254 # to be aligned with the primary one. Color table info is also shared
254 # to be aligned with the primary one. Color table info is also shared
255 # by all prompt classes through the cache. Nice OO spaghetti code!
255 # by all prompt classes through the cache. Nice OO spaghetti code!
256 self.cache = cache
256 self.cache = cache
257 self.sep = sep
257 self.sep = sep
258
258
259 # regexp to count the number of spaces at the end of a prompt
259 # regexp to count the number of spaces at the end of a prompt
260 # expression, useful for prompt auto-rewriting
260 # expression, useful for prompt auto-rewriting
261 self.rspace = re.compile(r'(\s*)$')
261 self.rspace = re.compile(r'(\s*)$')
262 # Flag to left-pad prompt strings to match the length of the primary
262 # Flag to left-pad prompt strings to match the length of the primary
263 # prompt
263 # prompt
264 self.pad_left = pad_left
264 self.pad_left = pad_left
265
265
266 # Set template to create each actual prompt (where numbers change).
266 # Set template to create each actual prompt (where numbers change).
267 # Use a property
267 # Use a property
268 self.p_template = prompt
268 self.p_template = prompt
269 self.set_p_str()
269 self.set_p_str()
270
270
271 def set_p_str(self):
271 def set_p_str(self):
272 """ Set the interpolating prompt strings.
272 """ Set the interpolating prompt strings.
273
273
274 This must be called every time the color settings change, because the
274 This must be called every time the color settings change, because the
275 prompt_specials global may have changed."""
275 prompt_specials global may have changed."""
276
276
277 import os,time # needed in locals for prompt string handling
277 import os,time # needed in locals for prompt string handling
278 loc = locals()
278 loc = locals()
279 try:
279 try:
280 self.p_str = ItplNS('%s%s%s' %
280 self.p_str = ItplNS('%s%s%s' %
281 ('${self.sep}${self.col_p}',
281 ('${self.sep}${self.col_p}',
282 multiple_replace(prompt_specials, self.p_template),
282 multiple_replace(prompt_specials, self.p_template),
283 '${self.col_norm}'),self.cache.shell.user_ns,loc)
283 '${self.col_norm}'),self.cache.shell.user_ns,loc)
284
284
285 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
285 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
286 self.p_template),
286 self.p_template),
287 self.cache.shell.user_ns,loc)
287 self.cache.shell.user_ns,loc)
288 except:
288 except:
289 print "Illegal prompt template (check $ usage!):",self.p_template
289 print "Illegal prompt template (check $ usage!):",self.p_template
290 self.p_str = self.p_template
290 self.p_str = self.p_template
291 self.p_str_nocolor = self.p_template
291 self.p_str_nocolor = self.p_template
292
292
293 def write(self, msg):
293 def write(self, msg):
294 sys.stdout.write(msg)
294 sys.stdout.write(msg)
295 return ''
295 return ''
296
296
297 def __str__(self):
297 def __str__(self):
298 """Return a string form of the prompt.
298 """Return a string form of the prompt.
299
299
300 This for is useful for continuation and output prompts, since it is
300 This for is useful for continuation and output prompts, since it is
301 left-padded to match lengths with the primary one (if the
301 left-padded to match lengths with the primary one (if the
302 self.pad_left attribute is set)."""
302 self.pad_left attribute is set)."""
303
303
304 out_str = str_safe(self.p_str)
304 out_str = str_safe(self.p_str)
305 if self.pad_left:
305 if self.pad_left:
306 # We must find the amount of padding required to match lengths,
306 # We must find the amount of padding required to match lengths,
307 # taking the color escapes (which are invisible on-screen) into
307 # taking the color escapes (which are invisible on-screen) into
308 # account.
308 # account.
309 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
309 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
310 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
310 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
311 return format % out_str
311 return format % out_str
312 else:
312 else:
313 return out_str
313 return out_str
314
314
315 # these path filters are put in as methods so that we can control the
315 # these path filters are put in as methods so that we can control the
316 # namespace where the prompt strings get evaluated
316 # namespace where the prompt strings get evaluated
317 def cwd_filt(self, depth):
317 def cwd_filt(self, depth):
318 """Return the last depth elements of the current working directory.
318 """Return the last depth elements of the current working directory.
319
319
320 $HOME is always replaced with '~'.
320 $HOME is always replaced with '~'.
321 If depth==0, the full path is returned."""
321 If depth==0, the full path is returned."""
322
322
323 cwd = os.getcwd().replace(HOME,"~")
323 cwd = os.getcwd().replace(HOME,"~")
324 out = os.sep.join(cwd.split(os.sep)[-depth:])
324 out = os.sep.join(cwd.split(os.sep)[-depth:])
325 if out:
325 if out:
326 return out
326 return out
327 else:
327 else:
328 return os.sep
328 return os.sep
329
329
330 def cwd_filt2(self, depth):
330 def cwd_filt2(self, depth):
331 """Return the last depth elements of the current working directory.
331 """Return the last depth elements of the current working directory.
332
332
333 $HOME is always replaced with '~'.
333 $HOME is always replaced with '~'.
334 If depth==0, the full path is returned."""
334 If depth==0, the full path is returned."""
335
335
336 full_cwd = os.getcwd()
336 full_cwd = os.getcwd()
337 cwd = full_cwd.replace(HOME,"~").split(os.sep)
337 cwd = full_cwd.replace(HOME,"~").split(os.sep)
338 if '~' in cwd and len(cwd) == depth+1:
338 if '~' in cwd and len(cwd) == depth+1:
339 depth += 1
339 depth += 1
340 drivepart = ''
340 drivepart = ''
341 if sys.platform == 'win32' and len(cwd) > depth:
341 if sys.platform == 'win32' and len(cwd) > depth:
342 drivepart = os.path.splitdrive(full_cwd)[0]
342 drivepart = os.path.splitdrive(full_cwd)[0]
343 out = drivepart + '/'.join(cwd[-depth:])
343 out = drivepart + '/'.join(cwd[-depth:])
344
344
345 if out:
345 if out:
346 return out
346 return out
347 else:
347 else:
348 return os.sep
348 return os.sep
349
349
350 def __nonzero__(self):
350 def __nonzero__(self):
351 """Implement boolean behavior.
351 """Implement boolean behavior.
352
352
353 Checks whether the p_str attribute is non-empty"""
353 Checks whether the p_str attribute is non-empty"""
354
354
355 return bool(self.p_template)
355 return bool(self.p_template)
356
356
357
357
358 class Prompt1(BasePrompt):
358 class Prompt1(BasePrompt):
359 """Input interactive prompt similar to Mathematica's."""
359 """Input interactive prompt similar to Mathematica's."""
360
360
361 def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True):
361 def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True):
362 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
362 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
363
363
364 def set_colors(self):
364 def set_colors(self):
365 self.set_p_str()
365 self.set_p_str()
366 Colors = self.cache.color_table.active_colors # shorthand
366 Colors = self.cache.color_table.active_colors # shorthand
367 self.col_p = Colors.in_prompt
367 self.col_p = Colors.in_prompt
368 self.col_num = Colors.in_number
368 self.col_num = Colors.in_number
369 self.col_norm = Colors.in_normal
369 self.col_norm = Colors.in_normal
370 # We need a non-input version of these escapes for the '--->'
370 # We need a non-input version of these escapes for the '--->'
371 # auto-call prompts used in the auto_rewrite() method.
371 # auto-call prompts used in the auto_rewrite() method.
372 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
372 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
373 self.col_norm_ni = Colors.normal
373 self.col_norm_ni = Colors.normal
374
374
375 def peek_next_prompt(self):
376 """Get the next prompt, but don't increment the counter."""
377 self.cache.prompt_count += 1
378 next_prompt = str_safe(self.p_str)
379 self.cache.prompt_count -= 1
380 return next_prompt
381
382 def __str__(self):
375 def __str__(self):
383 self.cache.prompt_count += 1
384 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
376 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
385 return str_safe(self.p_str)
377 return str_safe(self.p_str)
386
378
387 def auto_rewrite(self):
379 def auto_rewrite(self):
388 """Return a string of the form '--->' which lines up with the previous
380 """Return a string of the form '--->' which lines up with the previous
389 input string. Useful for systems which re-write the user input when
381 input string. Useful for systems which re-write the user input when
390 handling automatically special syntaxes."""
382 handling automatically special syntaxes."""
391
383
392 curr = str(self.cache.last_prompt)
384 curr = str(self.cache.last_prompt)
393 nrspaces = len(self.rspace.search(curr).group())
385 nrspaces = len(self.rspace.search(curr).group())
394 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
386 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
395 ' '*nrspaces,self.col_norm_ni)
387 ' '*nrspaces,self.col_norm_ni)
396
388
397
389
398 class PromptOut(BasePrompt):
390 class PromptOut(BasePrompt):
399 """Output interactive prompt similar to Mathematica's."""
391 """Output interactive prompt similar to Mathematica's."""
400
392
401 def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True):
393 def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True):
402 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
394 BasePrompt.__init__(self, cache, sep, prompt, pad_left)
403 if not self.p_template:
395 if not self.p_template:
404 self.__str__ = lambda: ''
396 self.__str__ = lambda: ''
405
397
406 def set_colors(self):
398 def set_colors(self):
407 self.set_p_str()
399 self.set_p_str()
408 Colors = self.cache.color_table.active_colors # shorthand
400 Colors = self.cache.color_table.active_colors # shorthand
409 self.col_p = Colors.out_prompt
401 self.col_p = Colors.out_prompt
410 self.col_num = Colors.out_number
402 self.col_num = Colors.out_number
411 self.col_norm = Colors.normal
403 self.col_norm = Colors.normal
412
404
413
405
414 class Prompt2(BasePrompt):
406 class Prompt2(BasePrompt):
415 """Interactive continuation prompt."""
407 """Interactive continuation prompt."""
416
408
417 def __init__(self, cache, prompt=' .\\D.: ', pad_left=True):
409 def __init__(self, cache, prompt=' .\\D.: ', pad_left=True):
418 self.cache = cache
410 self.cache = cache
419 self.p_template = prompt
411 self.p_template = prompt
420 self.pad_left = pad_left
412 self.pad_left = pad_left
421 self.set_p_str()
413 self.set_p_str()
422
414
423 def set_p_str(self):
415 def set_p_str(self):
424 import os,time # needed in locals for prompt string handling
416 import os,time # needed in locals for prompt string handling
425 loc = locals()
417 loc = locals()
426 self.p_str = ItplNS('%s%s%s' %
418 self.p_str = ItplNS('%s%s%s' %
427 ('${self.col_p2}',
419 ('${self.col_p2}',
428 multiple_replace(prompt_specials, self.p_template),
420 multiple_replace(prompt_specials, self.p_template),
429 '$self.col_norm'),
421 '$self.col_norm'),
430 self.cache.shell.user_ns,loc)
422 self.cache.shell.user_ns,loc)
431 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
423 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
432 self.p_template),
424 self.p_template),
433 self.cache.shell.user_ns,loc)
425 self.cache.shell.user_ns,loc)
434
426
435 def set_colors(self):
427 def set_colors(self):
436 self.set_p_str()
428 self.set_p_str()
437 Colors = self.cache.color_table.active_colors
429 Colors = self.cache.color_table.active_colors
438 self.col_p2 = Colors.in_prompt2
430 self.col_p2 = Colors.in_prompt2
439 self.col_norm = Colors.in_normal
431 self.col_norm = Colors.in_normal
440 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
432 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
441 # updated their prompt_in2 definitions. Remove eventually.
433 # updated their prompt_in2 definitions. Remove eventually.
442 self.col_p = Colors.out_prompt
434 self.col_p = Colors.out_prompt
443 self.col_num = Colors.out_number
435 self.col_num = Colors.out_number
444
436
@@ -1,652 +1,657 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 def get_default_editor():
42 def get_default_editor():
43 try:
43 try:
44 ed = os.environ['EDITOR']
44 ed = os.environ['EDITOR']
45 except KeyError:
45 except KeyError:
46 if os.name == 'posix':
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
48 else:
49 ed = 'notepad' # same in Windows!
49 ed = 'notepad' # same in Windows!
50 return ed
50 return ed
51
51
52
52
53 # store the builtin raw_input globally, and use this always, in case user code
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
55 raw_input_original = raw_input
56
56
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Main class
59 # Main class
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62
62
63 class TerminalInteractiveShell(InteractiveShell):
63 class TerminalInteractiveShell(InteractiveShell):
64
64
65 autoedit_syntax = CBool(False, config=True)
65 autoedit_syntax = CBool(False, config=True)
66 banner = Str('')
66 banner = Str('')
67 banner1 = Str(default_banner, config=True)
67 banner1 = Str(default_banner, config=True)
68 banner2 = Str('', config=True)
68 banner2 = Str('', config=True)
69 confirm_exit = CBool(True, config=True)
69 confirm_exit = CBool(True, config=True)
70 # This display_banner only controls whether or not self.show_banner()
70 # This display_banner only controls whether or not self.show_banner()
71 # is called when mainloop/interact are called. The default is False
71 # is called when mainloop/interact are called. The default is False
72 # because for the terminal based application, the banner behavior
72 # because for the terminal based application, the banner behavior
73 # is controlled by Global.display_banner, which IPythonApp looks at
73 # is controlled by Global.display_banner, which IPythonApp looks at
74 # to determine if *it* should call show_banner() by hand or not.
74 # to determine if *it* should call show_banner() by hand or not.
75 display_banner = CBool(False) # This isn't configurable!
75 display_banner = CBool(False) # This isn't configurable!
76 embedded = CBool(False)
76 embedded = CBool(False)
77 embedded_active = CBool(False)
77 embedded_active = CBool(False)
78 editor = Str(get_default_editor(), config=True)
78 editor = Str(get_default_editor(), config=True)
79 pager = Str('less', config=True)
79 pager = Str('less', config=True)
80
80
81 screen_length = Int(0, config=True)
81 screen_length = Int(0, config=True)
82 term_title = CBool(False, config=True)
82 term_title = CBool(False, config=True)
83
83
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 user_global_ns=None, custom_exceptions=((),None),
85 user_global_ns=None, custom_exceptions=((),None),
86 usage=None, banner1=None, banner2=None,
86 usage=None, banner1=None, banner2=None,
87 display_banner=None):
87 display_banner=None):
88
88
89 super(TerminalInteractiveShell, self).__init__(
89 super(TerminalInteractiveShell, self).__init__(
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 )
92 )
93 self.init_term_title()
93 self.init_term_title()
94 self.init_usage(usage)
94 self.init_usage(usage)
95 self.init_banner(banner1, banner2, display_banner)
95 self.init_banner(banner1, banner2, display_banner)
96
96
97 #-------------------------------------------------------------------------
97 #-------------------------------------------------------------------------
98 # Things related to the terminal
98 # Things related to the terminal
99 #-------------------------------------------------------------------------
99 #-------------------------------------------------------------------------
100
100
101 @property
101 @property
102 def usable_screen_length(self):
102 def usable_screen_length(self):
103 if self.screen_length == 0:
103 if self.screen_length == 0:
104 return 0
104 return 0
105 else:
105 else:
106 num_lines_bot = self.separate_in.count('\n')+1
106 num_lines_bot = self.separate_in.count('\n')+1
107 return self.screen_length - num_lines_bot
107 return self.screen_length - num_lines_bot
108
108
109 def init_term_title(self):
109 def init_term_title(self):
110 # Enable or disable the terminal title.
110 # Enable or disable the terminal title.
111 if self.term_title:
111 if self.term_title:
112 toggle_set_term_title(True)
112 toggle_set_term_title(True)
113 set_term_title('IPython: ' + abbrev_cwd())
113 set_term_title('IPython: ' + abbrev_cwd())
114 else:
114 else:
115 toggle_set_term_title(False)
115 toggle_set_term_title(False)
116
116
117 #-------------------------------------------------------------------------
117 #-------------------------------------------------------------------------
118 # Things related to aliases
118 # Things related to aliases
119 #-------------------------------------------------------------------------
119 #-------------------------------------------------------------------------
120
120
121 def init_alias(self):
121 def init_alias(self):
122 # The parent class defines aliases that can be safely used with any
122 # The parent class defines aliases that can be safely used with any
123 # frontend.
123 # frontend.
124 super(TerminalInteractiveShell, self).init_alias()
124 super(TerminalInteractiveShell, self).init_alias()
125
125
126 # Now define aliases that only make sense on the terminal, because they
126 # Now define aliases that only make sense on the terminal, because they
127 # need direct access to the console in a way that we can't emulate in
127 # need direct access to the console in a way that we can't emulate in
128 # GUI or web frontend
128 # GUI or web frontend
129 if os.name == 'posix':
129 if os.name == 'posix':
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
131 ('man', 'man')]
131 ('man', 'man')]
132 elif os.name == 'nt':
132 elif os.name == 'nt':
133 aliases = [('cls', 'cls')]
133 aliases = [('cls', 'cls')]
134
134
135
135
136 for name, cmd in aliases:
136 for name, cmd in aliases:
137 self.alias_manager.define_alias(name, cmd)
137 self.alias_manager.define_alias(name, cmd)
138
138
139 #-------------------------------------------------------------------------
139 #-------------------------------------------------------------------------
140 # Things related to the banner and usage
140 # Things related to the banner and usage
141 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
142
142
143 def _banner1_changed(self):
143 def _banner1_changed(self):
144 self.compute_banner()
144 self.compute_banner()
145
145
146 def _banner2_changed(self):
146 def _banner2_changed(self):
147 self.compute_banner()
147 self.compute_banner()
148
148
149 def _term_title_changed(self, name, new_value):
149 def _term_title_changed(self, name, new_value):
150 self.init_term_title()
150 self.init_term_title()
151
151
152 def init_banner(self, banner1, banner2, display_banner):
152 def init_banner(self, banner1, banner2, display_banner):
153 if banner1 is not None:
153 if banner1 is not None:
154 self.banner1 = banner1
154 self.banner1 = banner1
155 if banner2 is not None:
155 if banner2 is not None:
156 self.banner2 = banner2
156 self.banner2 = banner2
157 if display_banner is not None:
157 if display_banner is not None:
158 self.display_banner = display_banner
158 self.display_banner = display_banner
159 self.compute_banner()
159 self.compute_banner()
160
160
161 def show_banner(self, banner=None):
161 def show_banner(self, banner=None):
162 if banner is None:
162 if banner is None:
163 banner = self.banner
163 banner = self.banner
164 self.write(banner)
164 self.write(banner)
165
165
166 def compute_banner(self):
166 def compute_banner(self):
167 self.banner = self.banner1
167 self.banner = self.banner1
168 if self.profile:
168 if self.profile:
169 self.banner += '\nIPython profile: %s\n' % self.profile
169 self.banner += '\nIPython profile: %s\n' % self.profile
170 if self.banner2:
170 if self.banner2:
171 self.banner += '\n' + self.banner2
171 self.banner += '\n' + self.banner2
172
172
173 def init_usage(self, usage=None):
173 def init_usage(self, usage=None):
174 if usage is None:
174 if usage is None:
175 self.usage = interactive_usage
175 self.usage = interactive_usage
176 else:
176 else:
177 self.usage = usage
177 self.usage = usage
178
178
179 #-------------------------------------------------------------------------
179 #-------------------------------------------------------------------------
180 # Mainloop and code execution logic
180 # Mainloop and code execution logic
181 #-------------------------------------------------------------------------
181 #-------------------------------------------------------------------------
182
182
183 def mainloop(self, display_banner=None):
183 def mainloop(self, display_banner=None):
184 """Start the mainloop.
184 """Start the mainloop.
185
185
186 If an optional banner argument is given, it will override the
186 If an optional banner argument is given, it will override the
187 internally created default banner.
187 internally created default banner.
188 """
188 """
189
189
190 with nested(self.builtin_trap, self.display_trap):
190 with nested(self.builtin_trap, self.display_trap):
191
191
192 # if you run stuff with -c <cmd>, raw hist is not updated
192 # if you run stuff with -c <cmd>, raw hist is not updated
193 # ensure that it's in sync
193 # ensure that it's in sync
194 if len(self.input_hist) != len (self.input_hist_raw):
194 if len(self.input_hist) != len (self.input_hist_raw):
195 self.input_hist_raw = InputList(self.input_hist)
195 self.input_hist_raw = InputList(self.input_hist)
196
196
197 while 1:
197 while 1:
198 try:
198 try:
199 self.interact(display_banner=display_banner)
199 self.interact(display_banner=display_banner)
200 #self.interact_with_readline()
200 #self.interact_with_readline()
201 # XXX for testing of a readline-decoupled repl loop, call
201 # XXX for testing of a readline-decoupled repl loop, call
202 # interact_with_readline above
202 # interact_with_readline above
203 break
203 break
204 except KeyboardInterrupt:
204 except KeyboardInterrupt:
205 # this should not be necessary, but KeyboardInterrupt
205 # this should not be necessary, but KeyboardInterrupt
206 # handling seems rather unpredictable...
206 # handling seems rather unpredictable...
207 self.write("\nKeyboardInterrupt in interact()\n")
207 self.write("\nKeyboardInterrupt in interact()\n")
208
208
209 def interact(self, display_banner=None):
209 def interact(self, display_banner=None):
210 """Closely emulate the interactive Python console."""
210 """Closely emulate the interactive Python console."""
211
211
212 # batch run -> do not interact
212 # batch run -> do not interact
213 if self.exit_now:
213 if self.exit_now:
214 return
214 return
215
215
216 if display_banner is None:
216 if display_banner is None:
217 display_banner = self.display_banner
217 display_banner = self.display_banner
218 if display_banner:
218 if display_banner:
219 self.show_banner()
219 self.show_banner()
220
220
221 more = 0
221 more = 0
222
222
223 # Mark activity in the builtins
223 # Mark activity in the builtins
224 __builtin__.__dict__['__IPYTHON__active'] += 1
224 __builtin__.__dict__['__IPYTHON__active'] += 1
225
225
226 if self.has_readline:
226 if self.has_readline:
227 self.readline_startup_hook(self.pre_readline)
227 self.readline_startup_hook(self.pre_readline)
228 # exit_now is set by a call to %Exit or %Quit, through the
228 # exit_now is set by a call to %Exit or %Quit, through the
229 # ask_exit callback.
229 # ask_exit callback.
230
231 # Before showing any prompts, if the counter is at zero, we execute an
232 # empty line to ensure the user only sees prompts starting at one.
233 if self.execution_count == 0:
234 self.push_line('\n')
230
235
231 while not self.exit_now:
236 while not self.exit_now:
232 self.hooks.pre_prompt_hook()
237 self.hooks.pre_prompt_hook()
233 if more:
238 if more:
234 try:
239 try:
235 prompt = self.hooks.generate_prompt(True)
240 prompt = self.hooks.generate_prompt(True)
236 except:
241 except:
237 self.showtraceback()
242 self.showtraceback()
238 if self.autoindent:
243 if self.autoindent:
239 self.rl_do_indent = True
244 self.rl_do_indent = True
240
245
241 else:
246 else:
242 try:
247 try:
243 prompt = self.hooks.generate_prompt(False)
248 prompt = self.hooks.generate_prompt(False)
244 except:
249 except:
245 self.showtraceback()
250 self.showtraceback()
246 try:
251 try:
247 line = self.raw_input(prompt, more)
252 line = self.raw_input(prompt, more)
248 if self.exit_now:
253 if self.exit_now:
249 # quick exit on sys.std[in|out] close
254 # quick exit on sys.std[in|out] close
250 break
255 break
251 if self.autoindent:
256 if self.autoindent:
252 self.rl_do_indent = False
257 self.rl_do_indent = False
253
258
254 except KeyboardInterrupt:
259 except KeyboardInterrupt:
255 #double-guard against keyboardinterrupts during kbdint handling
260 #double-guard against keyboardinterrupts during kbdint handling
256 try:
261 try:
257 self.write('\nKeyboardInterrupt\n')
262 self.write('\nKeyboardInterrupt\n')
258 self.resetbuffer()
263 self.resetbuffer()
259 # keep cache in sync with the prompt counter:
264 # keep cache in sync with the prompt counter:
260 self.displayhook.prompt_count -= 1
265 self.displayhook.prompt_count -= 1
261
266
262 if self.autoindent:
267 if self.autoindent:
263 self.indent_current_nsp = 0
268 self.indent_current_nsp = 0
264 more = 0
269 more = 0
265 except KeyboardInterrupt:
270 except KeyboardInterrupt:
266 pass
271 pass
267 except EOFError:
272 except EOFError:
268 if self.autoindent:
273 if self.autoindent:
269 self.rl_do_indent = False
274 self.rl_do_indent = False
270 if self.has_readline:
275 if self.has_readline:
271 self.readline_startup_hook(None)
276 self.readline_startup_hook(None)
272 self.write('\n')
277 self.write('\n')
273 self.exit()
278 self.exit()
274 except bdb.BdbQuit:
279 except bdb.BdbQuit:
275 warn('The Python debugger has exited with a BdbQuit exception.\n'
280 warn('The Python debugger has exited with a BdbQuit exception.\n'
276 'Because of how pdb handles the stack, it is impossible\n'
281 'Because of how pdb handles the stack, it is impossible\n'
277 'for IPython to properly format this particular exception.\n'
282 'for IPython to properly format this particular exception.\n'
278 'IPython will resume normal operation.')
283 'IPython will resume normal operation.')
279 except:
284 except:
280 # exceptions here are VERY RARE, but they can be triggered
285 # exceptions here are VERY RARE, but they can be triggered
281 # asynchronously by signal handlers, for example.
286 # asynchronously by signal handlers, for example.
282 self.showtraceback()
287 self.showtraceback()
283 else:
288 else:
284 more = self.push_line(line)
289 more = self.push_line(line)
285 if (self.SyntaxTB.last_syntax_error and
290 if (self.SyntaxTB.last_syntax_error and
286 self.autoedit_syntax):
291 self.autoedit_syntax):
287 self.edit_syntax_error()
292 self.edit_syntax_error()
288
293
289 # We are off again...
294 # We are off again...
290 __builtin__.__dict__['__IPYTHON__active'] -= 1
295 __builtin__.__dict__['__IPYTHON__active'] -= 1
291
296
292 # Turn off the exit flag, so the mainloop can be restarted if desired
297 # Turn off the exit flag, so the mainloop can be restarted if desired
293 self.exit_now = False
298 self.exit_now = False
294
299
295 def raw_input(self,prompt='',continue_prompt=False):
300 def raw_input(self,prompt='',continue_prompt=False):
296 """Write a prompt and read a line.
301 """Write a prompt and read a line.
297
302
298 The returned line does not include the trailing newline.
303 The returned line does not include the trailing newline.
299 When the user enters the EOF key sequence, EOFError is raised.
304 When the user enters the EOF key sequence, EOFError is raised.
300
305
301 Optional inputs:
306 Optional inputs:
302
307
303 - prompt(''): a string to be printed to prompt the user.
308 - prompt(''): a string to be printed to prompt the user.
304
309
305 - continue_prompt(False): whether this line is the first one or a
310 - continue_prompt(False): whether this line is the first one or a
306 continuation in a sequence of inputs.
311 continuation in a sequence of inputs.
307 """
312 """
308 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
313 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
309
314
310 # Code run by the user may have modified the readline completer state.
315 # Code run by the user may have modified the readline completer state.
311 # We must ensure that our completer is back in place.
316 # We must ensure that our completer is back in place.
312
317
313 if self.has_readline:
318 if self.has_readline:
314 self.set_readline_completer()
319 self.set_readline_completer()
315
320
316 try:
321 try:
317 line = raw_input_original(prompt).decode(self.stdin_encoding)
322 line = raw_input_original(prompt).decode(self.stdin_encoding)
318 except ValueError:
323 except ValueError:
319 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
324 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
320 " or sys.stdout.close()!\nExiting IPython!")
325 " or sys.stdout.close()!\nExiting IPython!")
321 self.ask_exit()
326 self.ask_exit()
322 return ""
327 return ""
323
328
324 # Try to be reasonably smart about not re-indenting pasted input more
329 # Try to be reasonably smart about not re-indenting pasted input more
325 # than necessary. We do this by trimming out the auto-indent initial
330 # than necessary. We do this by trimming out the auto-indent initial
326 # spaces, if the user's actual input started itself with whitespace.
331 # spaces, if the user's actual input started itself with whitespace.
327 #debugx('self.buffer[-1]')
332 #debugx('self.buffer[-1]')
328
333
329 if self.autoindent:
334 if self.autoindent:
330 if num_ini_spaces(line) > self.indent_current_nsp:
335 if num_ini_spaces(line) > self.indent_current_nsp:
331 line = line[self.indent_current_nsp:]
336 line = line[self.indent_current_nsp:]
332 self.indent_current_nsp = 0
337 self.indent_current_nsp = 0
333
338
334 # store the unfiltered input before the user has any chance to modify
339 # store the unfiltered input before the user has any chance to modify
335 # it.
340 # it.
336 if line.strip():
341 if line.strip():
337 if continue_prompt:
342 if continue_prompt:
338 self.input_hist_raw[-1] += '%s\n' % line
343 self.input_hist_raw[-1] += '%s\n' % line
339 if self.has_readline and self.readline_use:
344 if self.has_readline and self.readline_use:
340 try:
345 try:
341 histlen = self.readline.get_current_history_length()
346 histlen = self.readline.get_current_history_length()
342 if histlen > 1:
347 if histlen > 1:
343 newhist = self.input_hist_raw[-1].rstrip()
348 newhist = self.input_hist_raw[-1].rstrip()
344 self.readline.remove_history_item(histlen-1)
349 self.readline.remove_history_item(histlen-1)
345 self.readline.replace_history_item(histlen-2,
350 self.readline.replace_history_item(histlen-2,
346 newhist.encode(self.stdin_encoding))
351 newhist.encode(self.stdin_encoding))
347 except AttributeError:
352 except AttributeError:
348 pass # re{move,place}_history_item are new in 2.4.
353 pass # re{move,place}_history_item are new in 2.4.
349 else:
354 else:
350 self.input_hist_raw.append('%s\n' % line)
355 self.input_hist_raw.append('%s\n' % line)
351 # only entries starting at first column go to shadow history
356 # only entries starting at first column go to shadow history
352 if line.lstrip() == line:
357 if line.lstrip() == line:
353 self.shadowhist.add(line.strip())
358 self.shadowhist.add(line.strip())
354 elif not continue_prompt:
359 elif not continue_prompt:
355 self.input_hist_raw.append('\n')
360 self.input_hist_raw.append('\n')
356 try:
361 try:
357 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
362 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
358 except:
363 except:
359 # blanket except, in case a user-defined prefilter crashes, so it
364 # blanket except, in case a user-defined prefilter crashes, so it
360 # can't take all of ipython with it.
365 # can't take all of ipython with it.
361 self.showtraceback()
366 self.showtraceback()
362 return ''
367 return ''
363 else:
368 else:
364 return lineout
369 return lineout
365
370
366 # TODO: The following three methods are an early attempt to refactor
371 # TODO: The following three methods are an early attempt to refactor
367 # the main code execution logic. We don't use them, but they may be
372 # the main code execution logic. We don't use them, but they may be
368 # helpful when we refactor the code execution logic further.
373 # helpful when we refactor the code execution logic further.
369 # def interact_prompt(self):
374 # def interact_prompt(self):
370 # """ Print the prompt (in read-eval-print loop)
375 # """ Print the prompt (in read-eval-print loop)
371 #
376 #
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
377 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
373 # used in standard IPython flow.
378 # used in standard IPython flow.
374 # """
379 # """
375 # if self.more:
380 # if self.more:
376 # try:
381 # try:
377 # prompt = self.hooks.generate_prompt(True)
382 # prompt = self.hooks.generate_prompt(True)
378 # except:
383 # except:
379 # self.showtraceback()
384 # self.showtraceback()
380 # if self.autoindent:
385 # if self.autoindent:
381 # self.rl_do_indent = True
386 # self.rl_do_indent = True
382 #
387 #
383 # else:
388 # else:
384 # try:
389 # try:
385 # prompt = self.hooks.generate_prompt(False)
390 # prompt = self.hooks.generate_prompt(False)
386 # except:
391 # except:
387 # self.showtraceback()
392 # self.showtraceback()
388 # self.write(prompt)
393 # self.write(prompt)
389 #
394 #
390 # def interact_handle_input(self,line):
395 # def interact_handle_input(self,line):
391 # """ Handle the input line (in read-eval-print loop)
396 # """ Handle the input line (in read-eval-print loop)
392 #
397 #
393 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
398 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
394 # used in standard IPython flow.
399 # used in standard IPython flow.
395 # """
400 # """
396 # if line.lstrip() == line:
401 # if line.lstrip() == line:
397 # self.shadowhist.add(line.strip())
402 # self.shadowhist.add(line.strip())
398 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
403 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
399 #
404 #
400 # if line.strip():
405 # if line.strip():
401 # if self.more:
406 # if self.more:
402 # self.input_hist_raw[-1] += '%s\n' % line
407 # self.input_hist_raw[-1] += '%s\n' % line
403 # else:
408 # else:
404 # self.input_hist_raw.append('%s\n' % line)
409 # self.input_hist_raw.append('%s\n' % line)
405 #
410 #
406 #
411 #
407 # self.more = self.push_line(lineout)
412 # self.more = self.push_line(lineout)
408 # if (self.SyntaxTB.last_syntax_error and
413 # if (self.SyntaxTB.last_syntax_error and
409 # self.autoedit_syntax):
414 # self.autoedit_syntax):
410 # self.edit_syntax_error()
415 # self.edit_syntax_error()
411 #
416 #
412 # def interact_with_readline(self):
417 # def interact_with_readline(self):
413 # """ Demo of using interact_handle_input, interact_prompt
418 # """ Demo of using interact_handle_input, interact_prompt
414 #
419 #
415 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
420 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
416 # it should work like this.
421 # it should work like this.
417 # """
422 # """
418 # self.readline_startup_hook(self.pre_readline)
423 # self.readline_startup_hook(self.pre_readline)
419 # while not self.exit_now:
424 # while not self.exit_now:
420 # self.interact_prompt()
425 # self.interact_prompt()
421 # if self.more:
426 # if self.more:
422 # self.rl_do_indent = True
427 # self.rl_do_indent = True
423 # else:
428 # else:
424 # self.rl_do_indent = False
429 # self.rl_do_indent = False
425 # line = raw_input_original().decode(self.stdin_encoding)
430 # line = raw_input_original().decode(self.stdin_encoding)
426 # self.interact_handle_input(line)
431 # self.interact_handle_input(line)
427
432
428 #-------------------------------------------------------------------------
433 #-------------------------------------------------------------------------
429 # Methods to support auto-editing of SyntaxErrors.
434 # Methods to support auto-editing of SyntaxErrors.
430 #-------------------------------------------------------------------------
435 #-------------------------------------------------------------------------
431
436
432 def edit_syntax_error(self):
437 def edit_syntax_error(self):
433 """The bottom half of the syntax error handler called in the main loop.
438 """The bottom half of the syntax error handler called in the main loop.
434
439
435 Loop until syntax error is fixed or user cancels.
440 Loop until syntax error is fixed or user cancels.
436 """
441 """
437
442
438 while self.SyntaxTB.last_syntax_error:
443 while self.SyntaxTB.last_syntax_error:
439 # copy and clear last_syntax_error
444 # copy and clear last_syntax_error
440 err = self.SyntaxTB.clear_err_state()
445 err = self.SyntaxTB.clear_err_state()
441 if not self._should_recompile(err):
446 if not self._should_recompile(err):
442 return
447 return
443 try:
448 try:
444 # may set last_syntax_error again if a SyntaxError is raised
449 # may set last_syntax_error again if a SyntaxError is raised
445 self.safe_execfile(err.filename,self.user_ns)
450 self.safe_execfile(err.filename,self.user_ns)
446 except:
451 except:
447 self.showtraceback()
452 self.showtraceback()
448 else:
453 else:
449 try:
454 try:
450 f = file(err.filename)
455 f = file(err.filename)
451 try:
456 try:
452 # This should be inside a display_trap block and I
457 # This should be inside a display_trap block and I
453 # think it is.
458 # think it is.
454 sys.displayhook(f.read())
459 sys.displayhook(f.read())
455 finally:
460 finally:
456 f.close()
461 f.close()
457 except:
462 except:
458 self.showtraceback()
463 self.showtraceback()
459
464
460 def _should_recompile(self,e):
465 def _should_recompile(self,e):
461 """Utility routine for edit_syntax_error"""
466 """Utility routine for edit_syntax_error"""
462
467
463 if e.filename in ('<ipython console>','<input>','<string>',
468 if e.filename in ('<ipython console>','<input>','<string>',
464 '<console>','<BackgroundJob compilation>',
469 '<console>','<BackgroundJob compilation>',
465 None):
470 None):
466
471
467 return False
472 return False
468 try:
473 try:
469 if (self.autoedit_syntax and
474 if (self.autoedit_syntax and
470 not self.ask_yes_no('Return to editor to correct syntax error? '
475 not self.ask_yes_no('Return to editor to correct syntax error? '
471 '[Y/n] ','y')):
476 '[Y/n] ','y')):
472 return False
477 return False
473 except EOFError:
478 except EOFError:
474 return False
479 return False
475
480
476 def int0(x):
481 def int0(x):
477 try:
482 try:
478 return int(x)
483 return int(x)
479 except TypeError:
484 except TypeError:
480 return 0
485 return 0
481 # always pass integer line and offset values to editor hook
486 # always pass integer line and offset values to editor hook
482 try:
487 try:
483 self.hooks.fix_error_editor(e.filename,
488 self.hooks.fix_error_editor(e.filename,
484 int0(e.lineno),int0(e.offset),e.msg)
489 int0(e.lineno),int0(e.offset),e.msg)
485 except TryNext:
490 except TryNext:
486 warn('Could not open editor')
491 warn('Could not open editor')
487 return False
492 return False
488 return True
493 return True
489
494
490 #-------------------------------------------------------------------------
495 #-------------------------------------------------------------------------
491 # Things related to GUI support and pylab
496 # Things related to GUI support and pylab
492 #-------------------------------------------------------------------------
497 #-------------------------------------------------------------------------
493
498
494 def enable_pylab(self, gui=None):
499 def enable_pylab(self, gui=None):
495 """Activate pylab support at runtime.
500 """Activate pylab support at runtime.
496
501
497 This turns on support for matplotlib, preloads into the interactive
502 This turns on support for matplotlib, preloads into the interactive
498 namespace all of numpy and pylab, and configures IPython to correcdtly
503 namespace all of numpy and pylab, and configures IPython to correcdtly
499 interact with the GUI event loop. The GUI backend to be used can be
504 interact with the GUI event loop. The GUI backend to be used can be
500 optionally selected with the optional :param:`gui` argument.
505 optionally selected with the optional :param:`gui` argument.
501
506
502 Parameters
507 Parameters
503 ----------
508 ----------
504 gui : optional, string
509 gui : optional, string
505
510
506 If given, dictates the choice of matplotlib GUI backend to use
511 If given, dictates the choice of matplotlib GUI backend to use
507 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
512 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
508 'gtk'), otherwise we use the default chosen by matplotlib (as
513 'gtk'), otherwise we use the default chosen by matplotlib (as
509 dictated by the matplotlib build-time options plus the user's
514 dictated by the matplotlib build-time options plus the user's
510 matplotlibrc configuration file).
515 matplotlibrc configuration file).
511 """
516 """
512 # We want to prevent the loading of pylab to pollute the user's
517 # We want to prevent the loading of pylab to pollute the user's
513 # namespace as shown by the %who* magics, so we execute the activation
518 # namespace as shown by the %who* magics, so we execute the activation
514 # code in an empty namespace, and we update *both* user_ns and
519 # code in an empty namespace, and we update *both* user_ns and
515 # user_ns_hidden with this information.
520 # user_ns_hidden with this information.
516 ns = {}
521 ns = {}
517 gui = pylab_activate(ns, gui)
522 gui = pylab_activate(ns, gui)
518 self.user_ns.update(ns)
523 self.user_ns.update(ns)
519 self.user_ns_hidden.update(ns)
524 self.user_ns_hidden.update(ns)
520 # Now we must activate the gui pylab wants to use, and fix %run to take
525 # Now we must activate the gui pylab wants to use, and fix %run to take
521 # plot updates into account
526 # plot updates into account
522 enable_gui(gui)
527 enable_gui(gui)
523 self.magic_run = self._pylab_magic_run
528 self.magic_run = self._pylab_magic_run
524
529
525 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
526 # Things related to exiting
531 # Things related to exiting
527 #-------------------------------------------------------------------------
532 #-------------------------------------------------------------------------
528
533
529 def ask_exit(self):
534 def ask_exit(self):
530 """ Ask the shell to exit. Can be overiden and used as a callback. """
535 """ Ask the shell to exit. Can be overiden and used as a callback. """
531 self.exit_now = True
536 self.exit_now = True
532
537
533 def exit(self):
538 def exit(self):
534 """Handle interactive exit.
539 """Handle interactive exit.
535
540
536 This method calls the ask_exit callback."""
541 This method calls the ask_exit callback."""
537 if self.confirm_exit:
542 if self.confirm_exit:
538 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
543 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
539 self.ask_exit()
544 self.ask_exit()
540 else:
545 else:
541 self.ask_exit()
546 self.ask_exit()
542
547
543 #------------------------------------------------------------------------
548 #------------------------------------------------------------------------
544 # Magic overrides
549 # Magic overrides
545 #------------------------------------------------------------------------
550 #------------------------------------------------------------------------
546 # Once the base class stops inheriting from magic, this code needs to be
551 # Once the base class stops inheriting from magic, this code needs to be
547 # moved into a separate machinery as well. For now, at least isolate here
552 # moved into a separate machinery as well. For now, at least isolate here
548 # the magics which this class needs to implement differently from the base
553 # the magics which this class needs to implement differently from the base
549 # class, or that are unique to it.
554 # class, or that are unique to it.
550
555
551 def magic_autoindent(self, parameter_s = ''):
556 def magic_autoindent(self, parameter_s = ''):
552 """Toggle autoindent on/off (if available)."""
557 """Toggle autoindent on/off (if available)."""
553
558
554 self.shell.set_autoindent()
559 self.shell.set_autoindent()
555 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
560 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
556
561
557 def magic_cpaste(self, parameter_s=''):
562 def magic_cpaste(self, parameter_s=''):
558 """Paste & execute a pre-formatted code block from clipboard.
563 """Paste & execute a pre-formatted code block from clipboard.
559
564
560 You must terminate the block with '--' (two minus-signs) alone on the
565 You must terminate the block with '--' (two minus-signs) alone on the
561 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
566 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
562 is the new sentinel for this operation)
567 is the new sentinel for this operation)
563
568
564 The block is dedented prior to execution to enable execution of method
569 The block is dedented prior to execution to enable execution of method
565 definitions. '>' and '+' characters at the beginning of a line are
570 definitions. '>' and '+' characters at the beginning of a line are
566 ignored, to allow pasting directly from e-mails, diff files and
571 ignored, to allow pasting directly from e-mails, diff files and
567 doctests (the '...' continuation prompt is also stripped). The
572 doctests (the '...' continuation prompt is also stripped). The
568 executed block is also assigned to variable named 'pasted_block' for
573 executed block is also assigned to variable named 'pasted_block' for
569 later editing with '%edit pasted_block'.
574 later editing with '%edit pasted_block'.
570
575
571 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
576 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
572 This assigns the pasted block to variable 'foo' as string, without
577 This assigns the pasted block to variable 'foo' as string, without
573 dedenting or executing it (preceding >>> and + is still stripped)
578 dedenting or executing it (preceding >>> and + is still stripped)
574
579
575 '%cpaste -r' re-executes the block previously entered by cpaste.
580 '%cpaste -r' re-executes the block previously entered by cpaste.
576
581
577 Do not be alarmed by garbled output on Windows (it's a readline bug).
582 Do not be alarmed by garbled output on Windows (it's a readline bug).
578 Just press enter and type -- (and press enter again) and the block
583 Just press enter and type -- (and press enter again) and the block
579 will be what was just pasted.
584 will be what was just pasted.
580
585
581 IPython statements (magics, shell escapes) are not supported (yet).
586 IPython statements (magics, shell escapes) are not supported (yet).
582
587
583 See also
588 See also
584 --------
589 --------
585 paste: automatically pull code from clipboard.
590 paste: automatically pull code from clipboard.
586 """
591 """
587
592
588 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
593 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
589 par = args.strip()
594 par = args.strip()
590 if opts.has_key('r'):
595 if opts.has_key('r'):
591 self._rerun_pasted()
596 self._rerun_pasted()
592 return
597 return
593
598
594 sentinel = opts.get('s','--')
599 sentinel = opts.get('s','--')
595
600
596 block = self._strip_pasted_lines_for_code(
601 block = self._strip_pasted_lines_for_code(
597 self._get_pasted_lines(sentinel))
602 self._get_pasted_lines(sentinel))
598
603
599 self._execute_block(block, par)
604 self._execute_block(block, par)
600
605
601 def magic_paste(self, parameter_s=''):
606 def magic_paste(self, parameter_s=''):
602 """Paste & execute a pre-formatted code block from clipboard.
607 """Paste & execute a pre-formatted code block from clipboard.
603
608
604 The text is pulled directly from the clipboard without user
609 The text is pulled directly from the clipboard without user
605 intervention and printed back on the screen before execution (unless
610 intervention and printed back on the screen before execution (unless
606 the -q flag is given to force quiet mode).
611 the -q flag is given to force quiet mode).
607
612
608 The block is dedented prior to execution to enable execution of method
613 The block is dedented prior to execution to enable execution of method
609 definitions. '>' and '+' characters at the beginning of a line are
614 definitions. '>' and '+' characters at the beginning of a line are
610 ignored, to allow pasting directly from e-mails, diff files and
615 ignored, to allow pasting directly from e-mails, diff files and
611 doctests (the '...' continuation prompt is also stripped). The
616 doctests (the '...' continuation prompt is also stripped). The
612 executed block is also assigned to variable named 'pasted_block' for
617 executed block is also assigned to variable named 'pasted_block' for
613 later editing with '%edit pasted_block'.
618 later editing with '%edit pasted_block'.
614
619
615 You can also pass a variable name as an argument, e.g. '%paste foo'.
620 You can also pass a variable name as an argument, e.g. '%paste foo'.
616 This assigns the pasted block to variable 'foo' as string, without
621 This assigns the pasted block to variable 'foo' as string, without
617 dedenting or executing it (preceding >>> and + is still stripped)
622 dedenting or executing it (preceding >>> and + is still stripped)
618
623
619 Options
624 Options
620 -------
625 -------
621
626
622 -r: re-executes the block previously entered by cpaste.
627 -r: re-executes the block previously entered by cpaste.
623
628
624 -q: quiet mode: do not echo the pasted text back to the terminal.
629 -q: quiet mode: do not echo the pasted text back to the terminal.
625
630
626 IPython statements (magics, shell escapes) are not supported (yet).
631 IPython statements (magics, shell escapes) are not supported (yet).
627
632
628 See also
633 See also
629 --------
634 --------
630 cpaste: manually paste code into terminal until you mark its end.
635 cpaste: manually paste code into terminal until you mark its end.
631 """
636 """
632 opts,args = self.parse_options(parameter_s,'rq',mode='string')
637 opts,args = self.parse_options(parameter_s,'rq',mode='string')
633 par = args.strip()
638 par = args.strip()
634 if opts.has_key('r'):
639 if opts.has_key('r'):
635 self._rerun_pasted()
640 self._rerun_pasted()
636 return
641 return
637
642
638 text = self.shell.hooks.clipboard_get()
643 text = self.shell.hooks.clipboard_get()
639 block = self._strip_pasted_lines_for_code(text.splitlines())
644 block = self._strip_pasted_lines_for_code(text.splitlines())
640
645
641 # By default, echo back to terminal unless quiet mode is requested
646 # By default, echo back to terminal unless quiet mode is requested
642 if not opts.has_key('q'):
647 if not opts.has_key('q'):
643 write = self.shell.write
648 write = self.shell.write
644 write(self.shell.pycolorize(block))
649 write(self.shell.pycolorize(block))
645 if not block.endswith('\n'):
650 if not block.endswith('\n'):
646 write('\n')
651 write('\n')
647 write("## -- End pasted text --\n")
652 write("## -- End pasted text --\n")
648
653
649 self._execute_block(block, par)
654 self._execute_block(block, par)
650
655
651
656
652 InteractiveShellABC.register(TerminalInteractiveShell)
657 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,626 +1,627 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import atexit
20 import atexit
21 import sys
21 import sys
22 import time
22 import time
23 import traceback
23 import traceback
24
24
25 # System library imports.
25 # System library imports.
26 import zmq
26 import zmq
27
27
28 # Local imports.
28 # Local imports.
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.utils import io
30 from IPython.utils import io
31 from IPython.utils.jsonutil import json_clean
31 from IPython.utils.jsonutil import json_clean
32 from IPython.lib import pylabtools
32 from IPython.lib import pylabtools
33 from IPython.utils.traitlets import Instance, Float
33 from IPython.utils.traitlets import Instance, Float
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
34 from entry_point import (base_launch_kernel, make_argument_parser, make_kernel,
35 start_kernel)
35 start_kernel)
36 from iostream import OutStream
36 from iostream import OutStream
37 from session import Session, Message
37 from session import Session, Message
38 from zmqshell import ZMQInteractiveShell
38 from zmqshell import ZMQInteractiveShell
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Main kernel class
41 # Main kernel class
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class Kernel(Configurable):
44 class Kernel(Configurable):
45
45
46 #---------------------------------------------------------------------------
46 #---------------------------------------------------------------------------
47 # Kernel interface
47 # Kernel interface
48 #---------------------------------------------------------------------------
48 #---------------------------------------------------------------------------
49
49
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 session = Instance(Session)
51 session = Instance(Session)
52 reply_socket = Instance('zmq.Socket')
52 reply_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
55
55
56 # Private interface
56 # Private interface
57
57
58 # Time to sleep after flushing the stdout/err buffers in each execute
58 # Time to sleep after flushing the stdout/err buffers in each execute
59 # cycle. While this introduces a hard limit on the minimal latency of the
59 # cycle. While this introduces a hard limit on the minimal latency of the
60 # execute cycle, it helps prevent output synchronization problems for
60 # execute cycle, it helps prevent output synchronization problems for
61 # clients.
61 # clients.
62 # Units are in seconds. The minimum zmq latency on local host is probably
62 # Units are in seconds. The minimum zmq latency on local host is probably
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 # a little if it's not enough after more interactive testing.
64 # a little if it's not enough after more interactive testing.
65 _execute_sleep = Float(0.0005, config=True)
65 _execute_sleep = Float(0.0005, config=True)
66
66
67 # Frequency of the kernel's event loop.
67 # Frequency of the kernel's event loop.
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 # adapt to milliseconds.
69 # adapt to milliseconds.
70 _poll_interval = Float(0.05, config=True)
70 _poll_interval = Float(0.05, config=True)
71
71
72 # If the shutdown was requested over the network, we leave here the
72 # If the shutdown was requested over the network, we leave here the
73 # necessary reply message so it can be sent by our registered atexit
73 # necessary reply message so it can be sent by our registered atexit
74 # handler. This ensures that the reply is only sent to clients truly at
74 # handler. This ensures that the reply is only sent to clients truly at
75 # the end of our shutdown process (which happens after the underlying
75 # the end of our shutdown process (which happens after the underlying
76 # IPython shell's own shutdown).
76 # IPython shell's own shutdown).
77 _shutdown_message = None
77 _shutdown_message = None
78
78
79 # This is a dict of port number that the kernel is listening on. It is set
79 # This is a dict of port number that the kernel is listening on. It is set
80 # by record_ports and used by connect_request.
80 # by record_ports and used by connect_request.
81 _recorded_ports = None
81 _recorded_ports = None
82
82
83 def __init__(self, **kwargs):
83 def __init__(self, **kwargs):
84 super(Kernel, self).__init__(**kwargs)
84 super(Kernel, self).__init__(**kwargs)
85
85
86 # Before we even start up the shell, register *first* our exit handlers
86 # Before we even start up the shell, register *first* our exit handlers
87 # so they come before the shell's
87 # so they come before the shell's
88 atexit.register(self._at_shutdown)
88 atexit.register(self._at_shutdown)
89
89
90 # Initialize the InteractiveShell subclass
90 # Initialize the InteractiveShell subclass
91 self.shell = ZMQInteractiveShell.instance()
91 self.shell = ZMQInteractiveShell.instance()
92 self.shell.displayhook.session = self.session
92 self.shell.displayhook.session = self.session
93 self.shell.displayhook.pub_socket = self.pub_socket
93 self.shell.displayhook.pub_socket = self.pub_socket
94
94
95 # TMP - hack while developing
95 # TMP - hack while developing
96 self.shell._reply_content = None
96 self.shell._reply_content = None
97
97
98 # Build dict of handlers for message types
98 # Build dict of handlers for message types
99 msg_types = [ 'execute_request', 'complete_request',
99 msg_types = [ 'execute_request', 'complete_request',
100 'object_info_request', 'history_request',
100 'object_info_request', 'history_request',
101 'connect_request', 'shutdown_request']
101 'connect_request', 'shutdown_request']
102 self.handlers = {}
102 self.handlers = {}
103 for msg_type in msg_types:
103 for msg_type in msg_types:
104 self.handlers[msg_type] = getattr(self, msg_type)
104 self.handlers[msg_type] = getattr(self, msg_type)
105
105
106 def do_one_iteration(self):
106 def do_one_iteration(self):
107 """Do one iteration of the kernel's evaluation loop.
107 """Do one iteration of the kernel's evaluation loop.
108 """
108 """
109 try:
109 try:
110 ident = self.reply_socket.recv(zmq.NOBLOCK)
110 ident = self.reply_socket.recv(zmq.NOBLOCK)
111 except zmq.ZMQError, e:
111 except zmq.ZMQError, e:
112 if e.errno == zmq.EAGAIN:
112 if e.errno == zmq.EAGAIN:
113 return
113 return
114 else:
114 else:
115 raise
115 raise
116 # FIXME: Bug in pyzmq/zmq?
116 # FIXME: Bug in pyzmq/zmq?
117 # assert self.reply_socket.rcvmore(), "Missing message part."
117 # assert self.reply_socket.rcvmore(), "Missing message part."
118 msg = self.reply_socket.recv_json()
118 msg = self.reply_socket.recv_json()
119
119
120 # Print some info about this message and leave a '--->' marker, so it's
120 # Print some info about this message and leave a '--->' marker, so it's
121 # easier to trace visually the message chain when debugging. Each
121 # easier to trace visually the message chain when debugging. Each
122 # handler prints its message at the end.
122 # handler prints its message at the end.
123 # Eventually we'll move these from stdout to a logger.
123 # Eventually we'll move these from stdout to a logger.
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
124 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
125 io.raw_print(' Content: ', msg['content'],
125 io.raw_print(' Content: ', msg['content'],
126 '\n --->\n ', sep='', end='')
126 '\n --->\n ', sep='', end='')
127
127
128 # Find and call actual handler for message
128 # Find and call actual handler for message
129 handler = self.handlers.get(msg['msg_type'], None)
129 handler = self.handlers.get(msg['msg_type'], None)
130 if handler is None:
130 if handler is None:
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
131 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
132 else:
132 else:
133 handler(ident, msg)
133 handler(ident, msg)
134
134
135 # Check whether we should exit, in case the incoming message set the
135 # Check whether we should exit, in case the incoming message set the
136 # exit flag on
136 # exit flag on
137 if self.shell.exit_now:
137 if self.shell.exit_now:
138 io.raw_print('\nExiting IPython kernel...')
138 io.raw_print('\nExiting IPython kernel...')
139 # We do a normal, clean exit, which allows any actions registered
139 # We do a normal, clean exit, which allows any actions registered
140 # via atexit (such as history saving) to take place.
140 # via atexit (such as history saving) to take place.
141 sys.exit(0)
141 sys.exit(0)
142
142
143
143
144 def start(self):
144 def start(self):
145 """ Start the kernel main loop.
145 """ Start the kernel main loop.
146 """
146 """
147 while True:
147 while True:
148 time.sleep(self._poll_interval)
148 time.sleep(self._poll_interval)
149 self.do_one_iteration()
149 self.do_one_iteration()
150
150
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
151 def record_ports(self, xrep_port, pub_port, req_port, hb_port):
152 """Record the ports that this kernel is using.
152 """Record the ports that this kernel is using.
153
153
154 The creator of the Kernel instance must call this methods if they
154 The creator of the Kernel instance must call this methods if they
155 want the :meth:`connect_request` method to return the port numbers.
155 want the :meth:`connect_request` method to return the port numbers.
156 """
156 """
157 self._recorded_ports = {
157 self._recorded_ports = {
158 'xrep_port' : xrep_port,
158 'xrep_port' : xrep_port,
159 'pub_port' : pub_port,
159 'pub_port' : pub_port,
160 'req_port' : req_port,
160 'req_port' : req_port,
161 'hb_port' : hb_port
161 'hb_port' : hb_port
162 }
162 }
163
163
164 #---------------------------------------------------------------------------
164 #---------------------------------------------------------------------------
165 # Kernel request handlers
165 # Kernel request handlers
166 #---------------------------------------------------------------------------
166 #---------------------------------------------------------------------------
167
167
168 def _publish_pyin(self, code, parent):
168 def _publish_pyin(self, code, parent):
169 """Publish the code request on the pyin stream."""
169 """Publish the code request on the pyin stream."""
170
170
171 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
171 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
172 self.pub_socket.send_json(pyin_msg)
172 self.pub_socket.send_json(pyin_msg)
173
173
174 def execute_request(self, ident, parent):
174 def execute_request(self, ident, parent):
175
175
176 status_msg = self.session.msg(
176 status_msg = self.session.msg(
177 u'status',
177 u'status',
178 {u'execution_state':u'busy'},
178 {u'execution_state':u'busy'},
179 parent=parent
179 parent=parent
180 )
180 )
181 self.pub_socket.send_json(status_msg)
181 self.pub_socket.send_json(status_msg)
182
182
183 try:
183 try:
184 content = parent[u'content']
184 content = parent[u'content']
185 code = content[u'code']
185 code = content[u'code']
186 silent = content[u'silent']
186 silent = content[u'silent']
187 except:
187 except:
188 io.raw_print_err("Got bad msg: ")
188 io.raw_print_err("Got bad msg: ")
189 io.raw_print_err(Message(parent))
189 io.raw_print_err(Message(parent))
190 return
190 return
191
191
192 shell = self.shell # we'll need this a lot here
192 shell = self.shell # we'll need this a lot here
193
193
194 # Replace raw_input. Note that is not sufficient to replace
194 # Replace raw_input. Note that is not sufficient to replace
195 # raw_input in the user namespace.
195 # raw_input in the user namespace.
196 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
196 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
197 __builtin__.raw_input = raw_input
197 __builtin__.raw_input = raw_input
198
198
199 # Set the parent message of the display hook and out streams.
199 # Set the parent message of the display hook and out streams.
200 shell.displayhook.set_parent(parent)
200 shell.displayhook.set_parent(parent)
201 sys.stdout.set_parent(parent)
201 sys.stdout.set_parent(parent)
202 sys.stderr.set_parent(parent)
202 sys.stderr.set_parent(parent)
203
203
204 # Re-broadcast our input for the benefit of listening clients, and
204 # Re-broadcast our input for the benefit of listening clients, and
205 # start computing output
205 # start computing output
206 if not silent:
206 if not silent:
207 self._publish_pyin(code, parent)
207 self._publish_pyin(code, parent)
208
208
209 reply_content = {}
209 reply_content = {}
210 try:
210 try:
211 if silent:
211 if silent:
212 # runcode uses 'exec' mode, so no displayhook will fire, and it
212 # runcode uses 'exec' mode, so no displayhook will fire, and it
213 # doesn't call logging or history manipulations. Print
213 # doesn't call logging or history manipulations. Print
214 # statements in that code will obviously still execute.
214 # statements in that code will obviously still execute.
215 shell.runcode(code)
215 shell.runcode(code)
216 else:
216 else:
217 # FIXME: runlines calls the exception handler itself.
217 # FIXME: runlines calls the exception handler itself.
218 shell._reply_content = None
218 shell._reply_content = None
219
219
220 # For now leave this here until we're sure we can stop using it
220 # For now leave this here until we're sure we can stop using it
221 #shell.runlines(code)
221 #shell.runlines(code)
222
222
223 # Experimental: cell mode! Test more before turning into
223 # Experimental: cell mode! Test more before turning into
224 # default and removing the hacks around runlines.
224 # default and removing the hacks around runlines.
225 shell.run_cell(code)
225 shell.run_cell(code)
226 except:
226 except:
227 status = u'error'
227 status = u'error'
228 # FIXME: this code right now isn't being used yet by default,
228 # FIXME: this code right now isn't being used yet by default,
229 # because the runlines() call above directly fires off exception
229 # because the runlines() call above directly fires off exception
230 # reporting. This code, therefore, is only active in the scenario
230 # reporting. This code, therefore, is only active in the scenario
231 # where runlines itself has an unhandled exception. We need to
231 # where runlines itself has an unhandled exception. We need to
232 # uniformize this, for all exception construction to come from a
232 # uniformize this, for all exception construction to come from a
233 # single location in the codbase.
233 # single location in the codbase.
234 etype, evalue, tb = sys.exc_info()
234 etype, evalue, tb = sys.exc_info()
235 tb_list = traceback.format_exception(etype, evalue, tb)
235 tb_list = traceback.format_exception(etype, evalue, tb)
236 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
236 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
237 else:
237 else:
238 status = u'ok'
238 status = u'ok'
239
239
240 reply_content[u'status'] = status
240 reply_content[u'status'] = status
241 # Compute the execution counter so clients can display prompts
241
242 reply_content['execution_count'] = shell.displayhook.prompt_count
242 # Return the execution counter so clients can display prompts
243 reply_content['execution_count'] = shell.execution_count
243
244
244 # FIXME - fish exception info out of shell, possibly left there by
245 # FIXME - fish exception info out of shell, possibly left there by
245 # runlines. We'll need to clean up this logic later.
246 # runlines. We'll need to clean up this logic later.
246 if shell._reply_content is not None:
247 if shell._reply_content is not None:
247 reply_content.update(shell._reply_content)
248 reply_content.update(shell._reply_content)
248
249
249 # At this point, we can tell whether the main code execution succeeded
250 # At this point, we can tell whether the main code execution succeeded
250 # or not. If it did, we proceed to evaluate user_variables/expressions
251 # or not. If it did, we proceed to evaluate user_variables/expressions
251 if reply_content['status'] == 'ok':
252 if reply_content['status'] == 'ok':
252 reply_content[u'user_variables'] = \
253 reply_content[u'user_variables'] = \
253 shell.user_variables(content[u'user_variables'])
254 shell.user_variables(content[u'user_variables'])
254 reply_content[u'user_expressions'] = \
255 reply_content[u'user_expressions'] = \
255 shell.user_expressions(content[u'user_expressions'])
256 shell.user_expressions(content[u'user_expressions'])
256 else:
257 else:
257 # If there was an error, don't even try to compute variables or
258 # If there was an error, don't even try to compute variables or
258 # expressions
259 # expressions
259 reply_content[u'user_variables'] = {}
260 reply_content[u'user_variables'] = {}
260 reply_content[u'user_expressions'] = {}
261 reply_content[u'user_expressions'] = {}
261
262
262 # Payloads should be retrieved regardless of outcome, so we can both
263 # Payloads should be retrieved regardless of outcome, so we can both
263 # recover partial output (that could have been generated early in a
264 # recover partial output (that could have been generated early in a
264 # block, before an error) and clear the payload system always.
265 # block, before an error) and clear the payload system always.
265 reply_content[u'payload'] = shell.payload_manager.read_payload()
266 reply_content[u'payload'] = shell.payload_manager.read_payload()
266 # Be agressive about clearing the payload because we don't want
267 # Be agressive about clearing the payload because we don't want
267 # it to sit in memory until the next execute_request comes in.
268 # it to sit in memory until the next execute_request comes in.
268 shell.payload_manager.clear_payload()
269 shell.payload_manager.clear_payload()
269
270
270 # Send the reply.
271 # Send the reply.
271 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
272 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
272 io.raw_print(reply_msg)
273 io.raw_print(reply_msg)
273
274
274 # Flush output before sending the reply.
275 # Flush output before sending the reply.
275 sys.stdout.flush()
276 sys.stdout.flush()
276 sys.stderr.flush()
277 sys.stderr.flush()
277 # FIXME: on rare occasions, the flush doesn't seem to make it to the
278 # FIXME: on rare occasions, the flush doesn't seem to make it to the
278 # clients... This seems to mitigate the problem, but we definitely need
279 # clients... This seems to mitigate the problem, but we definitely need
279 # to better understand what's going on.
280 # to better understand what's going on.
280 if self._execute_sleep:
281 if self._execute_sleep:
281 time.sleep(self._execute_sleep)
282 time.sleep(self._execute_sleep)
282
283
283 self.reply_socket.send(ident, zmq.SNDMORE)
284 self.reply_socket.send(ident, zmq.SNDMORE)
284 self.reply_socket.send_json(reply_msg)
285 self.reply_socket.send_json(reply_msg)
285 if reply_msg['content']['status'] == u'error':
286 if reply_msg['content']['status'] == u'error':
286 self._abort_queue()
287 self._abort_queue()
287
288
288 status_msg = self.session.msg(
289 status_msg = self.session.msg(
289 u'status',
290 u'status',
290 {u'execution_state':u'idle'},
291 {u'execution_state':u'idle'},
291 parent=parent
292 parent=parent
292 )
293 )
293 self.pub_socket.send_json(status_msg)
294 self.pub_socket.send_json(status_msg)
294
295
295 def complete_request(self, ident, parent):
296 def complete_request(self, ident, parent):
296 txt, matches = self._complete(parent)
297 txt, matches = self._complete(parent)
297 matches = {'matches' : matches,
298 matches = {'matches' : matches,
298 'matched_text' : txt,
299 'matched_text' : txt,
299 'status' : 'ok'}
300 'status' : 'ok'}
300 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
301 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
301 matches, parent, ident)
302 matches, parent, ident)
302 io.raw_print(completion_msg)
303 io.raw_print(completion_msg)
303
304
304 def object_info_request(self, ident, parent):
305 def object_info_request(self, ident, parent):
305 object_info = self.shell.object_inspect(parent['content']['oname'])
306 object_info = self.shell.object_inspect(parent['content']['oname'])
306 # Before we send this object over, we scrub it for JSON usage
307 # Before we send this object over, we scrub it for JSON usage
307 oinfo = json_clean(object_info)
308 oinfo = json_clean(object_info)
308 msg = self.session.send(self.reply_socket, 'object_info_reply',
309 msg = self.session.send(self.reply_socket, 'object_info_reply',
309 oinfo, parent, ident)
310 oinfo, parent, ident)
310 io.raw_print(msg)
311 io.raw_print(msg)
311
312
312 def history_request(self, ident, parent):
313 def history_request(self, ident, parent):
313 output = parent['content']['output']
314 output = parent['content']['output']
314 index = parent['content']['index']
315 index = parent['content']['index']
315 raw = parent['content']['raw']
316 raw = parent['content']['raw']
316 hist = self.shell.get_history(index=index, raw=raw, output=output)
317 hist = self.shell.get_history(index=index, raw=raw, output=output)
317 content = {'history' : hist}
318 content = {'history' : hist}
318 msg = self.session.send(self.reply_socket, 'history_reply',
319 msg = self.session.send(self.reply_socket, 'history_reply',
319 content, parent, ident)
320 content, parent, ident)
320 io.raw_print(msg)
321 io.raw_print(msg)
321
322
322 def connect_request(self, ident, parent):
323 def connect_request(self, ident, parent):
323 if self._recorded_ports is not None:
324 if self._recorded_ports is not None:
324 content = self._recorded_ports.copy()
325 content = self._recorded_ports.copy()
325 else:
326 else:
326 content = {}
327 content = {}
327 msg = self.session.send(self.reply_socket, 'connect_reply',
328 msg = self.session.send(self.reply_socket, 'connect_reply',
328 content, parent, ident)
329 content, parent, ident)
329 io.raw_print(msg)
330 io.raw_print(msg)
330
331
331 def shutdown_request(self, ident, parent):
332 def shutdown_request(self, ident, parent):
332 self.shell.exit_now = True
333 self.shell.exit_now = True
333 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
334 self._shutdown_message = self.session.msg(u'shutdown_reply', {}, parent)
334 sys.exit(0)
335 sys.exit(0)
335
336
336 #---------------------------------------------------------------------------
337 #---------------------------------------------------------------------------
337 # Protected interface
338 # Protected interface
338 #---------------------------------------------------------------------------
339 #---------------------------------------------------------------------------
339
340
340 def _abort_queue(self):
341 def _abort_queue(self):
341 while True:
342 while True:
342 try:
343 try:
343 ident = self.reply_socket.recv(zmq.NOBLOCK)
344 ident = self.reply_socket.recv(zmq.NOBLOCK)
344 except zmq.ZMQError, e:
345 except zmq.ZMQError, e:
345 if e.errno == zmq.EAGAIN:
346 if e.errno == zmq.EAGAIN:
346 break
347 break
347 else:
348 else:
348 assert self.reply_socket.rcvmore(), \
349 assert self.reply_socket.rcvmore(), \
349 "Unexpected missing message part."
350 "Unexpected missing message part."
350 msg = self.reply_socket.recv_json()
351 msg = self.reply_socket.recv_json()
351 io.raw_print("Aborting:\n", Message(msg))
352 io.raw_print("Aborting:\n", Message(msg))
352 msg_type = msg['msg_type']
353 msg_type = msg['msg_type']
353 reply_type = msg_type.split('_')[0] + '_reply'
354 reply_type = msg_type.split('_')[0] + '_reply'
354 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
355 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
355 io.raw_print(reply_msg)
356 io.raw_print(reply_msg)
356 self.reply_socket.send(ident,zmq.SNDMORE)
357 self.reply_socket.send(ident,zmq.SNDMORE)
357 self.reply_socket.send_json(reply_msg)
358 self.reply_socket.send_json(reply_msg)
358 # We need to wait a bit for requests to come in. This can probably
359 # We need to wait a bit for requests to come in. This can probably
359 # be set shorter for true asynchronous clients.
360 # be set shorter for true asynchronous clients.
360 time.sleep(0.1)
361 time.sleep(0.1)
361
362
362 def _raw_input(self, prompt, ident, parent):
363 def _raw_input(self, prompt, ident, parent):
363 # Flush output before making the request.
364 # Flush output before making the request.
364 sys.stderr.flush()
365 sys.stderr.flush()
365 sys.stdout.flush()
366 sys.stdout.flush()
366
367
367 # Send the input request.
368 # Send the input request.
368 content = dict(prompt=prompt)
369 content = dict(prompt=prompt)
369 msg = self.session.msg(u'input_request', content, parent)
370 msg = self.session.msg(u'input_request', content, parent)
370 self.req_socket.send_json(msg)
371 self.req_socket.send_json(msg)
371
372
372 # Await a response.
373 # Await a response.
373 reply = self.req_socket.recv_json()
374 reply = self.req_socket.recv_json()
374 try:
375 try:
375 value = reply['content']['value']
376 value = reply['content']['value']
376 except:
377 except:
377 io.raw_print_err("Got bad raw_input reply: ")
378 io.raw_print_err("Got bad raw_input reply: ")
378 io.raw_print_err(Message(parent))
379 io.raw_print_err(Message(parent))
379 value = ''
380 value = ''
380 return value
381 return value
381
382
382 def _complete(self, msg):
383 def _complete(self, msg):
383 c = msg['content']
384 c = msg['content']
384 try:
385 try:
385 cpos = int(c['cursor_pos'])
386 cpos = int(c['cursor_pos'])
386 except:
387 except:
387 # If we don't get something that we can convert to an integer, at
388 # If we don't get something that we can convert to an integer, at
388 # least attempt the completion guessing the cursor is at the end of
389 # least attempt the completion guessing the cursor is at the end of
389 # the text, if there's any, and otherwise of the line
390 # the text, if there's any, and otherwise of the line
390 cpos = len(c['text'])
391 cpos = len(c['text'])
391 if cpos==0:
392 if cpos==0:
392 cpos = len(c['line'])
393 cpos = len(c['line'])
393 return self.shell.complete(c['text'], c['line'], cpos)
394 return self.shell.complete(c['text'], c['line'], cpos)
394
395
395 def _object_info(self, context):
396 def _object_info(self, context):
396 symbol, leftover = self._symbol_from_context(context)
397 symbol, leftover = self._symbol_from_context(context)
397 if symbol is not None and not leftover:
398 if symbol is not None and not leftover:
398 doc = getattr(symbol, '__doc__', '')
399 doc = getattr(symbol, '__doc__', '')
399 else:
400 else:
400 doc = ''
401 doc = ''
401 object_info = dict(docstring = doc)
402 object_info = dict(docstring = doc)
402 return object_info
403 return object_info
403
404
404 def _symbol_from_context(self, context):
405 def _symbol_from_context(self, context):
405 if not context:
406 if not context:
406 return None, context
407 return None, context
407
408
408 base_symbol_string = context[0]
409 base_symbol_string = context[0]
409 symbol = self.shell.user_ns.get(base_symbol_string, None)
410 symbol = self.shell.user_ns.get(base_symbol_string, None)
410 if symbol is None:
411 if symbol is None:
411 symbol = __builtin__.__dict__.get(base_symbol_string, None)
412 symbol = __builtin__.__dict__.get(base_symbol_string, None)
412 if symbol is None:
413 if symbol is None:
413 return None, context
414 return None, context
414
415
415 context = context[1:]
416 context = context[1:]
416 for i, name in enumerate(context):
417 for i, name in enumerate(context):
417 new_symbol = getattr(symbol, name, None)
418 new_symbol = getattr(symbol, name, None)
418 if new_symbol is None:
419 if new_symbol is None:
419 return symbol, context[i:]
420 return symbol, context[i:]
420 else:
421 else:
421 symbol = new_symbol
422 symbol = new_symbol
422
423
423 return symbol, []
424 return symbol, []
424
425
425 def _at_shutdown(self):
426 def _at_shutdown(self):
426 """Actions taken at shutdown by the kernel, called by python's atexit.
427 """Actions taken at shutdown by the kernel, called by python's atexit.
427 """
428 """
428 # io.rprint("Kernel at_shutdown") # dbg
429 # io.rprint("Kernel at_shutdown") # dbg
429 if self._shutdown_message is not None:
430 if self._shutdown_message is not None:
430 self.reply_socket.send_json(self._shutdown_message)
431 self.reply_socket.send_json(self._shutdown_message)
431 io.raw_print(self._shutdown_message)
432 io.raw_print(self._shutdown_message)
432 # A very short sleep to give zmq time to flush its message buffers
433 # A very short sleep to give zmq time to flush its message buffers
433 # before Python truly shuts down.
434 # before Python truly shuts down.
434 time.sleep(0.01)
435 time.sleep(0.01)
435
436
436
437
437 class QtKernel(Kernel):
438 class QtKernel(Kernel):
438 """A Kernel subclass with Qt support."""
439 """A Kernel subclass with Qt support."""
439
440
440 def start(self):
441 def start(self):
441 """Start a kernel with QtPy4 event loop integration."""
442 """Start a kernel with QtPy4 event loop integration."""
442
443
443 from PyQt4 import QtCore
444 from PyQt4 import QtCore
444 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
445 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
445
446
446 self.app = get_app_qt4([" "])
447 self.app = get_app_qt4([" "])
447 self.app.setQuitOnLastWindowClosed(False)
448 self.app.setQuitOnLastWindowClosed(False)
448 self.timer = QtCore.QTimer()
449 self.timer = QtCore.QTimer()
449 self.timer.timeout.connect(self.do_one_iteration)
450 self.timer.timeout.connect(self.do_one_iteration)
450 # Units for the timer are in milliseconds
451 # Units for the timer are in milliseconds
451 self.timer.start(1000*self._poll_interval)
452 self.timer.start(1000*self._poll_interval)
452 start_event_loop_qt4(self.app)
453 start_event_loop_qt4(self.app)
453
454
454
455
455 class WxKernel(Kernel):
456 class WxKernel(Kernel):
456 """A Kernel subclass with Wx support."""
457 """A Kernel subclass with Wx support."""
457
458
458 def start(self):
459 def start(self):
459 """Start a kernel with wx event loop support."""
460 """Start a kernel with wx event loop support."""
460
461
461 import wx
462 import wx
462 from IPython.lib.guisupport import start_event_loop_wx
463 from IPython.lib.guisupport import start_event_loop_wx
463
464
464 doi = self.do_one_iteration
465 doi = self.do_one_iteration
465 # Wx uses milliseconds
466 # Wx uses milliseconds
466 poll_interval = int(1000*self._poll_interval)
467 poll_interval = int(1000*self._poll_interval)
467
468
468 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
469 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
469 # We make the Frame hidden when we create it in the main app below.
470 # We make the Frame hidden when we create it in the main app below.
470 class TimerFrame(wx.Frame):
471 class TimerFrame(wx.Frame):
471 def __init__(self, func):
472 def __init__(self, func):
472 wx.Frame.__init__(self, None, -1)
473 wx.Frame.__init__(self, None, -1)
473 self.timer = wx.Timer(self)
474 self.timer = wx.Timer(self)
474 # Units for the timer are in milliseconds
475 # Units for the timer are in milliseconds
475 self.timer.Start(poll_interval)
476 self.timer.Start(poll_interval)
476 self.Bind(wx.EVT_TIMER, self.on_timer)
477 self.Bind(wx.EVT_TIMER, self.on_timer)
477 self.func = func
478 self.func = func
478
479
479 def on_timer(self, event):
480 def on_timer(self, event):
480 self.func()
481 self.func()
481
482
482 # We need a custom wx.App to create our Frame subclass that has the
483 # We need a custom wx.App to create our Frame subclass that has the
483 # wx.Timer to drive the ZMQ event loop.
484 # wx.Timer to drive the ZMQ event loop.
484 class IPWxApp(wx.App):
485 class IPWxApp(wx.App):
485 def OnInit(self):
486 def OnInit(self):
486 self.frame = TimerFrame(doi)
487 self.frame = TimerFrame(doi)
487 self.frame.Show(False)
488 self.frame.Show(False)
488 return True
489 return True
489
490
490 # The redirect=False here makes sure that wx doesn't replace
491 # The redirect=False here makes sure that wx doesn't replace
491 # sys.stdout/stderr with its own classes.
492 # sys.stdout/stderr with its own classes.
492 self.app = IPWxApp(redirect=False)
493 self.app = IPWxApp(redirect=False)
493 start_event_loop_wx(self.app)
494 start_event_loop_wx(self.app)
494
495
495
496
496 class TkKernel(Kernel):
497 class TkKernel(Kernel):
497 """A Kernel subclass with Tk support."""
498 """A Kernel subclass with Tk support."""
498
499
499 def start(self):
500 def start(self):
500 """Start a Tk enabled event loop."""
501 """Start a Tk enabled event loop."""
501
502
502 import Tkinter
503 import Tkinter
503 doi = self.do_one_iteration
504 doi = self.do_one_iteration
504 # Tk uses milliseconds
505 # Tk uses milliseconds
505 poll_interval = int(1000*self._poll_interval)
506 poll_interval = int(1000*self._poll_interval)
506 # For Tkinter, we create a Tk object and call its withdraw method.
507 # For Tkinter, we create a Tk object and call its withdraw method.
507 class Timer(object):
508 class Timer(object):
508 def __init__(self, func):
509 def __init__(self, func):
509 self.app = Tkinter.Tk()
510 self.app = Tkinter.Tk()
510 self.app.withdraw()
511 self.app.withdraw()
511 self.func = func
512 self.func = func
512
513
513 def on_timer(self):
514 def on_timer(self):
514 self.func()
515 self.func()
515 self.app.after(poll_interval, self.on_timer)
516 self.app.after(poll_interval, self.on_timer)
516
517
517 def start(self):
518 def start(self):
518 self.on_timer() # Call it once to get things going.
519 self.on_timer() # Call it once to get things going.
519 self.app.mainloop()
520 self.app.mainloop()
520
521
521 self.timer = Timer(doi)
522 self.timer = Timer(doi)
522 self.timer.start()
523 self.timer.start()
523
524
524
525
525 class GTKKernel(Kernel):
526 class GTKKernel(Kernel):
526 """A Kernel subclass with GTK support."""
527 """A Kernel subclass with GTK support."""
527
528
528 def start(self):
529 def start(self):
529 """Start the kernel, coordinating with the GTK event loop"""
530 """Start the kernel, coordinating with the GTK event loop"""
530 from .gui.gtkembed import GTKEmbed
531 from .gui.gtkembed import GTKEmbed
531
532
532 gtk_kernel = GTKEmbed(self)
533 gtk_kernel = GTKEmbed(self)
533 gtk_kernel.start()
534 gtk_kernel.start()
534
535
535
536
536 #-----------------------------------------------------------------------------
537 #-----------------------------------------------------------------------------
537 # Kernel main and launch functions
538 # Kernel main and launch functions
538 #-----------------------------------------------------------------------------
539 #-----------------------------------------------------------------------------
539
540
540 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
541 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
541 independent=False, pylab=False):
542 independent=False, pylab=False):
542 """Launches a localhost kernel, binding to the specified ports.
543 """Launches a localhost kernel, binding to the specified ports.
543
544
544 Parameters
545 Parameters
545 ----------
546 ----------
546 xrep_port : int, optional
547 xrep_port : int, optional
547 The port to use for XREP channel.
548 The port to use for XREP channel.
548
549
549 pub_port : int, optional
550 pub_port : int, optional
550 The port to use for the SUB channel.
551 The port to use for the SUB channel.
551
552
552 req_port : int, optional
553 req_port : int, optional
553 The port to use for the REQ (raw input) channel.
554 The port to use for the REQ (raw input) channel.
554
555
555 hb_port : int, optional
556 hb_port : int, optional
556 The port to use for the hearbeat REP channel.
557 The port to use for the hearbeat REP channel.
557
558
558 independent : bool, optional (default False)
559 independent : bool, optional (default False)
559 If set, the kernel process is guaranteed to survive if this process
560 If set, the kernel process is guaranteed to survive if this process
560 dies. If not set, an effort is made to ensure that the kernel is killed
561 dies. If not set, an effort is made to ensure that the kernel is killed
561 when this process dies. Note that in this case it is still good practice
562 when this process dies. Note that in this case it is still good practice
562 to kill kernels manually before exiting.
563 to kill kernels manually before exiting.
563
564
564 pylab : bool or string, optional (default False)
565 pylab : bool or string, optional (default False)
565 If not False, the kernel will be launched with pylab enabled. If a
566 If not False, the kernel will be launched with pylab enabled. If a
566 string is passed, matplotlib will use the specified backend. Otherwise,
567 string is passed, matplotlib will use the specified backend. Otherwise,
567 matplotlib's default backend will be used.
568 matplotlib's default backend will be used.
568
569
569 Returns
570 Returns
570 -------
571 -------
571 A tuple of form:
572 A tuple of form:
572 (kernel_process, xrep_port, pub_port, req_port)
573 (kernel_process, xrep_port, pub_port, req_port)
573 where kernel_process is a Popen object and the ports are integers.
574 where kernel_process is a Popen object and the ports are integers.
574 """
575 """
575 extra_arguments = []
576 extra_arguments = []
576 if pylab:
577 if pylab:
577 extra_arguments.append('--pylab')
578 extra_arguments.append('--pylab')
578 if isinstance(pylab, basestring):
579 if isinstance(pylab, basestring):
579 extra_arguments.append(pylab)
580 extra_arguments.append(pylab)
580 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
581 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
581 xrep_port, pub_port, req_port, hb_port,
582 xrep_port, pub_port, req_port, hb_port,
582 independent, extra_arguments)
583 independent, extra_arguments)
583
584
584
585
585 def main():
586 def main():
586 """ The IPython kernel main entry point.
587 """ The IPython kernel main entry point.
587 """
588 """
588 parser = make_argument_parser()
589 parser = make_argument_parser()
589 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
590 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
590 const='auto', help = \
591 const='auto', help = \
591 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
592 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
592 given, the GUI backend is matplotlib's, otherwise use one of: \
593 given, the GUI backend is matplotlib's, otherwise use one of: \
593 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
594 ['tk', 'gtk', 'qt', 'wx', 'inline'].")
594 namespace = parser.parse_args()
595 namespace = parser.parse_args()
595
596
596 kernel_class = Kernel
597 kernel_class = Kernel
597
598
598 kernel_classes = {
599 kernel_classes = {
599 'qt' : QtKernel,
600 'qt' : QtKernel,
600 'qt4': QtKernel,
601 'qt4': QtKernel,
601 'inline': Kernel,
602 'inline': Kernel,
602 'wx' : WxKernel,
603 'wx' : WxKernel,
603 'tk' : TkKernel,
604 'tk' : TkKernel,
604 'gtk': GTKKernel,
605 'gtk': GTKKernel,
605 }
606 }
606 if namespace.pylab:
607 if namespace.pylab:
607 if namespace.pylab == 'auto':
608 if namespace.pylab == 'auto':
608 gui, backend = pylabtools.find_gui_and_backend()
609 gui, backend = pylabtools.find_gui_and_backend()
609 else:
610 else:
610 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
611 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
611 kernel_class = kernel_classes.get(gui)
612 kernel_class = kernel_classes.get(gui)
612 if kernel_class is None:
613 if kernel_class is None:
613 raise ValueError('GUI is not supported: %r' % gui)
614 raise ValueError('GUI is not supported: %r' % gui)
614 pylabtools.activate_matplotlib(backend)
615 pylabtools.activate_matplotlib(backend)
615
616
616 kernel = make_kernel(namespace, kernel_class, OutStream)
617 kernel = make_kernel(namespace, kernel_class, OutStream)
617
618
618 if namespace.pylab:
619 if namespace.pylab:
619 pylabtools.import_pylab(kernel.shell.user_ns, backend,
620 pylabtools.import_pylab(kernel.shell.user_ns, backend,
620 shell=kernel.shell)
621 shell=kernel.shell)
621
622
622 start_kernel(namespace, kernel)
623 start_kernel(namespace, kernel)
623
624
624
625
625 if __name__ == '__main__':
626 if __name__ == '__main__':
626 main()
627 main()
General Comments 0
You need to be logged in to leave comments. Login now