##// END OF EJS Templates
Added --gui to match %gui use, better docs and behavior for %pylab code....
Fernando Perez -
Show More
@@ -1,555 +1,587 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors:
7 Authors:
8
8
9 * Brian Granger
9 * Brian Granger
10 * Fernando Perez
10 * Fernando Perez
11
11
12 Notes
12 Notes
13 -----
13 -----
14 """
14 """
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2009 The IPython Development Team
17 # Copyright (C) 2008-2009 The IPython Development Team
18 #
18 #
19 # Distributed under the terms of the BSD License. The full license is in
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Imports
24 # Imports
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30
30
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
33 from IPython.core.error import UsageError
33 from IPython.core.error import UsageError
34 from IPython.core.iplib import InteractiveShell
34 from IPython.core.iplib import InteractiveShell
35 from IPython.core.pylabtools import pylab_activate
35 from IPython.core.pylabtools import pylab_activate
36 from IPython.config.loader import (
36 from IPython.config.loader import (
37 NoConfigDefault,
37 NoConfigDefault,
38 Config,
38 Config,
39 PyFileConfigLoader
39 PyFileConfigLoader
40 )
40 )
41 from IPython.lib import inputhook
41 from IPython.lib import inputhook
42 from IPython.utils.genutils import filefind, get_ipython_dir
42 from IPython.utils.genutils import filefind, get_ipython_dir
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Utilities and helpers
45 # Utilities and helpers
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 ipython_desc = """
48 ipython_desc = """
49 A Python shell with automatic history (input and output), dynamic object
49 A Python shell with automatic history (input and output), dynamic object
50 introspection, easier configuration, command completion, access to the system
50 introspection, easier configuration, command completion, access to the system
51 shell and more.
51 shell and more.
52 """
52 """
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Main classes and functions
55 # Main classes and functions
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58 cl_args = (
58 cl_args = (
59 (('--autocall',), dict(
59 (('--autocall',), dict(
60 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
60 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
61 help='Set the autocall value (0,1,2).',
61 help='Set the autocall value (0,1,2).',
62 metavar='InteractiveShell.autocall')
62 metavar='InteractiveShell.autocall')
63 ),
63 ),
64 (('--autoindent',), dict(
64 (('--autoindent',), dict(
65 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
65 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
66 help='Turn on autoindenting.')
66 help='Turn on autoindenting.')
67 ),
67 ),
68 (('--no-autoindent',), dict(
68 (('--no-autoindent',), dict(
69 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
69 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
70 help='Turn off autoindenting.')
70 help='Turn off autoindenting.')
71 ),
71 ),
72 (('--automagic',), dict(
72 (('--automagic',), dict(
73 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
73 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
74 help='Turn on the auto calling of magic commands.')
74 help='Turn on the auto calling of magic commands.')
75 ),
75 ),
76 (('--no-automagic',), dict(
76 (('--no-automagic',), dict(
77 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
77 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
78 help='Turn off the auto calling of magic commands.')
78 help='Turn off the auto calling of magic commands.')
79 ),
79 ),
80 (('--autoedit-syntax',), dict(
80 (('--autoedit-syntax',), dict(
81 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
81 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
82 help='Turn on auto editing of files with syntax errors.')
82 help='Turn on auto editing of files with syntax errors.')
83 ),
83 ),
84 (('--no-autoedit-syntax',), dict(
84 (('--no-autoedit-syntax',), dict(
85 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
85 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
86 help='Turn off auto editing of files with syntax errors.')
86 help='Turn off auto editing of files with syntax errors.')
87 ),
87 ),
88 (('--banner',), dict(
88 (('--banner',), dict(
89 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
89 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
90 help='Display a banner upon starting IPython.')
90 help='Display a banner upon starting IPython.')
91 ),
91 ),
92 (('--no-banner',), dict(
92 (('--no-banner',), dict(
93 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
93 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
94 help="Don't display a banner upon starting IPython.")
94 help="Don't display a banner upon starting IPython.")
95 ),
95 ),
96 (('--cache-size',), dict(
96 (('--cache-size',), dict(
97 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
97 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
98 help="Set the size of the output cache.",
98 help="Set the size of the output cache.",
99 metavar='InteractiveShell.cache_size')
99 metavar='InteractiveShell.cache_size')
100 ),
100 ),
101 (('--classic',), dict(
101 (('--classic',), dict(
102 action='store_true', dest='Global.classic', default=NoConfigDefault,
102 action='store_true', dest='Global.classic', default=NoConfigDefault,
103 help="Gives IPython a similar feel to the classic Python prompt.")
103 help="Gives IPython a similar feel to the classic Python prompt.")
104 ),
104 ),
105 (('--colors',), dict(
105 (('--colors',), dict(
106 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
106 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
107 help="Set the color scheme (NoColor, Linux, and LightBG).",
107 help="Set the color scheme (NoColor, Linux, and LightBG).",
108 metavar='InteractiveShell.colors')
108 metavar='InteractiveShell.colors')
109 ),
109 ),
110 (('--color-info',), dict(
110 (('--color-info',), dict(
111 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
111 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
112 help="Enable using colors for info related things.")
112 help="Enable using colors for info related things.")
113 ),
113 ),
114 (('--no-color-info',), dict(
114 (('--no-color-info',), dict(
115 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
115 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
116 help="Disable using colors for info related things.")
116 help="Disable using colors for info related things.")
117 ),
117 ),
118 (('--confirm-exit',), dict(
118 (('--confirm-exit',), dict(
119 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
119 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
120 help="Prompt the user when existing.")
120 help="Prompt the user when existing.")
121 ),
121 ),
122 (('--no-confirm-exit',), dict(
122 (('--no-confirm-exit',), dict(
123 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
123 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
124 help="Don't prompt the user when existing.")
124 help="Don't prompt the user when existing.")
125 ),
125 ),
126 (('--deep-reload',), dict(
126 (('--deep-reload',), dict(
127 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
127 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
128 help="Enable deep (recursive) reloading by default.")
128 help="Enable deep (recursive) reloading by default.")
129 ),
129 ),
130 (('--no-deep-reload',), dict(
130 (('--no-deep-reload',), dict(
131 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
131 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
132 help="Disable deep (recursive) reloading by default.")
132 help="Disable deep (recursive) reloading by default.")
133 ),
133 ),
134 (('--editor',), dict(
134 (('--editor',), dict(
135 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
135 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
136 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
136 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
137 metavar='InteractiveShell.editor')
137 metavar='InteractiveShell.editor')
138 ),
138 ),
139 (('--log','-l'), dict(
139 (('--log','-l'), dict(
140 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
140 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
141 help="Start logging to the default file (./ipython_log.py).")
141 help="Start logging to the default file (./ipython_log.py).")
142 ),
142 ),
143 (('--logfile','-lf'), dict(
143 (('--logfile','-lf'), dict(
144 type=unicode, dest='InteractiveShell.logfile', default=NoConfigDefault,
144 type=unicode, dest='InteractiveShell.logfile', default=NoConfigDefault,
145 help="Start logging to logfile.",
145 help="Start logging to logfile.",
146 metavar='InteractiveShell.logfile')
146 metavar='InteractiveShell.logfile')
147 ),
147 ),
148 (('--log-append','-la'), dict(
148 (('--log-append','-la'), dict(
149 type=unicode, dest='InteractiveShell.logappend', default=NoConfigDefault,
149 type=unicode, dest='InteractiveShell.logappend', default=NoConfigDefault,
150 help="Start logging to the give file in append mode.",
150 help="Start logging to the give file in append mode.",
151 metavar='InteractiveShell.logfile')
151 metavar='InteractiveShell.logfile')
152 ),
152 ),
153 (('--pdb',), dict(
153 (('--pdb',), dict(
154 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
154 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
155 help="Enable auto calling the pdb debugger after every exception.")
155 help="Enable auto calling the pdb debugger after every exception.")
156 ),
156 ),
157 (('--no-pdb',), dict(
157 (('--no-pdb',), dict(
158 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
158 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
159 help="Disable auto calling the pdb debugger after every exception.")
159 help="Disable auto calling the pdb debugger after every exception.")
160 ),
160 ),
161 (('--pprint',), dict(
161 (('--pprint',), dict(
162 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
162 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
163 help="Enable auto pretty printing of results.")
163 help="Enable auto pretty printing of results.")
164 ),
164 ),
165 (('--no-pprint',), dict(
165 (('--no-pprint',), dict(
166 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
166 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
167 help="Disable auto auto pretty printing of results.")
167 help="Disable auto auto pretty printing of results.")
168 ),
168 ),
169 (('--prompt-in1','-pi1'), dict(
169 (('--prompt-in1','-pi1'), dict(
170 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
170 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
171 help="Set the main input prompt ('In [\#]: ')",
171 help="Set the main input prompt ('In [\#]: ')",
172 metavar='InteractiveShell.prompt_in1')
172 metavar='InteractiveShell.prompt_in1')
173 ),
173 ),
174 (('--prompt-in2','-pi2'), dict(
174 (('--prompt-in2','-pi2'), dict(
175 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
175 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
176 help="Set the secondary input prompt (' .\D.: ')",
176 help="Set the secondary input prompt (' .\D.: ')",
177 metavar='InteractiveShell.prompt_in2')
177 metavar='InteractiveShell.prompt_in2')
178 ),
178 ),
179 (('--prompt-out','-po'), dict(
179 (('--prompt-out','-po'), dict(
180 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
180 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
181 help="Set the output prompt ('Out[\#]:')",
181 help="Set the output prompt ('Out[\#]:')",
182 metavar='InteractiveShell.prompt_out')
182 metavar='InteractiveShell.prompt_out')
183 ),
183 ),
184 (('--quick',), dict(
184 (('--quick',), dict(
185 action='store_true', dest='Global.quick', default=NoConfigDefault,
185 action='store_true', dest='Global.quick', default=NoConfigDefault,
186 help="Enable quick startup with no config files.")
186 help="Enable quick startup with no config files.")
187 ),
187 ),
188 (('--readline',), dict(
188 (('--readline',), dict(
189 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
189 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
190 help="Enable readline for command line usage.")
190 help="Enable readline for command line usage.")
191 ),
191 ),
192 (('--no-readline',), dict(
192 (('--no-readline',), dict(
193 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
193 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
194 help="Disable readline for command line usage.")
194 help="Disable readline for command line usage.")
195 ),
195 ),
196 (('--screen-length','-sl'), dict(
196 (('--screen-length','-sl'), dict(
197 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
197 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
198 help='Number of lines on screen, used to control printing of long strings.',
198 help='Number of lines on screen, used to control printing of long strings.',
199 metavar='InteractiveShell.screen_length')
199 metavar='InteractiveShell.screen_length')
200 ),
200 ),
201 (('--separate-in','-si'), dict(
201 (('--separate-in','-si'), dict(
202 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
202 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
203 help="Separator before input prompts. Default '\n'.",
203 help="Separator before input prompts. Default '\n'.",
204 metavar='InteractiveShell.separate_in')
204 metavar='InteractiveShell.separate_in')
205 ),
205 ),
206 (('--separate-out','-so'), dict(
206 (('--separate-out','-so'), dict(
207 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
207 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
208 help="Separator before output prompts. Default 0 (nothing).",
208 help="Separator before output prompts. Default 0 (nothing).",
209 metavar='InteractiveShell.separate_out')
209 metavar='InteractiveShell.separate_out')
210 ),
210 ),
211 (('--separate-out2','-so2'), dict(
211 (('--separate-out2','-so2'), dict(
212 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
212 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
213 help="Separator after output prompts. Default 0 (nonight).",
213 help="Separator after output prompts. Default 0 (nonight).",
214 metavar='InteractiveShell.separate_out2')
214 metavar='InteractiveShell.separate_out2')
215 ),
215 ),
216 (('-no-sep',), dict(
216 (('-no-sep',), dict(
217 action='store_true', dest='Global.nosep', default=NoConfigDefault,
217 action='store_true', dest='Global.nosep', default=NoConfigDefault,
218 help="Eliminate all spacing between prompts.")
218 help="Eliminate all spacing between prompts.")
219 ),
219 ),
220 (('--term-title',), dict(
220 (('--term-title',), dict(
221 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
221 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
222 help="Enable auto setting the terminal title.")
222 help="Enable auto setting the terminal title.")
223 ),
223 ),
224 (('--no-term-title',), dict(
224 (('--no-term-title',), dict(
225 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
225 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
226 help="Disable auto setting the terminal title.")
226 help="Disable auto setting the terminal title.")
227 ),
227 ),
228 (('--xmode',), dict(
228 (('--xmode',), dict(
229 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
229 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
230 help="Exception mode ('Plain','Context','Verbose')",
230 help="Exception mode ('Plain','Context','Verbose')",
231 metavar='InteractiveShell.xmode')
231 metavar='InteractiveShell.xmode')
232 ),
232 ),
233 (('--ext',), dict(
233 (('--ext',), dict(
234 type=str, dest='Global.extra_extension', default=NoConfigDefault,
234 type=str, dest='Global.extra_extension', default=NoConfigDefault,
235 help="The dotted module name of an IPython extension to load.",
235 help="The dotted module name of an IPython extension to load.",
236 metavar='Global.extra_extension')
236 metavar='Global.extra_extension')
237 ),
237 ),
238 (('-c',), dict(
238 (('-c',), dict(
239 type=str, dest='Global.code_to_run', default=NoConfigDefault,
239 type=str, dest='Global.code_to_run', default=NoConfigDefault,
240 help="Execute the given command string.",
240 help="Execute the given command string.",
241 metavar='Global.code_to_run')
241 metavar='Global.code_to_run')
242 ),
242 ),
243 (('-i',), dict(
243 (('-i',), dict(
244 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
244 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
245 help="If running code from the command line, become interactive afterwards.")
245 help="If running code from the command line, become interactive afterwards.")
246 ),
246 ),
247
248 # Options to start with GUI control enabled from the beginning
249 (('--gui',), dict(
250 type=str, dest='Global.gui', default=NoConfigDefault,
251 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
252 metavar='gui-mode')
253 ),
254
255 (('--pylab',), dict(
256 type=str, dest='Global.pylab', default=NoConfigDefault,
257 nargs='?', const='auto', metavar='gui-mode',
258 help="Pre-load matplotlib and numpy for interactive use. "+
259 "If no value is given, the gui backend is matplotlib's, else use "+
260 "one of: ['tk', 'qt', 'wx', 'gtk'].")
261 ),
262
263 # Legacy GUI options. Leave them in for backwards compatibility, but the
264 # 'thread' names are really a misnomer now.
247 (('--wthread','-wthread'), dict(
265 (('--wthread','-wthread'), dict(
248 action='store_true', dest='Global.wthread', default=NoConfigDefault,
266 action='store_true', dest='Global.wthread', default=NoConfigDefault,
249 help="Enable wxPython event loop integration.")
267 help="Enable wxPython event loop integration "+
268 "(DEPRECATED, use --gui wx)")
250 ),
269 ),
251 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
270 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
252 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
271 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
253 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
272 help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+
273 "(DEPRECATED, use --gui qt)")
254 ),
274 ),
255 (('--gthread','-gthread'), dict(
275 (('--gthread','-gthread'), dict(
256 action='store_true', dest='Global.gthread', default=NoConfigDefault,
276 action='store_true', dest='Global.gthread', default=NoConfigDefault,
257 help="Enable GTK event loop integration.")
277 help="Enable GTK event loop integration. "+
278 "(DEPRECATED, use --gui gtk)")
258 ),
279 ),
259 (('--pylab',), dict(
260 action='store_true', dest='Global.pylab', default=NoConfigDefault,
261 help="Pre-load matplotlib and numpy for interactive use.")
262 )
263 )
280 )
264
281
265
282
266 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
283 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
267
284
268 arguments = cl_args
285 arguments = cl_args
269
286
270 def load_config(self):
287 def load_config(self):
271 """Do actions just before loading the command line config."""
288 """Do actions just before loading the command line config."""
272
289
273 # Special hack: there are countless uses of 'ipython -pylab' (with one
290 # Special hack: there are countless uses of 'ipython -pylab' (with one
274 # dash) in the wild, including in printed books. Since argparse does
291 # dash) in the wild, including in printed books. Since argparse does
275 # will interpret -pylab as '-p ylab', sending us in a search for a
292 # will interpret -pylab as '-p ylab', sending us in a search for a
276 # profile named 'ylab', instead we special-case here -pylab as the
293 # profile named 'ylab', instead we special-case here -pylab as the
277 # first or second option only (this is how old ipython used to work)
294 # first or second option only (this is how old ipython used to work)
278 # and convert this use to --pylab. Ugly, but needed for this one
295 # and convert this use to --pylab. Ugly, but needed for this one
279 # very widely used case.
296 # very widely used case.
280 firstargs = sys.argv[:3]
297 firstargs = sys.argv[:3]
281 try:
298 try:
282 idx = firstargs.index('-pylab')
299 idx = firstargs.index('-pylab')
283 except ValueError:
300 except ValueError:
284 pass
301 pass
285 else:
302 else:
286 sys.argv[idx] = '--pylab'
303 sys.argv[idx] = '--pylab'
287 return super(IPythonAppCLConfigLoader, self).load_config()
304 return super(IPythonAppCLConfigLoader, self).load_config()
288
305
289 default_config_file_name = u'ipython_config.py'
306 default_config_file_name = u'ipython_config.py'
290
307
291
308
292 class IPythonApp(Application):
309 class IPythonApp(Application):
293 name = u'ipython'
310 name = u'ipython'
294 description = 'IPython: an enhanced interactive Python shell.'
311 description = 'IPython: an enhanced interactive Python shell.'
295 config_file_name = default_config_file_name
312 config_file_name = default_config_file_name
296
313
297 def create_default_config(self):
314 def create_default_config(self):
298 super(IPythonApp, self).create_default_config()
315 super(IPythonApp, self).create_default_config()
299 # Eliminate multiple lookups
316 # Eliminate multiple lookups
300 Global = self.default_config.Global
317 Global = self.default_config.Global
318
301 # Set all default values
319 # Set all default values
302 Global.display_banner = True
320 Global.display_banner = True
303
321
304 # If the -c flag is given or a file is given to run at the cmd line
322 # If the -c flag is given or a file is given to run at the cmd line
305 # like "ipython foo.py", normally we exit without starting the main
323 # like "ipython foo.py", normally we exit without starting the main
306 # loop. The force_interact config variable allows a user to override
324 # loop. The force_interact config variable allows a user to override
307 # this and interact. It is also set by the -i cmd line flag, just
325 # this and interact. It is also set by the -i cmd line flag, just
308 # like Python.
326 # like Python.
309 Global.force_interact = False
327 Global.force_interact = False
310
328
311 # By default always interact by starting the IPython mainloop.
329 # By default always interact by starting the IPython mainloop.
312 Global.interact = True
330 Global.interact = True
313
331
314 # No GUI integration by default
332 # No GUI integration by default
315 Global.wthread = False
333 Global.gui = False
316 Global.q4thread = False
317 Global.gthread = False
318
319 # Pylab off by default
334 # Pylab off by default
320 Global.pylab = False
335 Global.pylab = False
321
336
337 # Deprecated versions of gui support that used threading, we support
338 # them just for bacwards compatibility as an alternate spelling for
339 # '--gui X'
340 Global.qthread = False
341 Global.q4thread = False
342 Global.wthread = False
343 Global.gthread = False
344
322 def create_command_line_config(self):
345 def create_command_line_config(self):
323 """Create and return a command line config loader."""
346 """Create and return a command line config loader."""
324 return IPythonAppCLConfigLoader(
347 return IPythonAppCLConfigLoader(
325 description=self.description,
348 description=self.description,
326 version=release.version
349 version=release.version
327 )
350 )
328
351
329
352
330 def load_file_config(self):
353 def load_file_config(self):
331 if hasattr(self.command_line_config.Global, 'quick'):
354 if hasattr(self.command_line_config.Global, 'quick'):
332 if self.command_line_config.Global.quick:
355 if self.command_line_config.Global.quick:
333 self.file_config = Config()
356 self.file_config = Config()
334 return
357 return
335 super(IPythonApp, self).load_file_config()
358 super(IPythonApp, self).load_file_config()
336
359
337 def post_load_file_config(self):
360 def post_load_file_config(self):
338 if hasattr(self.command_line_config.Global, 'extra_extension'):
361 if hasattr(self.command_line_config.Global, 'extra_extension'):
339 if not hasattr(self.file_config.Global, 'extensions'):
362 if not hasattr(self.file_config.Global, 'extensions'):
340 self.file_config.Global.extensions = []
363 self.file_config.Global.extensions = []
341 self.file_config.Global.extensions.append(
364 self.file_config.Global.extensions.append(
342 self.command_line_config.Global.extra_extension)
365 self.command_line_config.Global.extra_extension)
343 del self.command_line_config.Global.extra_extension
366 del self.command_line_config.Global.extra_extension
344
367
345 def pre_construct(self):
368 def pre_construct(self):
346 config = self.master_config
369 config = self.master_config
347
370
348 if hasattr(config.Global, 'classic'):
371 if hasattr(config.Global, 'classic'):
349 if config.Global.classic:
372 if config.Global.classic:
350 config.InteractiveShell.cache_size = 0
373 config.InteractiveShell.cache_size = 0
351 config.InteractiveShell.pprint = 0
374 config.InteractiveShell.pprint = 0
352 config.InteractiveShell.prompt_in1 = '>>> '
375 config.InteractiveShell.prompt_in1 = '>>> '
353 config.InteractiveShell.prompt_in2 = '... '
376 config.InteractiveShell.prompt_in2 = '... '
354 config.InteractiveShell.prompt_out = ''
377 config.InteractiveShell.prompt_out = ''
355 config.InteractiveShell.separate_in = \
378 config.InteractiveShell.separate_in = \
356 config.InteractiveShell.separate_out = \
379 config.InteractiveShell.separate_out = \
357 config.InteractiveShell.separate_out2 = ''
380 config.InteractiveShell.separate_out2 = ''
358 config.InteractiveShell.colors = 'NoColor'
381 config.InteractiveShell.colors = 'NoColor'
359 config.InteractiveShell.xmode = 'Plain'
382 config.InteractiveShell.xmode = 'Plain'
360
383
361 if hasattr(config.Global, 'nosep'):
384 if hasattr(config.Global, 'nosep'):
362 if config.Global.nosep:
385 if config.Global.nosep:
363 config.InteractiveShell.separate_in = \
386 config.InteractiveShell.separate_in = \
364 config.InteractiveShell.separate_out = \
387 config.InteractiveShell.separate_out = \
365 config.InteractiveShell.separate_out2 = ''
388 config.InteractiveShell.separate_out2 = ''
366
389
367 # if there is code of files to run from the cmd line, don't interact
390 # if there is code of files to run from the cmd line, don't interact
368 # unless the -i flag (Global.force_interact) is true.
391 # unless the -i flag (Global.force_interact) is true.
369 code_to_run = config.Global.get('code_to_run','')
392 code_to_run = config.Global.get('code_to_run','')
370 file_to_run = False
393 file_to_run = False
371 if len(self.extra_args)>=1:
394 if len(self.extra_args)>=1:
372 if self.extra_args[0]:
395 if self.extra_args[0]:
373 file_to_run = True
396 file_to_run = True
374 if file_to_run or code_to_run:
397 if file_to_run or code_to_run:
375 if not config.Global.force_interact:
398 if not config.Global.force_interact:
376 config.Global.interact = False
399 config.Global.interact = False
377
400
378 def construct(self):
401 def construct(self):
379 # I am a little hesitant to put these into InteractiveShell itself.
402 # I am a little hesitant to put these into InteractiveShell itself.
380 # But that might be the place for them
403 # But that might be the place for them
381 sys.path.insert(0, '')
404 sys.path.insert(0, '')
382
405
383 # Create an InteractiveShell instance
406 # Create an InteractiveShell instance
384 self.shell = InteractiveShell(
407 self.shell = InteractiveShell(
385 parent=None,
408 parent=None,
386 config=self.master_config
409 config=self.master_config
387 )
410 )
388
411
389 def post_construct(self):
412 def post_construct(self):
390 """Do actions after construct, but before starting the app."""
413 """Do actions after construct, but before starting the app."""
391 config = self.master_config
414 config = self.master_config
392
415
393 # shell.display_banner should always be False for the terminal
416 # shell.display_banner should always be False for the terminal
394 # based app, because we call shell.show_banner() by hand below
417 # based app, because we call shell.show_banner() by hand below
395 # so the banner shows *before* all extension loading stuff.
418 # so the banner shows *before* all extension loading stuff.
396 self.shell.display_banner = False
419 self.shell.display_banner = False
397
420
398 if config.Global.display_banner and \
421 if config.Global.display_banner and \
399 config.Global.interact:
422 config.Global.interact:
400 self.shell.show_banner()
423 self.shell.show_banner()
401
424
402 # Make sure there is a space below the banner.
425 # Make sure there is a space below the banner.
403 if self.log_level <= logging.INFO: print
426 if self.log_level <= logging.INFO: print
404
427
405 # Now a variety of things that happen after the banner is printed.
428 # Now a variety of things that happen after the banner is printed.
406 self._enable_gui_pylab()
429 self._enable_gui_pylab()
407 self._load_extensions()
430 self._load_extensions()
408 self._run_exec_lines()
431 self._run_exec_lines()
409 self._run_exec_files()
432 self._run_exec_files()
410 self._run_cmd_line_code()
433 self._run_cmd_line_code()
411 self._configure_xmode()
434 self._configure_xmode()
412
435
413 def _enable_gui_pylab(self):
436 def _enable_gui_pylab(self):
414 """Enable GUI event loop integration, taking pylab into account."""
437 """Enable GUI event loop integration, taking pylab into account."""
415 Global = self.master_config.Global
438 Global = self.master_config.Global
416
439
417 # Select which gui to use
440 # Select which gui to use
418 if Global.wthread:
441 if Global.gui:
442 gui = Global.gui
443 # The following are deprecated, but there's likely to be a lot of use
444 # of this form out there, so we might as well support it for now. But
445 # the --gui option above takes precedence.
446 elif Global.wthread:
419 gui = inputhook.GUI_WX
447 gui = inputhook.GUI_WX
420 elif Global.q4thread:
448 elif Global.qthread:
421 gui = inputhook.GUI_QT
449 gui = inputhook.GUI_QT
422 elif Global.gthread:
450 elif Global.gthread:
423 gui = inputhook.GUI_GTK
451 gui = inputhook.GUI_GTK
424 else:
452 else:
425 gui = None
453 gui = None
426
454
455 # Using --pylab will also require gui activation, though which toolkit
456 # to use may be chosen automatically based on mpl configuration.
427 if Global.pylab:
457 if Global.pylab:
428 activate = self.shell.enable_pylab
458 activate = self.shell.enable_pylab
459 if Global.pylab == 'auto':
460 gui = None
461 else:
462 gui = Global.pylab
429 else:
463 else:
430 # Enable only GUI integration, no pylab
464 # Enable only GUI integration, no pylab
431 activate = inputhook.enable_gui
465 activate = inputhook.enable_gui
432
466
433 if gui or Global.pylab:
467 if gui or Global.pylab:
434 try:
468 try:
435 m = "Enabling GUI event loop integration, toolkit=%s, pylab=%s"\
469 self.log.info("Enabling GUI event loop integration, "
436 % (gui, Global.pylab)
470 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
437 self.log.info(m)
438 activate(gui)
471 activate(gui)
439 except:
472 except:
440 self.log.warn("Error in enabling GUI event loop integration:")
473 self.log.warn("Error in enabling GUI event loop integration:")
441 self.shell.showtraceback()
474 self.shell.showtraceback()
442
475
443
444 def _load_extensions(self):
476 def _load_extensions(self):
445 """Load all IPython extensions in Global.extensions.
477 """Load all IPython extensions in Global.extensions.
446
478
447 This uses the :meth:`InteractiveShell.load_extensions` to load all
479 This uses the :meth:`InteractiveShell.load_extensions` to load all
448 the extensions listed in ``self.master_config.Global.extensions``.
480 the extensions listed in ``self.master_config.Global.extensions``.
449 """
481 """
450 try:
482 try:
451 if hasattr(self.master_config.Global, 'extensions'):
483 if hasattr(self.master_config.Global, 'extensions'):
452 self.log.debug("Loading IPython extensions...")
484 self.log.debug("Loading IPython extensions...")
453 extensions = self.master_config.Global.extensions
485 extensions = self.master_config.Global.extensions
454 for ext in extensions:
486 for ext in extensions:
455 try:
487 try:
456 self.log.info("Loading IPython extension: %s" % ext)
488 self.log.info("Loading IPython extension: %s" % ext)
457 self.shell.load_extension(ext)
489 self.shell.load_extension(ext)
458 except:
490 except:
459 self.log.warn("Error in loading extension: %s" % ext)
491 self.log.warn("Error in loading extension: %s" % ext)
460 self.shell.showtraceback()
492 self.shell.showtraceback()
461 except:
493 except:
462 self.log.warn("Unknown error in loading extensions:")
494 self.log.warn("Unknown error in loading extensions:")
463 self.shell.showtraceback()
495 self.shell.showtraceback()
464
496
465 def _run_exec_lines(self):
497 def _run_exec_lines(self):
466 """Run lines of code in Global.exec_lines in the user's namespace."""
498 """Run lines of code in Global.exec_lines in the user's namespace."""
467 try:
499 try:
468 if hasattr(self.master_config.Global, 'exec_lines'):
500 if hasattr(self.master_config.Global, 'exec_lines'):
469 self.log.debug("Running code from Global.exec_lines...")
501 self.log.debug("Running code from Global.exec_lines...")
470 exec_lines = self.master_config.Global.exec_lines
502 exec_lines = self.master_config.Global.exec_lines
471 for line in exec_lines:
503 for line in exec_lines:
472 try:
504 try:
473 self.log.info("Running code in user namespace: %s" % line)
505 self.log.info("Running code in user namespace: %s" % line)
474 self.shell.runlines(line)
506 self.shell.runlines(line)
475 except:
507 except:
476 self.log.warn("Error in executing line in user namespace: %s" % line)
508 self.log.warn("Error in executing line in user namespace: %s" % line)
477 self.shell.showtraceback()
509 self.shell.showtraceback()
478 except:
510 except:
479 self.log.warn("Unknown error in handling Global.exec_lines:")
511 self.log.warn("Unknown error in handling Global.exec_lines:")
480 self.shell.showtraceback()
512 self.shell.showtraceback()
481
513
482 def _exec_file(self, fname):
514 def _exec_file(self, fname):
483 full_filename = filefind(fname, [u'.', self.ipython_dir])
515 full_filename = filefind(fname, [u'.', self.ipython_dir])
484 if os.path.isfile(full_filename):
516 if os.path.isfile(full_filename):
485 if full_filename.endswith(u'.py'):
517 if full_filename.endswith(u'.py'):
486 self.log.info("Running file in user namespace: %s" % full_filename)
518 self.log.info("Running file in user namespace: %s" % full_filename)
487 self.shell.safe_execfile(full_filename, self.shell.user_ns)
519 self.shell.safe_execfile(full_filename, self.shell.user_ns)
488 elif full_filename.endswith('.ipy'):
520 elif full_filename.endswith('.ipy'):
489 self.log.info("Running file in user namespace: %s" % full_filename)
521 self.log.info("Running file in user namespace: %s" % full_filename)
490 self.shell.safe_execfile_ipy(full_filename)
522 self.shell.safe_execfile_ipy(full_filename)
491 else:
523 else:
492 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
524 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
493
525
494 def _run_exec_files(self):
526 def _run_exec_files(self):
495 try:
527 try:
496 if hasattr(self.master_config.Global, 'exec_files'):
528 if hasattr(self.master_config.Global, 'exec_files'):
497 self.log.debug("Running files in Global.exec_files...")
529 self.log.debug("Running files in Global.exec_files...")
498 exec_files = self.master_config.Global.exec_files
530 exec_files = self.master_config.Global.exec_files
499 for fname in exec_files:
531 for fname in exec_files:
500 self._exec_file(fname)
532 self._exec_file(fname)
501 except:
533 except:
502 self.log.warn("Unknown error in handling Global.exec_files:")
534 self.log.warn("Unknown error in handling Global.exec_files:")
503 self.shell.showtraceback()
535 self.shell.showtraceback()
504
536
505 def _run_cmd_line_code(self):
537 def _run_cmd_line_code(self):
506 if hasattr(self.master_config.Global, 'code_to_run'):
538 if hasattr(self.master_config.Global, 'code_to_run'):
507 line = self.master_config.Global.code_to_run
539 line = self.master_config.Global.code_to_run
508 try:
540 try:
509 self.log.info("Running code given at command line (-c): %s" % line)
541 self.log.info("Running code given at command line (-c): %s" % line)
510 self.shell.runlines(line)
542 self.shell.runlines(line)
511 except:
543 except:
512 self.log.warn("Error in executing line in user namespace: %s" % line)
544 self.log.warn("Error in executing line in user namespace: %s" % line)
513 self.shell.showtraceback()
545 self.shell.showtraceback()
514 return
546 return
515 # Like Python itself, ignore the second if the first of these is present
547 # Like Python itself, ignore the second if the first of these is present
516 try:
548 try:
517 fname = self.extra_args[0]
549 fname = self.extra_args[0]
518 except:
550 except:
519 pass
551 pass
520 else:
552 else:
521 try:
553 try:
522 self._exec_file(fname)
554 self._exec_file(fname)
523 except:
555 except:
524 self.log.warn("Error in executing file in user namespace: %s" % fname)
556 self.log.warn("Error in executing file in user namespace: %s" % fname)
525 self.shell.showtraceback()
557 self.shell.showtraceback()
526
558
527 def _configure_xmode(self):
559 def _configure_xmode(self):
528 # XXX - shouldn't this be read from the config? I'm still a little
560 # XXX - shouldn't this be read from the config? I'm still a little
529 # lost with all the details of handling the new config guys...
561 # lost with all the details of handling the new config guys...
530 self.shell.InteractiveTB.set_mode(mode=self.shell.xmode)
562 self.shell.InteractiveTB.set_mode(mode=self.shell.xmode)
531
563
532 def start_app(self):
564 def start_app(self):
533 if self.master_config.Global.interact:
565 if self.master_config.Global.interact:
534 self.log.debug("Starting IPython's mainloop...")
566 self.log.debug("Starting IPython's mainloop...")
535 self.shell.mainloop()
567 self.shell.mainloop()
536
568
537
569
538
570
539 def load_default_config(ipython_dir=None):
571 def load_default_config(ipython_dir=None):
540 """Load the default config file from the default ipython_dir.
572 """Load the default config file from the default ipython_dir.
541
573
542 This is useful for embedded shells.
574 This is useful for embedded shells.
543 """
575 """
544 if ipython_dir is None:
576 if ipython_dir is None:
545 ipython_dir = get_ipython_dir()
577 ipython_dir = get_ipython_dir()
546 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
578 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
547 config = cl.load_config()
579 config = cl.load_config()
548 return config
580 return config
549
581
550
582
551 def launch_new_instance():
583 def launch_new_instance():
552 """Create and run a full blown IPython instance"""
584 """Create and run a full blown IPython instance"""
553 app = IPythonApp()
585 app = IPythonApp()
554 app.start()
586 app.start()
555
587
@@ -1,2502 +1,2525 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from __future__ import with_statement
19 from __future__ import with_statement
20
20
21 import __builtin__
21 import __builtin__
22 import StringIO
22 import StringIO
23 import bdb
23 import bdb
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.core import debugger, oinspect
34 from IPython.core import debugger, oinspect
35 from IPython.core import history as ipcorehist
35 from IPython.core import history as ipcorehist
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.component import Component
41 from IPython.core.component import Component
42 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.error import TryNext, UsageError
43 from IPython.core.error import TryNext, UsageError
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
45 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prompts import CachedOutput
48 from IPython.core.prompts import CachedOutput
49 from IPython.core.pylabtools import pylab_activate
49 from IPython.core.pylabtools import pylab_activate
50 from IPython.core.usage import interactive_usage, default_banner
50 from IPython.core.usage import interactive_usage, default_banner
51 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.lib.inputhook import enable_gui
52 from IPython.lib.inputhook import enable_gui
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils import PyColorize
54 from IPython.utils import PyColorize
55 from IPython.utils import pickleshare
55 from IPython.utils import pickleshare
56 from IPython.utils.genutils import get_ipython_dir
56 from IPython.utils.genutils import get_ipython_dir
57 from IPython.utils.ipstruct import Struct
57 from IPython.utils.ipstruct import Struct
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 from IPython.utils.syspathcontext import prepended_to_syspath
61
61
62 # XXX - need to clean up this import * line
62 # XXX - need to clean up this import * line
63 from IPython.utils.genutils import *
63 from IPython.utils.genutils import *
64
64
65 # from IPython.utils import growl
65 # from IPython.utils import growl
66 # growl.start("IPython")
66 # growl.start("IPython")
67
67
68 from IPython.utils.traitlets import (
68 from IPython.utils.traitlets import (
69 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
69 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
70 )
70 )
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 # store the builtin raw_input globally, and use this always, in case user code
76 # store the builtin raw_input globally, and use this always, in case user code
77 # overwrites it (like wx.py.PyShell does)
77 # overwrites it (like wx.py.PyShell does)
78 raw_input_original = raw_input
78 raw_input_original = raw_input
79
79
80 # compiled regexps for autoindent management
80 # compiled regexps for autoindent management
81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
81 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82
82
83 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
84 # Utilities
84 # Utilities
85 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
86
86
87 ini_spaces_re = re.compile(r'^(\s+)')
87 ini_spaces_re = re.compile(r'^(\s+)')
88
88
89
89
90 def num_ini_spaces(strng):
90 def num_ini_spaces(strng):
91 """Return the number of initial spaces in a string"""
91 """Return the number of initial spaces in a string"""
92
92
93 ini_spaces = ini_spaces_re.match(strng)
93 ini_spaces = ini_spaces_re.match(strng)
94 if ini_spaces:
94 if ini_spaces:
95 return ini_spaces.end()
95 return ini_spaces.end()
96 else:
96 else:
97 return 0
97 return 0
98
98
99
99
100 def softspace(file, newvalue):
100 def softspace(file, newvalue):
101 """Copied from code.py, to remove the dependency"""
101 """Copied from code.py, to remove the dependency"""
102
102
103 oldvalue = 0
103 oldvalue = 0
104 try:
104 try:
105 oldvalue = file.softspace
105 oldvalue = file.softspace
106 except AttributeError:
106 except AttributeError:
107 pass
107 pass
108 try:
108 try:
109 file.softspace = newvalue
109 file.softspace = newvalue
110 except (AttributeError, TypeError):
110 except (AttributeError, TypeError):
111 # "attribute-less object" or "read-only attributes"
111 # "attribute-less object" or "read-only attributes"
112 pass
112 pass
113 return oldvalue
113 return oldvalue
114
114
115
115
116 def no_op(*a, **kw): pass
116 def no_op(*a, **kw): pass
117
117
118 class SpaceInInput(exceptions.Exception): pass
118 class SpaceInInput(exceptions.Exception): pass
119
119
120 class Bunch: pass
120 class Bunch: pass
121
121
122 class InputList(list):
122 class InputList(list):
123 """Class to store user input.
123 """Class to store user input.
124
124
125 It's basically a list, but slices return a string instead of a list, thus
125 It's basically a list, but slices return a string instead of a list, thus
126 allowing things like (assuming 'In' is an instance):
126 allowing things like (assuming 'In' is an instance):
127
127
128 exec In[4:7]
128 exec In[4:7]
129
129
130 or
130 or
131
131
132 exec In[5:9] + In[14] + In[21:25]"""
132 exec In[5:9] + In[14] + In[21:25]"""
133
133
134 def __getslice__(self,i,j):
134 def __getslice__(self,i,j):
135 return ''.join(list.__getslice__(self,i,j))
135 return ''.join(list.__getslice__(self,i,j))
136
136
137
137
138 class SyntaxTB(ultratb.ListTB):
138 class SyntaxTB(ultratb.ListTB):
139 """Extension which holds some state: the last exception value"""
139 """Extension which holds some state: the last exception value"""
140
140
141 def __init__(self,color_scheme = 'NoColor'):
141 def __init__(self,color_scheme = 'NoColor'):
142 ultratb.ListTB.__init__(self,color_scheme)
142 ultratb.ListTB.__init__(self,color_scheme)
143 self.last_syntax_error = None
143 self.last_syntax_error = None
144
144
145 def __call__(self, etype, value, elist):
145 def __call__(self, etype, value, elist):
146 self.last_syntax_error = value
146 self.last_syntax_error = value
147 ultratb.ListTB.__call__(self,etype,value,elist)
147 ultratb.ListTB.__call__(self,etype,value,elist)
148
148
149 def clear_err_state(self):
149 def clear_err_state(self):
150 """Return the current error state and clear it"""
150 """Return the current error state and clear it"""
151 e = self.last_syntax_error
151 e = self.last_syntax_error
152 self.last_syntax_error = None
152 self.last_syntax_error = None
153 return e
153 return e
154
154
155
155
156 def get_default_editor():
156 def get_default_editor():
157 try:
157 try:
158 ed = os.environ['EDITOR']
158 ed = os.environ['EDITOR']
159 except KeyError:
159 except KeyError:
160 if os.name == 'posix':
160 if os.name == 'posix':
161 ed = 'vi' # the only one guaranteed to be there!
161 ed = 'vi' # the only one guaranteed to be there!
162 else:
162 else:
163 ed = 'notepad' # same in Windows!
163 ed = 'notepad' # same in Windows!
164 return ed
164 return ed
165
165
166
166
167 def get_default_colors():
167 def get_default_colors():
168 if sys.platform=='darwin':
168 if sys.platform=='darwin':
169 return "LightBG"
169 return "LightBG"
170 elif os.name=='nt':
170 elif os.name=='nt':
171 return 'Linux'
171 return 'Linux'
172 else:
172 else:
173 return 'Linux'
173 return 'Linux'
174
174
175
175
176 class SeparateStr(Str):
176 class SeparateStr(Str):
177 """A Str subclass to validate separate_in, separate_out, etc.
177 """A Str subclass to validate separate_in, separate_out, etc.
178
178
179 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
179 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
180 """
180 """
181
181
182 def validate(self, obj, value):
182 def validate(self, obj, value):
183 if value == '0': value = ''
183 if value == '0': value = ''
184 value = value.replace('\\n','\n')
184 value = value.replace('\\n','\n')
185 return super(SeparateStr, self).validate(obj, value)
185 return super(SeparateStr, self).validate(obj, value)
186
186
187
187
188 #-----------------------------------------------------------------------------
188 #-----------------------------------------------------------------------------
189 # Main IPython class
189 # Main IPython class
190 #-----------------------------------------------------------------------------
190 #-----------------------------------------------------------------------------
191
191
192
192
193 class InteractiveShell(Component, Magic):
193 class InteractiveShell(Component, Magic):
194 """An enhanced, interactive shell for Python."""
194 """An enhanced, interactive shell for Python."""
195
195
196 autocall = Enum((0,1,2), default_value=1, config=True)
196 autocall = Enum((0,1,2), default_value=1, config=True)
197 autoedit_syntax = CBool(False, config=True)
197 autoedit_syntax = CBool(False, config=True)
198 autoindent = CBool(True, config=True)
198 autoindent = CBool(True, config=True)
199 automagic = CBool(True, config=True)
199 automagic = CBool(True, config=True)
200 banner = Str('')
200 banner = Str('')
201 banner1 = Str(default_banner, config=True)
201 banner1 = Str(default_banner, config=True)
202 banner2 = Str('', config=True)
202 banner2 = Str('', config=True)
203 cache_size = Int(1000, config=True)
203 cache_size = Int(1000, config=True)
204 color_info = CBool(True, config=True)
204 color_info = CBool(True, config=True)
205 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
205 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
206 default_value=get_default_colors(), config=True)
206 default_value=get_default_colors(), config=True)
207 confirm_exit = CBool(True, config=True)
207 confirm_exit = CBool(True, config=True)
208 debug = CBool(False, config=True)
208 debug = CBool(False, config=True)
209 deep_reload = CBool(False, config=True)
209 deep_reload = CBool(False, config=True)
210 # This display_banner only controls whether or not self.show_banner()
210 # This display_banner only controls whether or not self.show_banner()
211 # is called when mainloop/interact are called. The default is False
211 # is called when mainloop/interact are called. The default is False
212 # because for the terminal based application, the banner behavior
212 # because for the terminal based application, the banner behavior
213 # is controlled by Global.display_banner, which IPythonApp looks at
213 # is controlled by Global.display_banner, which IPythonApp looks at
214 # to determine if *it* should call show_banner() by hand or not.
214 # to determine if *it* should call show_banner() by hand or not.
215 display_banner = CBool(False) # This isn't configurable!
215 display_banner = CBool(False) # This isn't configurable!
216 embedded = CBool(False)
216 embedded = CBool(False)
217 embedded_active = CBool(False)
217 embedded_active = CBool(False)
218 editor = Str(get_default_editor(), config=True)
218 editor = Str(get_default_editor(), config=True)
219 filename = Str("<ipython console>")
219 filename = Str("<ipython console>")
220 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
220 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
221 logstart = CBool(False, config=True)
221 logstart = CBool(False, config=True)
222 logfile = Str('', config=True)
222 logfile = Str('', config=True)
223 logappend = Str('', config=True)
223 logappend = Str('', config=True)
224 object_info_string_level = Enum((0,1,2), default_value=0,
224 object_info_string_level = Enum((0,1,2), default_value=0,
225 config=True)
225 config=True)
226 pager = Str('less', config=True)
226 pager = Str('less', config=True)
227 pdb = CBool(False, config=True)
227 pdb = CBool(False, config=True)
228 pprint = CBool(True, config=True)
228 pprint = CBool(True, config=True)
229 profile = Str('', config=True)
229 profile = Str('', config=True)
230 prompt_in1 = Str('In [\\#]: ', config=True)
230 prompt_in1 = Str('In [\\#]: ', config=True)
231 prompt_in2 = Str(' .\\D.: ', config=True)
231 prompt_in2 = Str(' .\\D.: ', config=True)
232 prompt_out = Str('Out[\\#]: ', config=True)
232 prompt_out = Str('Out[\\#]: ', config=True)
233 prompts_pad_left = CBool(True, config=True)
233 prompts_pad_left = CBool(True, config=True)
234 quiet = CBool(False, config=True)
234 quiet = CBool(False, config=True)
235
235
236 readline_use = CBool(True, config=True)
236 readline_use = CBool(True, config=True)
237 readline_merge_completions = CBool(True, config=True)
237 readline_merge_completions = CBool(True, config=True)
238 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
238 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
239 readline_remove_delims = Str('-/~', config=True)
239 readline_remove_delims = Str('-/~', config=True)
240 readline_parse_and_bind = List([
240 readline_parse_and_bind = List([
241 'tab: complete',
241 'tab: complete',
242 '"\C-l": possible-completions',
242 '"\C-l": possible-completions',
243 'set show-all-if-ambiguous on',
243 'set show-all-if-ambiguous on',
244 '"\C-o": tab-insert',
244 '"\C-o": tab-insert',
245 '"\M-i": " "',
245 '"\M-i": " "',
246 '"\M-o": "\d\d\d\d"',
246 '"\M-o": "\d\d\d\d"',
247 '"\M-I": "\d\d\d\d"',
247 '"\M-I": "\d\d\d\d"',
248 '"\C-r": reverse-search-history',
248 '"\C-r": reverse-search-history',
249 '"\C-s": forward-search-history',
249 '"\C-s": forward-search-history',
250 '"\C-p": history-search-backward',
250 '"\C-p": history-search-backward',
251 '"\C-n": history-search-forward',
251 '"\C-n": history-search-forward',
252 '"\e[A": history-search-backward',
252 '"\e[A": history-search-backward',
253 '"\e[B": history-search-forward',
253 '"\e[B": history-search-forward',
254 '"\C-k": kill-line',
254 '"\C-k": kill-line',
255 '"\C-u": unix-line-discard',
255 '"\C-u": unix-line-discard',
256 ], allow_none=False, config=True)
256 ], allow_none=False, config=True)
257
257
258 screen_length = Int(0, config=True)
258 screen_length = Int(0, config=True)
259
259
260 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
260 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
261 separate_in = SeparateStr('\n', config=True)
261 separate_in = SeparateStr('\n', config=True)
262 separate_out = SeparateStr('', config=True)
262 separate_out = SeparateStr('', config=True)
263 separate_out2 = SeparateStr('', config=True)
263 separate_out2 = SeparateStr('', config=True)
264
264
265 system_header = Str('IPython system call: ', config=True)
265 system_header = Str('IPython system call: ', config=True)
266 system_verbose = CBool(False, config=True)
266 system_verbose = CBool(False, config=True)
267 term_title = CBool(False, config=True)
267 term_title = CBool(False, config=True)
268 wildcards_case_sensitive = CBool(True, config=True)
268 wildcards_case_sensitive = CBool(True, config=True)
269 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
269 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
270 default_value='Context', config=True)
270 default_value='Context', config=True)
271
271
272 autoexec = List(allow_none=False)
272 autoexec = List(allow_none=False)
273
273
274 # class attribute to indicate whether the class supports threads or not.
274 # class attribute to indicate whether the class supports threads or not.
275 # Subclasses with thread support should override this as needed.
275 # Subclasses with thread support should override this as needed.
276 isthreaded = False
276 isthreaded = False
277
277
278 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
278 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
279 user_ns=None, user_global_ns=None,
279 user_ns=None, user_global_ns=None,
280 banner1=None, banner2=None, display_banner=None,
280 banner1=None, banner2=None, display_banner=None,
281 custom_exceptions=((),None)):
281 custom_exceptions=((),None)):
282
282
283 # This is where traitlets with a config_key argument are updated
283 # This is where traitlets with a config_key argument are updated
284 # from the values on config.
284 # from the values on config.
285 super(InteractiveShell, self).__init__(parent, config=config)
285 super(InteractiveShell, self).__init__(parent, config=config)
286
286
287 # These are relatively independent and stateless
287 # These are relatively independent and stateless
288 self.init_ipython_dir(ipython_dir)
288 self.init_ipython_dir(ipython_dir)
289 self.init_instance_attrs()
289 self.init_instance_attrs()
290 self.init_term_title()
290 self.init_term_title()
291 self.init_usage(usage)
291 self.init_usage(usage)
292 self.init_banner(banner1, banner2, display_banner)
292 self.init_banner(banner1, banner2, display_banner)
293
293
294 # Create namespaces (user_ns, user_global_ns, etc.)
294 # Create namespaces (user_ns, user_global_ns, etc.)
295 self.init_create_namespaces(user_ns, user_global_ns)
295 self.init_create_namespaces(user_ns, user_global_ns)
296 # This has to be done after init_create_namespaces because it uses
296 # This has to be done after init_create_namespaces because it uses
297 # something in self.user_ns, but before init_sys_modules, which
297 # something in self.user_ns, but before init_sys_modules, which
298 # is the first thing to modify sys.
298 # is the first thing to modify sys.
299 self.save_sys_module_state()
299 self.save_sys_module_state()
300 self.init_sys_modules()
300 self.init_sys_modules()
301
301
302 self.init_history()
302 self.init_history()
303 self.init_encoding()
303 self.init_encoding()
304 self.init_prefilter()
304 self.init_prefilter()
305
305
306 Magic.__init__(self, self)
306 Magic.__init__(self, self)
307
307
308 self.init_syntax_highlighting()
308 self.init_syntax_highlighting()
309 self.init_hooks()
309 self.init_hooks()
310 self.init_pushd_popd_magic()
310 self.init_pushd_popd_magic()
311 self.init_traceback_handlers(custom_exceptions)
311 self.init_traceback_handlers(custom_exceptions)
312 self.init_user_ns()
312 self.init_user_ns()
313 self.init_logger()
313 self.init_logger()
314 self.init_alias()
314 self.init_alias()
315 self.init_builtins()
315 self.init_builtins()
316
316
317 # pre_config_initialization
317 # pre_config_initialization
318 self.init_shadow_hist()
318 self.init_shadow_hist()
319
319
320 # The next section should contain averything that was in ipmaker.
320 # The next section should contain averything that was in ipmaker.
321 self.init_logstart()
321 self.init_logstart()
322
322
323 # The following was in post_config_initialization
323 # The following was in post_config_initialization
324 self.init_inspector()
324 self.init_inspector()
325 self.init_readline()
325 self.init_readline()
326 self.init_prompts()
326 self.init_prompts()
327 self.init_displayhook()
327 self.init_displayhook()
328 self.init_reload_doctest()
328 self.init_reload_doctest()
329 self.init_magics()
329 self.init_magics()
330 self.init_pdb()
330 self.init_pdb()
331 self.hooks.late_startup_hook()
331 self.hooks.late_startup_hook()
332
332
333 def get_ipython(self):
333 def get_ipython(self):
334 return self
334 return self
335
335
336 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
337 # Traitlet changed handlers
337 # Traitlet changed handlers
338 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
339
339
340 def _banner1_changed(self):
340 def _banner1_changed(self):
341 self.compute_banner()
341 self.compute_banner()
342
342
343 def _banner2_changed(self):
343 def _banner2_changed(self):
344 self.compute_banner()
344 self.compute_banner()
345
345
346 def _ipython_dir_changed(self, name, new):
346 def _ipython_dir_changed(self, name, new):
347 if not os.path.isdir(new):
347 if not os.path.isdir(new):
348 os.makedirs(new, mode = 0777)
348 os.makedirs(new, mode = 0777)
349 if not os.path.isdir(self.ipython_extension_dir):
349 if not os.path.isdir(self.ipython_extension_dir):
350 os.makedirs(self.ipython_extension_dir, mode = 0777)
350 os.makedirs(self.ipython_extension_dir, mode = 0777)
351
351
352 @property
352 @property
353 def ipython_extension_dir(self):
353 def ipython_extension_dir(self):
354 return os.path.join(self.ipython_dir, 'extensions')
354 return os.path.join(self.ipython_dir, 'extensions')
355
355
356 @property
356 @property
357 def usable_screen_length(self):
357 def usable_screen_length(self):
358 if self.screen_length == 0:
358 if self.screen_length == 0:
359 return 0
359 return 0
360 else:
360 else:
361 num_lines_bot = self.separate_in.count('\n')+1
361 num_lines_bot = self.separate_in.count('\n')+1
362 return self.screen_length - num_lines_bot
362 return self.screen_length - num_lines_bot
363
363
364 def _term_title_changed(self, name, new_value):
364 def _term_title_changed(self, name, new_value):
365 self.init_term_title()
365 self.init_term_title()
366
366
367 def set_autoindent(self,value=None):
367 def set_autoindent(self,value=None):
368 """Set the autoindent flag, checking for readline support.
368 """Set the autoindent flag, checking for readline support.
369
369
370 If called with no arguments, it acts as a toggle."""
370 If called with no arguments, it acts as a toggle."""
371
371
372 if not self.has_readline:
372 if not self.has_readline:
373 if os.name == 'posix':
373 if os.name == 'posix':
374 warn("The auto-indent feature requires the readline library")
374 warn("The auto-indent feature requires the readline library")
375 self.autoindent = 0
375 self.autoindent = 0
376 return
376 return
377 if value is None:
377 if value is None:
378 self.autoindent = not self.autoindent
378 self.autoindent = not self.autoindent
379 else:
379 else:
380 self.autoindent = value
380 self.autoindent = value
381
381
382 #-------------------------------------------------------------------------
382 #-------------------------------------------------------------------------
383 # init_* methods called by __init__
383 # init_* methods called by __init__
384 #-------------------------------------------------------------------------
384 #-------------------------------------------------------------------------
385
385
386 def init_ipython_dir(self, ipython_dir):
386 def init_ipython_dir(self, ipython_dir):
387 if ipython_dir is not None:
387 if ipython_dir is not None:
388 self.ipython_dir = ipython_dir
388 self.ipython_dir = ipython_dir
389 self.config.Global.ipython_dir = self.ipython_dir
389 self.config.Global.ipython_dir = self.ipython_dir
390 return
390 return
391
391
392 if hasattr(self.config.Global, 'ipython_dir'):
392 if hasattr(self.config.Global, 'ipython_dir'):
393 self.ipython_dir = self.config.Global.ipython_dir
393 self.ipython_dir = self.config.Global.ipython_dir
394 else:
394 else:
395 self.ipython_dir = get_ipython_dir()
395 self.ipython_dir = get_ipython_dir()
396
396
397 # All children can just read this
397 # All children can just read this
398 self.config.Global.ipython_dir = self.ipython_dir
398 self.config.Global.ipython_dir = self.ipython_dir
399
399
400 def init_instance_attrs(self):
400 def init_instance_attrs(self):
401 self.jobs = BackgroundJobManager()
401 self.jobs = BackgroundJobManager()
402 self.more = False
402 self.more = False
403
403
404 # command compiler
404 # command compiler
405 self.compile = codeop.CommandCompiler()
405 self.compile = codeop.CommandCompiler()
406
406
407 # User input buffer
407 # User input buffer
408 self.buffer = []
408 self.buffer = []
409
409
410 # Make an empty namespace, which extension writers can rely on both
410 # Make an empty namespace, which extension writers can rely on both
411 # existing and NEVER being used by ipython itself. This gives them a
411 # existing and NEVER being used by ipython itself. This gives them a
412 # convenient location for storing additional information and state
412 # convenient location for storing additional information and state
413 # their extensions may require, without fear of collisions with other
413 # their extensions may require, without fear of collisions with other
414 # ipython names that may develop later.
414 # ipython names that may develop later.
415 self.meta = Struct()
415 self.meta = Struct()
416
416
417 # Object variable to store code object waiting execution. This is
417 # Object variable to store code object waiting execution. This is
418 # used mainly by the multithreaded shells, but it can come in handy in
418 # used mainly by the multithreaded shells, but it can come in handy in
419 # other situations. No need to use a Queue here, since it's a single
419 # other situations. No need to use a Queue here, since it's a single
420 # item which gets cleared once run.
420 # item which gets cleared once run.
421 self.code_to_run = None
421 self.code_to_run = None
422
422
423 # Flag to mark unconditional exit
423 # Flag to mark unconditional exit
424 self.exit_now = False
424 self.exit_now = False
425
425
426 # Temporary files used for various purposes. Deleted at exit.
426 # Temporary files used for various purposes. Deleted at exit.
427 self.tempfiles = []
427 self.tempfiles = []
428
428
429 # Keep track of readline usage (later set by init_readline)
429 # Keep track of readline usage (later set by init_readline)
430 self.has_readline = False
430 self.has_readline = False
431
431
432 # keep track of where we started running (mainly for crash post-mortem)
432 # keep track of where we started running (mainly for crash post-mortem)
433 # This is not being used anywhere currently.
433 # This is not being used anywhere currently.
434 self.starting_dir = os.getcwd()
434 self.starting_dir = os.getcwd()
435
435
436 # Indentation management
436 # Indentation management
437 self.indent_current_nsp = 0
437 self.indent_current_nsp = 0
438
438
439 def init_term_title(self):
439 def init_term_title(self):
440 # Enable or disable the terminal title.
440 # Enable or disable the terminal title.
441 if self.term_title:
441 if self.term_title:
442 toggle_set_term_title(True)
442 toggle_set_term_title(True)
443 set_term_title('IPython: ' + abbrev_cwd())
443 set_term_title('IPython: ' + abbrev_cwd())
444 else:
444 else:
445 toggle_set_term_title(False)
445 toggle_set_term_title(False)
446
446
447 def init_usage(self, usage=None):
447 def init_usage(self, usage=None):
448 if usage is None:
448 if usage is None:
449 self.usage = interactive_usage
449 self.usage = interactive_usage
450 else:
450 else:
451 self.usage = usage
451 self.usage = usage
452
452
453 def init_encoding(self):
453 def init_encoding(self):
454 # Get system encoding at startup time. Certain terminals (like Emacs
454 # Get system encoding at startup time. Certain terminals (like Emacs
455 # under Win32 have it set to None, and we need to have a known valid
455 # under Win32 have it set to None, and we need to have a known valid
456 # encoding to use in the raw_input() method
456 # encoding to use in the raw_input() method
457 try:
457 try:
458 self.stdin_encoding = sys.stdin.encoding or 'ascii'
458 self.stdin_encoding = sys.stdin.encoding or 'ascii'
459 except AttributeError:
459 except AttributeError:
460 self.stdin_encoding = 'ascii'
460 self.stdin_encoding = 'ascii'
461
461
462 def init_syntax_highlighting(self):
462 def init_syntax_highlighting(self):
463 # Python source parser/formatter for syntax highlighting
463 # Python source parser/formatter for syntax highlighting
464 pyformat = PyColorize.Parser().format
464 pyformat = PyColorize.Parser().format
465 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
465 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
466
466
467 def init_pushd_popd_magic(self):
467 def init_pushd_popd_magic(self):
468 # for pushd/popd management
468 # for pushd/popd management
469 try:
469 try:
470 self.home_dir = get_home_dir()
470 self.home_dir = get_home_dir()
471 except HomeDirError, msg:
471 except HomeDirError, msg:
472 fatal(msg)
472 fatal(msg)
473
473
474 self.dir_stack = []
474 self.dir_stack = []
475
475
476 def init_logger(self):
476 def init_logger(self):
477 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
477 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
478 # local shortcut, this is used a LOT
478 # local shortcut, this is used a LOT
479 self.log = self.logger.log
479 self.log = self.logger.log
480
480
481 def init_logstart(self):
481 def init_logstart(self):
482 if self.logappend:
482 if self.logappend:
483 self.magic_logstart(self.logappend + ' append')
483 self.magic_logstart(self.logappend + ' append')
484 elif self.logfile:
484 elif self.logfile:
485 self.magic_logstart(self.logfile)
485 self.magic_logstart(self.logfile)
486 elif self.logstart:
486 elif self.logstart:
487 self.magic_logstart()
487 self.magic_logstart()
488
488
489 def init_builtins(self):
489 def init_builtins(self):
490 self.builtin_trap = BuiltinTrap(self)
490 self.builtin_trap = BuiltinTrap(self)
491
491
492 def init_inspector(self):
492 def init_inspector(self):
493 # Object inspector
493 # Object inspector
494 self.inspector = oinspect.Inspector(oinspect.InspectColors,
494 self.inspector = oinspect.Inspector(oinspect.InspectColors,
495 PyColorize.ANSICodeColors,
495 PyColorize.ANSICodeColors,
496 'NoColor',
496 'NoColor',
497 self.object_info_string_level)
497 self.object_info_string_level)
498
498
499 def init_prompts(self):
499 def init_prompts(self):
500 # Initialize cache, set in/out prompts and printing system
500 # Initialize cache, set in/out prompts and printing system
501 self.outputcache = CachedOutput(self,
501 self.outputcache = CachedOutput(self,
502 self.cache_size,
502 self.cache_size,
503 self.pprint,
503 self.pprint,
504 input_sep = self.separate_in,
504 input_sep = self.separate_in,
505 output_sep = self.separate_out,
505 output_sep = self.separate_out,
506 output_sep2 = self.separate_out2,
506 output_sep2 = self.separate_out2,
507 ps1 = self.prompt_in1,
507 ps1 = self.prompt_in1,
508 ps2 = self.prompt_in2,
508 ps2 = self.prompt_in2,
509 ps_out = self.prompt_out,
509 ps_out = self.prompt_out,
510 pad_left = self.prompts_pad_left)
510 pad_left = self.prompts_pad_left)
511
511
512 # user may have over-ridden the default print hook:
512 # user may have over-ridden the default print hook:
513 try:
513 try:
514 self.outputcache.__class__.display = self.hooks.display
514 self.outputcache.__class__.display = self.hooks.display
515 except AttributeError:
515 except AttributeError:
516 pass
516 pass
517
517
518 def init_displayhook(self):
518 def init_displayhook(self):
519 self.display_trap = DisplayTrap(self, self.outputcache)
519 self.display_trap = DisplayTrap(self, self.outputcache)
520
520
521 def init_reload_doctest(self):
521 def init_reload_doctest(self):
522 # Do a proper resetting of doctest, including the necessary displayhook
522 # Do a proper resetting of doctest, including the necessary displayhook
523 # monkeypatching
523 # monkeypatching
524 try:
524 try:
525 doctest_reload()
525 doctest_reload()
526 except ImportError:
526 except ImportError:
527 warn("doctest module does not exist.")
527 warn("doctest module does not exist.")
528
528
529 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
530 # Things related to the banner
530 # Things related to the banner
531 #-------------------------------------------------------------------------
531 #-------------------------------------------------------------------------
532
532
533 def init_banner(self, banner1, banner2, display_banner):
533 def init_banner(self, banner1, banner2, display_banner):
534 if banner1 is not None:
534 if banner1 is not None:
535 self.banner1 = banner1
535 self.banner1 = banner1
536 if banner2 is not None:
536 if banner2 is not None:
537 self.banner2 = banner2
537 self.banner2 = banner2
538 if display_banner is not None:
538 if display_banner is not None:
539 self.display_banner = display_banner
539 self.display_banner = display_banner
540 self.compute_banner()
540 self.compute_banner()
541
541
542 def show_banner(self, banner=None):
542 def show_banner(self, banner=None):
543 if banner is None:
543 if banner is None:
544 banner = self.banner
544 banner = self.banner
545 self.write(banner)
545 self.write(banner)
546
546
547 def compute_banner(self):
547 def compute_banner(self):
548 self.banner = self.banner1 + '\n'
548 self.banner = self.banner1 + '\n'
549 if self.profile:
549 if self.profile:
550 self.banner += '\nIPython profile: %s\n' % self.profile
550 self.banner += '\nIPython profile: %s\n' % self.profile
551 if self.banner2:
551 if self.banner2:
552 self.banner += '\n' + self.banner2 + '\n'
552 self.banner += '\n' + self.banner2 + '\n'
553
553
554 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
555 # Things related to injections into the sys module
555 # Things related to injections into the sys module
556 #-------------------------------------------------------------------------
556 #-------------------------------------------------------------------------
557
557
558 def save_sys_module_state(self):
558 def save_sys_module_state(self):
559 """Save the state of hooks in the sys module.
559 """Save the state of hooks in the sys module.
560
560
561 This has to be called after self.user_ns is created.
561 This has to be called after self.user_ns is created.
562 """
562 """
563 self._orig_sys_module_state = {}
563 self._orig_sys_module_state = {}
564 self._orig_sys_module_state['stdin'] = sys.stdin
564 self._orig_sys_module_state['stdin'] = sys.stdin
565 self._orig_sys_module_state['stdout'] = sys.stdout
565 self._orig_sys_module_state['stdout'] = sys.stdout
566 self._orig_sys_module_state['stderr'] = sys.stderr
566 self._orig_sys_module_state['stderr'] = sys.stderr
567 self._orig_sys_module_state['excepthook'] = sys.excepthook
567 self._orig_sys_module_state['excepthook'] = sys.excepthook
568 try:
568 try:
569 self._orig_sys_modules_main_name = self.user_ns['__name__']
569 self._orig_sys_modules_main_name = self.user_ns['__name__']
570 except KeyError:
570 except KeyError:
571 pass
571 pass
572
572
573 def restore_sys_module_state(self):
573 def restore_sys_module_state(self):
574 """Restore the state of the sys module."""
574 """Restore the state of the sys module."""
575 try:
575 try:
576 for k, v in self._orig_sys_module_state.items():
576 for k, v in self._orig_sys_module_state.items():
577 setattr(sys, k, v)
577 setattr(sys, k, v)
578 except AttributeError:
578 except AttributeError:
579 pass
579 pass
580 try:
580 try:
581 delattr(sys, 'ipcompleter')
581 delattr(sys, 'ipcompleter')
582 except AttributeError:
582 except AttributeError:
583 pass
583 pass
584 # Reset what what done in self.init_sys_modules
584 # Reset what what done in self.init_sys_modules
585 try:
585 try:
586 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
586 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
587 except (AttributeError, KeyError):
587 except (AttributeError, KeyError):
588 pass
588 pass
589
589
590 #-------------------------------------------------------------------------
590 #-------------------------------------------------------------------------
591 # Things related to hooks
591 # Things related to hooks
592 #-------------------------------------------------------------------------
592 #-------------------------------------------------------------------------
593
593
594 def init_hooks(self):
594 def init_hooks(self):
595 # hooks holds pointers used for user-side customizations
595 # hooks holds pointers used for user-side customizations
596 self.hooks = Struct()
596 self.hooks = Struct()
597
597
598 self.strdispatchers = {}
598 self.strdispatchers = {}
599
599
600 # Set all default hooks, defined in the IPython.hooks module.
600 # Set all default hooks, defined in the IPython.hooks module.
601 import IPython.core.hooks
601 import IPython.core.hooks
602 hooks = IPython.core.hooks
602 hooks = IPython.core.hooks
603 for hook_name in hooks.__all__:
603 for hook_name in hooks.__all__:
604 # default hooks have priority 100, i.e. low; user hooks should have
604 # default hooks have priority 100, i.e. low; user hooks should have
605 # 0-100 priority
605 # 0-100 priority
606 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
606 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
607
607
608 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
608 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
609 """set_hook(name,hook) -> sets an internal IPython hook.
609 """set_hook(name,hook) -> sets an internal IPython hook.
610
610
611 IPython exposes some of its internal API as user-modifiable hooks. By
611 IPython exposes some of its internal API as user-modifiable hooks. By
612 adding your function to one of these hooks, you can modify IPython's
612 adding your function to one of these hooks, you can modify IPython's
613 behavior to call at runtime your own routines."""
613 behavior to call at runtime your own routines."""
614
614
615 # At some point in the future, this should validate the hook before it
615 # At some point in the future, this should validate the hook before it
616 # accepts it. Probably at least check that the hook takes the number
616 # accepts it. Probably at least check that the hook takes the number
617 # of args it's supposed to.
617 # of args it's supposed to.
618
618
619 f = new.instancemethod(hook,self,self.__class__)
619 f = new.instancemethod(hook,self,self.__class__)
620
620
621 # check if the hook is for strdispatcher first
621 # check if the hook is for strdispatcher first
622 if str_key is not None:
622 if str_key is not None:
623 sdp = self.strdispatchers.get(name, StrDispatch())
623 sdp = self.strdispatchers.get(name, StrDispatch())
624 sdp.add_s(str_key, f, priority )
624 sdp.add_s(str_key, f, priority )
625 self.strdispatchers[name] = sdp
625 self.strdispatchers[name] = sdp
626 return
626 return
627 if re_key is not None:
627 if re_key is not None:
628 sdp = self.strdispatchers.get(name, StrDispatch())
628 sdp = self.strdispatchers.get(name, StrDispatch())
629 sdp.add_re(re.compile(re_key), f, priority )
629 sdp.add_re(re.compile(re_key), f, priority )
630 self.strdispatchers[name] = sdp
630 self.strdispatchers[name] = sdp
631 return
631 return
632
632
633 dp = getattr(self.hooks, name, None)
633 dp = getattr(self.hooks, name, None)
634 if name not in IPython.core.hooks.__all__:
634 if name not in IPython.core.hooks.__all__:
635 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
635 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
636 if not dp:
636 if not dp:
637 dp = IPython.core.hooks.CommandChainDispatcher()
637 dp = IPython.core.hooks.CommandChainDispatcher()
638
638
639 try:
639 try:
640 dp.add(f,priority)
640 dp.add(f,priority)
641 except AttributeError:
641 except AttributeError:
642 # it was not commandchain, plain old func - replace
642 # it was not commandchain, plain old func - replace
643 dp = f
643 dp = f
644
644
645 setattr(self.hooks,name, dp)
645 setattr(self.hooks,name, dp)
646
646
647 #-------------------------------------------------------------------------
647 #-------------------------------------------------------------------------
648 # Things related to the "main" module
648 # Things related to the "main" module
649 #-------------------------------------------------------------------------
649 #-------------------------------------------------------------------------
650
650
651 def new_main_mod(self,ns=None):
651 def new_main_mod(self,ns=None):
652 """Return a new 'main' module object for user code execution.
652 """Return a new 'main' module object for user code execution.
653 """
653 """
654 main_mod = self._user_main_module
654 main_mod = self._user_main_module
655 init_fakemod_dict(main_mod,ns)
655 init_fakemod_dict(main_mod,ns)
656 return main_mod
656 return main_mod
657
657
658 def cache_main_mod(self,ns,fname):
658 def cache_main_mod(self,ns,fname):
659 """Cache a main module's namespace.
659 """Cache a main module's namespace.
660
660
661 When scripts are executed via %run, we must keep a reference to the
661 When scripts are executed via %run, we must keep a reference to the
662 namespace of their __main__ module (a FakeModule instance) around so
662 namespace of their __main__ module (a FakeModule instance) around so
663 that Python doesn't clear it, rendering objects defined therein
663 that Python doesn't clear it, rendering objects defined therein
664 useless.
664 useless.
665
665
666 This method keeps said reference in a private dict, keyed by the
666 This method keeps said reference in a private dict, keyed by the
667 absolute path of the module object (which corresponds to the script
667 absolute path of the module object (which corresponds to the script
668 path). This way, for multiple executions of the same script we only
668 path). This way, for multiple executions of the same script we only
669 keep one copy of the namespace (the last one), thus preventing memory
669 keep one copy of the namespace (the last one), thus preventing memory
670 leaks from old references while allowing the objects from the last
670 leaks from old references while allowing the objects from the last
671 execution to be accessible.
671 execution to be accessible.
672
672
673 Note: we can not allow the actual FakeModule instances to be deleted,
673 Note: we can not allow the actual FakeModule instances to be deleted,
674 because of how Python tears down modules (it hard-sets all their
674 because of how Python tears down modules (it hard-sets all their
675 references to None without regard for reference counts). This method
675 references to None without regard for reference counts). This method
676 must therefore make a *copy* of the given namespace, to allow the
676 must therefore make a *copy* of the given namespace, to allow the
677 original module's __dict__ to be cleared and reused.
677 original module's __dict__ to be cleared and reused.
678
678
679
679
680 Parameters
680 Parameters
681 ----------
681 ----------
682 ns : a namespace (a dict, typically)
682 ns : a namespace (a dict, typically)
683
683
684 fname : str
684 fname : str
685 Filename associated with the namespace.
685 Filename associated with the namespace.
686
686
687 Examples
687 Examples
688 --------
688 --------
689
689
690 In [10]: import IPython
690 In [10]: import IPython
691
691
692 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
692 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
693
693
694 In [12]: IPython.__file__ in _ip._main_ns_cache
694 In [12]: IPython.__file__ in _ip._main_ns_cache
695 Out[12]: True
695 Out[12]: True
696 """
696 """
697 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
697 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
698
698
699 def clear_main_mod_cache(self):
699 def clear_main_mod_cache(self):
700 """Clear the cache of main modules.
700 """Clear the cache of main modules.
701
701
702 Mainly for use by utilities like %reset.
702 Mainly for use by utilities like %reset.
703
703
704 Examples
704 Examples
705 --------
705 --------
706
706
707 In [15]: import IPython
707 In [15]: import IPython
708
708
709 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
709 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
710
710
711 In [17]: len(_ip._main_ns_cache) > 0
711 In [17]: len(_ip._main_ns_cache) > 0
712 Out[17]: True
712 Out[17]: True
713
713
714 In [18]: _ip.clear_main_mod_cache()
714 In [18]: _ip.clear_main_mod_cache()
715
715
716 In [19]: len(_ip._main_ns_cache) == 0
716 In [19]: len(_ip._main_ns_cache) == 0
717 Out[19]: True
717 Out[19]: True
718 """
718 """
719 self._main_ns_cache.clear()
719 self._main_ns_cache.clear()
720
720
721 #-------------------------------------------------------------------------
721 #-------------------------------------------------------------------------
722 # Things related to debugging
722 # Things related to debugging
723 #-------------------------------------------------------------------------
723 #-------------------------------------------------------------------------
724
724
725 def init_pdb(self):
725 def init_pdb(self):
726 # Set calling of pdb on exceptions
726 # Set calling of pdb on exceptions
727 # self.call_pdb is a property
727 # self.call_pdb is a property
728 self.call_pdb = self.pdb
728 self.call_pdb = self.pdb
729
729
730 def _get_call_pdb(self):
730 def _get_call_pdb(self):
731 return self._call_pdb
731 return self._call_pdb
732
732
733 def _set_call_pdb(self,val):
733 def _set_call_pdb(self,val):
734
734
735 if val not in (0,1,False,True):
735 if val not in (0,1,False,True):
736 raise ValueError,'new call_pdb value must be boolean'
736 raise ValueError,'new call_pdb value must be boolean'
737
737
738 # store value in instance
738 # store value in instance
739 self._call_pdb = val
739 self._call_pdb = val
740
740
741 # notify the actual exception handlers
741 # notify the actual exception handlers
742 self.InteractiveTB.call_pdb = val
742 self.InteractiveTB.call_pdb = val
743 if self.isthreaded:
743 if self.isthreaded:
744 try:
744 try:
745 self.sys_excepthook.call_pdb = val
745 self.sys_excepthook.call_pdb = val
746 except:
746 except:
747 warn('Failed to activate pdb for threaded exception handler')
747 warn('Failed to activate pdb for threaded exception handler')
748
748
749 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
749 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
750 'Control auto-activation of pdb at exceptions')
750 'Control auto-activation of pdb at exceptions')
751
751
752 def debugger(self,force=False):
752 def debugger(self,force=False):
753 """Call the pydb/pdb debugger.
753 """Call the pydb/pdb debugger.
754
754
755 Keywords:
755 Keywords:
756
756
757 - force(False): by default, this routine checks the instance call_pdb
757 - force(False): by default, this routine checks the instance call_pdb
758 flag and does not actually invoke the debugger if the flag is false.
758 flag and does not actually invoke the debugger if the flag is false.
759 The 'force' option forces the debugger to activate even if the flag
759 The 'force' option forces the debugger to activate even if the flag
760 is false.
760 is false.
761 """
761 """
762
762
763 if not (force or self.call_pdb):
763 if not (force or self.call_pdb):
764 return
764 return
765
765
766 if not hasattr(sys,'last_traceback'):
766 if not hasattr(sys,'last_traceback'):
767 error('No traceback has been produced, nothing to debug.')
767 error('No traceback has been produced, nothing to debug.')
768 return
768 return
769
769
770 # use pydb if available
770 # use pydb if available
771 if debugger.has_pydb:
771 if debugger.has_pydb:
772 from pydb import pm
772 from pydb import pm
773 else:
773 else:
774 # fallback to our internal debugger
774 # fallback to our internal debugger
775 pm = lambda : self.InteractiveTB.debugger(force=True)
775 pm = lambda : self.InteractiveTB.debugger(force=True)
776 self.history_saving_wrapper(pm)()
776 self.history_saving_wrapper(pm)()
777
777
778 #-------------------------------------------------------------------------
778 #-------------------------------------------------------------------------
779 # Things related to IPython's various namespaces
779 # Things related to IPython's various namespaces
780 #-------------------------------------------------------------------------
780 #-------------------------------------------------------------------------
781
781
782 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
782 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
783 # Create the namespace where the user will operate. user_ns is
783 # Create the namespace where the user will operate. user_ns is
784 # normally the only one used, and it is passed to the exec calls as
784 # normally the only one used, and it is passed to the exec calls as
785 # the locals argument. But we do carry a user_global_ns namespace
785 # the locals argument. But we do carry a user_global_ns namespace
786 # given as the exec 'globals' argument, This is useful in embedding
786 # given as the exec 'globals' argument, This is useful in embedding
787 # situations where the ipython shell opens in a context where the
787 # situations where the ipython shell opens in a context where the
788 # distinction between locals and globals is meaningful. For
788 # distinction between locals and globals is meaningful. For
789 # non-embedded contexts, it is just the same object as the user_ns dict.
789 # non-embedded contexts, it is just the same object as the user_ns dict.
790
790
791 # FIXME. For some strange reason, __builtins__ is showing up at user
791 # FIXME. For some strange reason, __builtins__ is showing up at user
792 # level as a dict instead of a module. This is a manual fix, but I
792 # level as a dict instead of a module. This is a manual fix, but I
793 # should really track down where the problem is coming from. Alex
793 # should really track down where the problem is coming from. Alex
794 # Schmolck reported this problem first.
794 # Schmolck reported this problem first.
795
795
796 # A useful post by Alex Martelli on this topic:
796 # A useful post by Alex Martelli on this topic:
797 # Re: inconsistent value from __builtins__
797 # Re: inconsistent value from __builtins__
798 # Von: Alex Martelli <aleaxit@yahoo.com>
798 # Von: Alex Martelli <aleaxit@yahoo.com>
799 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
799 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
800 # Gruppen: comp.lang.python
800 # Gruppen: comp.lang.python
801
801
802 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
802 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
803 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
803 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
804 # > <type 'dict'>
804 # > <type 'dict'>
805 # > >>> print type(__builtins__)
805 # > >>> print type(__builtins__)
806 # > <type 'module'>
806 # > <type 'module'>
807 # > Is this difference in return value intentional?
807 # > Is this difference in return value intentional?
808
808
809 # Well, it's documented that '__builtins__' can be either a dictionary
809 # Well, it's documented that '__builtins__' can be either a dictionary
810 # or a module, and it's been that way for a long time. Whether it's
810 # or a module, and it's been that way for a long time. Whether it's
811 # intentional (or sensible), I don't know. In any case, the idea is
811 # intentional (or sensible), I don't know. In any case, the idea is
812 # that if you need to access the built-in namespace directly, you
812 # that if you need to access the built-in namespace directly, you
813 # should start with "import __builtin__" (note, no 's') which will
813 # should start with "import __builtin__" (note, no 's') which will
814 # definitely give you a module. Yeah, it's somewhat confusing:-(.
814 # definitely give you a module. Yeah, it's somewhat confusing:-(.
815
815
816 # These routines return properly built dicts as needed by the rest of
816 # These routines return properly built dicts as needed by the rest of
817 # the code, and can also be used by extension writers to generate
817 # the code, and can also be used by extension writers to generate
818 # properly initialized namespaces.
818 # properly initialized namespaces.
819 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
819 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
820 user_global_ns)
820 user_global_ns)
821
821
822 # Assign namespaces
822 # Assign namespaces
823 # This is the namespace where all normal user variables live
823 # This is the namespace where all normal user variables live
824 self.user_ns = user_ns
824 self.user_ns = user_ns
825 self.user_global_ns = user_global_ns
825 self.user_global_ns = user_global_ns
826
826
827 # An auxiliary namespace that checks what parts of the user_ns were
827 # An auxiliary namespace that checks what parts of the user_ns were
828 # loaded at startup, so we can list later only variables defined in
828 # loaded at startup, so we can list later only variables defined in
829 # actual interactive use. Since it is always a subset of user_ns, it
829 # actual interactive use. Since it is always a subset of user_ns, it
830 # doesn't need to be seaparately tracked in the ns_table
830 # doesn't need to be separately tracked in the ns_table.
831 self.user_config_ns = {}
831 self.user_config_ns = {}
832
832
833 # A namespace to keep track of internal data structures to prevent
833 # A namespace to keep track of internal data structures to prevent
834 # them from cluttering user-visible stuff. Will be updated later
834 # them from cluttering user-visible stuff. Will be updated later
835 self.internal_ns = {}
835 self.internal_ns = {}
836
836
837 # Now that FakeModule produces a real module, we've run into a nasty
837 # Now that FakeModule produces a real module, we've run into a nasty
838 # problem: after script execution (via %run), the module where the user
838 # problem: after script execution (via %run), the module where the user
839 # code ran is deleted. Now that this object is a true module (needed
839 # code ran is deleted. Now that this object is a true module (needed
840 # so docetst and other tools work correctly), the Python module
840 # so docetst and other tools work correctly), the Python module
841 # teardown mechanism runs over it, and sets to None every variable
841 # teardown mechanism runs over it, and sets to None every variable
842 # present in that module. Top-level references to objects from the
842 # present in that module. Top-level references to objects from the
843 # script survive, because the user_ns is updated with them. However,
843 # script survive, because the user_ns is updated with them. However,
844 # calling functions defined in the script that use other things from
844 # calling functions defined in the script that use other things from
845 # the script will fail, because the function's closure had references
845 # the script will fail, because the function's closure had references
846 # to the original objects, which are now all None. So we must protect
846 # to the original objects, which are now all None. So we must protect
847 # these modules from deletion by keeping a cache.
847 # these modules from deletion by keeping a cache.
848 #
848 #
849 # To avoid keeping stale modules around (we only need the one from the
849 # To avoid keeping stale modules around (we only need the one from the
850 # last run), we use a dict keyed with the full path to the script, so
850 # last run), we use a dict keyed with the full path to the script, so
851 # only the last version of the module is held in the cache. Note,
851 # only the last version of the module is held in the cache. Note,
852 # however, that we must cache the module *namespace contents* (their
852 # however, that we must cache the module *namespace contents* (their
853 # __dict__). Because if we try to cache the actual modules, old ones
853 # __dict__). Because if we try to cache the actual modules, old ones
854 # (uncached) could be destroyed while still holding references (such as
854 # (uncached) could be destroyed while still holding references (such as
855 # those held by GUI objects that tend to be long-lived)>
855 # those held by GUI objects that tend to be long-lived)>
856 #
856 #
857 # The %reset command will flush this cache. See the cache_main_mod()
857 # The %reset command will flush this cache. See the cache_main_mod()
858 # and clear_main_mod_cache() methods for details on use.
858 # and clear_main_mod_cache() methods for details on use.
859
859
860 # This is the cache used for 'main' namespaces
860 # This is the cache used for 'main' namespaces
861 self._main_ns_cache = {}
861 self._main_ns_cache = {}
862 # And this is the single instance of FakeModule whose __dict__ we keep
862 # And this is the single instance of FakeModule whose __dict__ we keep
863 # copying and clearing for reuse on each %run
863 # copying and clearing for reuse on each %run
864 self._user_main_module = FakeModule()
864 self._user_main_module = FakeModule()
865
865
866 # A table holding all the namespaces IPython deals with, so that
866 # A table holding all the namespaces IPython deals with, so that
867 # introspection facilities can search easily.
867 # introspection facilities can search easily.
868 self.ns_table = {'user':user_ns,
868 self.ns_table = {'user':user_ns,
869 'user_global':user_global_ns,
869 'user_global':user_global_ns,
870 'internal':self.internal_ns,
870 'internal':self.internal_ns,
871 'builtin':__builtin__.__dict__
871 'builtin':__builtin__.__dict__
872 }
872 }
873
873
874 # Similarly, track all namespaces where references can be held and that
874 # Similarly, track all namespaces where references can be held and that
875 # we can safely clear (so it can NOT include builtin). This one can be
875 # we can safely clear (so it can NOT include builtin). This one can be
876 # a simple list.
876 # a simple list.
877 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
877 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
878 self.internal_ns, self._main_ns_cache ]
878 self.internal_ns, self._main_ns_cache ]
879
879
880 def init_sys_modules(self):
880 def init_sys_modules(self):
881 # We need to insert into sys.modules something that looks like a
881 # We need to insert into sys.modules something that looks like a
882 # module but which accesses the IPython namespace, for shelve and
882 # module but which accesses the IPython namespace, for shelve and
883 # pickle to work interactively. Normally they rely on getting
883 # pickle to work interactively. Normally they rely on getting
884 # everything out of __main__, but for embedding purposes each IPython
884 # everything out of __main__, but for embedding purposes each IPython
885 # instance has its own private namespace, so we can't go shoving
885 # instance has its own private namespace, so we can't go shoving
886 # everything into __main__.
886 # everything into __main__.
887
887
888 # note, however, that we should only do this for non-embedded
888 # note, however, that we should only do this for non-embedded
889 # ipythons, which really mimic the __main__.__dict__ with their own
889 # ipythons, which really mimic the __main__.__dict__ with their own
890 # namespace. Embedded instances, on the other hand, should not do
890 # namespace. Embedded instances, on the other hand, should not do
891 # this because they need to manage the user local/global namespaces
891 # this because they need to manage the user local/global namespaces
892 # only, but they live within a 'normal' __main__ (meaning, they
892 # only, but they live within a 'normal' __main__ (meaning, they
893 # shouldn't overtake the execution environment of the script they're
893 # shouldn't overtake the execution environment of the script they're
894 # embedded in).
894 # embedded in).
895
895
896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
896 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
897
897
898 try:
898 try:
899 main_name = self.user_ns['__name__']
899 main_name = self.user_ns['__name__']
900 except KeyError:
900 except KeyError:
901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
901 raise KeyError('user_ns dictionary MUST have a "__name__" key')
902 else:
902 else:
903 sys.modules[main_name] = FakeModule(self.user_ns)
903 sys.modules[main_name] = FakeModule(self.user_ns)
904
904
905 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
905 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
906 """Return a valid local and global user interactive namespaces.
906 """Return a valid local and global user interactive namespaces.
907
907
908 This builds a dict with the minimal information needed to operate as a
908 This builds a dict with the minimal information needed to operate as a
909 valid IPython user namespace, which you can pass to the various
909 valid IPython user namespace, which you can pass to the various
910 embedding classes in ipython. The default implementation returns the
910 embedding classes in ipython. The default implementation returns the
911 same dict for both the locals and the globals to allow functions to
911 same dict for both the locals and the globals to allow functions to
912 refer to variables in the namespace. Customized implementations can
912 refer to variables in the namespace. Customized implementations can
913 return different dicts. The locals dictionary can actually be anything
913 return different dicts. The locals dictionary can actually be anything
914 following the basic mapping protocol of a dict, but the globals dict
914 following the basic mapping protocol of a dict, but the globals dict
915 must be a true dict, not even a subclass. It is recommended that any
915 must be a true dict, not even a subclass. It is recommended that any
916 custom object for the locals namespace synchronize with the globals
916 custom object for the locals namespace synchronize with the globals
917 dict somehow.
917 dict somehow.
918
918
919 Raises TypeError if the provided globals namespace is not a true dict.
919 Raises TypeError if the provided globals namespace is not a true dict.
920
920
921 :Parameters:
921 :Parameters:
922 user_ns : dict-like, optional
922 user_ns : dict-like, optional
923 The current user namespace. The items in this namespace should
923 The current user namespace. The items in this namespace should
924 be included in the output. If None, an appropriate blank
924 be included in the output. If None, an appropriate blank
925 namespace should be created.
925 namespace should be created.
926 user_global_ns : dict, optional
926 user_global_ns : dict, optional
927 The current user global namespace. The items in this namespace
927 The current user global namespace. The items in this namespace
928 should be included in the output. If None, an appropriate
928 should be included in the output. If None, an appropriate
929 blank namespace should be created.
929 blank namespace should be created.
930
930
931 :Returns:
931 :Returns:
932 A tuple pair of dictionary-like object to be used as the local namespace
932 A tuple pair of dictionary-like object to be used as the local namespace
933 of the interpreter and a dict to be used as the global namespace.
933 of the interpreter and a dict to be used as the global namespace.
934 """
934 """
935
935
936 if user_ns is None:
936 if user_ns is None:
937 # Set __name__ to __main__ to better match the behavior of the
937 # Set __name__ to __main__ to better match the behavior of the
938 # normal interpreter.
938 # normal interpreter.
939 user_ns = {'__name__' :'__main__',
939 user_ns = {'__name__' :'__main__',
940 '__builtins__' : __builtin__,
940 '__builtins__' : __builtin__,
941 }
941 }
942 else:
942 else:
943 user_ns.setdefault('__name__','__main__')
943 user_ns.setdefault('__name__','__main__')
944 user_ns.setdefault('__builtins__',__builtin__)
944 user_ns.setdefault('__builtins__',__builtin__)
945
945
946 if user_global_ns is None:
946 if user_global_ns is None:
947 user_global_ns = user_ns
947 user_global_ns = user_ns
948 if type(user_global_ns) is not dict:
948 if type(user_global_ns) is not dict:
949 raise TypeError("user_global_ns must be a true dict; got %r"
949 raise TypeError("user_global_ns must be a true dict; got %r"
950 % type(user_global_ns))
950 % type(user_global_ns))
951
951
952 return user_ns, user_global_ns
952 return user_ns, user_global_ns
953
953
954 def init_user_ns(self):
954 def init_user_ns(self):
955 """Initialize all user-visible namespaces to their minimum defaults.
955 """Initialize all user-visible namespaces to their minimum defaults.
956
956
957 Certain history lists are also initialized here, as they effectively
957 Certain history lists are also initialized here, as they effectively
958 act as user namespaces.
958 act as user namespaces.
959
959
960 Notes
960 Notes
961 -----
961 -----
962 All data structures here are only filled in, they are NOT reset by this
962 All data structures here are only filled in, they are NOT reset by this
963 method. If they were not empty before, data will simply be added to
963 method. If they were not empty before, data will simply be added to
964 therm.
964 therm.
965 """
965 """
966 # Store myself as the public api!!!
966 # Store myself as the public api!!!
967 self.user_ns['get_ipython'] = self.get_ipython
967 self.user_ns['get_ipython'] = self.get_ipython
968
968
969 # make global variables for user access to the histories
969 # make global variables for user access to the histories
970 self.user_ns['_ih'] = self.input_hist
970 self.user_ns['_ih'] = self.input_hist
971 self.user_ns['_oh'] = self.output_hist
971 self.user_ns['_oh'] = self.output_hist
972 self.user_ns['_dh'] = self.dir_hist
972 self.user_ns['_dh'] = self.dir_hist
973
973
974 # user aliases to input and output histories
974 # user aliases to input and output histories
975 self.user_ns['In'] = self.input_hist
975 self.user_ns['In'] = self.input_hist
976 self.user_ns['Out'] = self.output_hist
976 self.user_ns['Out'] = self.output_hist
977
977
978 self.user_ns['_sh'] = shadowns
978 self.user_ns['_sh'] = shadowns
979
979
980 # Put 'help' in the user namespace
980 # Put 'help' in the user namespace
981 try:
981 try:
982 from site import _Helper
982 from site import _Helper
983 self.user_ns['help'] = _Helper()
983 self.user_ns['help'] = _Helper()
984 except ImportError:
984 except ImportError:
985 warn('help() not available - check site.py')
985 warn('help() not available - check site.py')
986
986
987 def reset(self):
987 def reset(self):
988 """Clear all internal namespaces.
988 """Clear all internal namespaces.
989
989
990 Note that this is much more aggressive than %reset, since it clears
990 Note that this is much more aggressive than %reset, since it clears
991 fully all namespaces, as well as all input/output lists.
991 fully all namespaces, as well as all input/output lists.
992 """
992 """
993 for ns in self.ns_refs_table:
993 for ns in self.ns_refs_table:
994 ns.clear()
994 ns.clear()
995
995
996 self.alias_manager.clear_aliases()
996 self.alias_manager.clear_aliases()
997
997
998 # Clear input and output histories
998 # Clear input and output histories
999 self.input_hist[:] = []
999 self.input_hist[:] = []
1000 self.input_hist_raw[:] = []
1000 self.input_hist_raw[:] = []
1001 self.output_hist.clear()
1001 self.output_hist.clear()
1002
1002
1003 # Restore the user namespaces to minimal usability
1003 # Restore the user namespaces to minimal usability
1004 self.init_user_ns()
1004 self.init_user_ns()
1005
1005
1006 # Restore the default and user aliases
1006 # Restore the default and user aliases
1007 self.alias_manager.init_aliases()
1007 self.alias_manager.init_aliases()
1008
1008
1009 def push(self, variables, interactive=True):
1009 def push(self, variables, interactive=True):
1010 """Inject a group of variables into the IPython user namespace.
1010 """Inject a group of variables into the IPython user namespace.
1011
1011
1012 Parameters
1012 Parameters
1013 ----------
1013 ----------
1014 variables : dict, str or list/tuple of str
1014 variables : dict, str or list/tuple of str
1015 The variables to inject into the user's namespace. If a dict,
1015 The variables to inject into the user's namespace. If a dict,
1016 a simple update is done. If a str, the string is assumed to
1016 a simple update is done. If a str, the string is assumed to
1017 have variable names separated by spaces. A list/tuple of str
1017 have variable names separated by spaces. A list/tuple of str
1018 can also be used to give the variable names. If just the variable
1018 can also be used to give the variable names. If just the variable
1019 names are give (list/tuple/str) then the variable values looked
1019 names are give (list/tuple/str) then the variable values looked
1020 up in the callers frame.
1020 up in the callers frame.
1021 interactive : bool
1021 interactive : bool
1022 If True (default), the variables will be listed with the ``who``
1022 If True (default), the variables will be listed with the ``who``
1023 magic.
1023 magic.
1024 """
1024 """
1025 vdict = None
1025 vdict = None
1026
1026
1027 # We need a dict of name/value pairs to do namespace updates.
1027 # We need a dict of name/value pairs to do namespace updates.
1028 if isinstance(variables, dict):
1028 if isinstance(variables, dict):
1029 vdict = variables
1029 vdict = variables
1030 elif isinstance(variables, (basestring, list, tuple)):
1030 elif isinstance(variables, (basestring, list, tuple)):
1031 if isinstance(variables, basestring):
1031 if isinstance(variables, basestring):
1032 vlist = variables.split()
1032 vlist = variables.split()
1033 else:
1033 else:
1034 vlist = variables
1034 vlist = variables
1035 vdict = {}
1035 vdict = {}
1036 cf = sys._getframe(1)
1036 cf = sys._getframe(1)
1037 for name in vlist:
1037 for name in vlist:
1038 try:
1038 try:
1039 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1039 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1040 except:
1040 except:
1041 print ('Could not get variable %s from %s' %
1041 print ('Could not get variable %s from %s' %
1042 (name,cf.f_code.co_name))
1042 (name,cf.f_code.co_name))
1043 else:
1043 else:
1044 raise ValueError('variables must be a dict/str/list/tuple')
1044 raise ValueError('variables must be a dict/str/list/tuple')
1045
1045
1046 # Propagate variables to user namespace
1046 # Propagate variables to user namespace
1047 self.user_ns.update(vdict)
1047 self.user_ns.update(vdict)
1048
1048
1049 # And configure interactive visibility
1049 # And configure interactive visibility
1050 config_ns = self.user_config_ns
1050 config_ns = self.user_config_ns
1051 if interactive:
1051 if interactive:
1052 for name, val in vdict.iteritems():
1052 for name, val in vdict.iteritems():
1053 config_ns.pop(name, None)
1053 config_ns.pop(name, None)
1054 else:
1054 else:
1055 for name,val in vdict.iteritems():
1055 for name,val in vdict.iteritems():
1056 config_ns[name] = val
1056 config_ns[name] = val
1057
1057
1058 #-------------------------------------------------------------------------
1058 #-------------------------------------------------------------------------
1059 # Things related to history management
1059 # Things related to history management
1060 #-------------------------------------------------------------------------
1060 #-------------------------------------------------------------------------
1061
1061
1062 def init_history(self):
1062 def init_history(self):
1063 # List of input with multi-line handling.
1063 # List of input with multi-line handling.
1064 self.input_hist = InputList()
1064 self.input_hist = InputList()
1065 # This one will hold the 'raw' input history, without any
1065 # This one will hold the 'raw' input history, without any
1066 # pre-processing. This will allow users to retrieve the input just as
1066 # pre-processing. This will allow users to retrieve the input just as
1067 # it was exactly typed in by the user, with %hist -r.
1067 # it was exactly typed in by the user, with %hist -r.
1068 self.input_hist_raw = InputList()
1068 self.input_hist_raw = InputList()
1069
1069
1070 # list of visited directories
1070 # list of visited directories
1071 try:
1071 try:
1072 self.dir_hist = [os.getcwd()]
1072 self.dir_hist = [os.getcwd()]
1073 except OSError:
1073 except OSError:
1074 self.dir_hist = []
1074 self.dir_hist = []
1075
1075
1076 # dict of output history
1076 # dict of output history
1077 self.output_hist = {}
1077 self.output_hist = {}
1078
1078
1079 # Now the history file
1079 # Now the history file
1080 if self.profile:
1080 if self.profile:
1081 histfname = 'history-%s' % self.profile
1081 histfname = 'history-%s' % self.profile
1082 else:
1082 else:
1083 histfname = 'history'
1083 histfname = 'history'
1084 self.histfile = os.path.join(self.ipython_dir, histfname)
1084 self.histfile = os.path.join(self.ipython_dir, histfname)
1085
1085
1086 # Fill the history zero entry, user counter starts at 1
1086 # Fill the history zero entry, user counter starts at 1
1087 self.input_hist.append('\n')
1087 self.input_hist.append('\n')
1088 self.input_hist_raw.append('\n')
1088 self.input_hist_raw.append('\n')
1089
1089
1090 def init_shadow_hist(self):
1090 def init_shadow_hist(self):
1091 try:
1091 try:
1092 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1092 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1093 except exceptions.UnicodeDecodeError:
1093 except exceptions.UnicodeDecodeError:
1094 print "Your ipython_dir can't be decoded to unicode!"
1094 print "Your ipython_dir can't be decoded to unicode!"
1095 print "Please set HOME environment variable to something that"
1095 print "Please set HOME environment variable to something that"
1096 print r"only has ASCII characters, e.g. c:\home"
1096 print r"only has ASCII characters, e.g. c:\home"
1097 print "Now it is", self.ipython_dir
1097 print "Now it is", self.ipython_dir
1098 sys.exit()
1098 sys.exit()
1099 self.shadowhist = ipcorehist.ShadowHist(self.db)
1099 self.shadowhist = ipcorehist.ShadowHist(self.db)
1100
1100
1101 def savehist(self):
1101 def savehist(self):
1102 """Save input history to a file (via readline library)."""
1102 """Save input history to a file (via readline library)."""
1103
1103
1104 try:
1104 try:
1105 self.readline.write_history_file(self.histfile)
1105 self.readline.write_history_file(self.histfile)
1106 except:
1106 except:
1107 print 'Unable to save IPython command history to file: ' + \
1107 print 'Unable to save IPython command history to file: ' + \
1108 `self.histfile`
1108 `self.histfile`
1109
1109
1110 def reloadhist(self):
1110 def reloadhist(self):
1111 """Reload the input history from disk file."""
1111 """Reload the input history from disk file."""
1112
1112
1113 try:
1113 try:
1114 self.readline.clear_history()
1114 self.readline.clear_history()
1115 self.readline.read_history_file(self.shell.histfile)
1115 self.readline.read_history_file(self.shell.histfile)
1116 except AttributeError:
1116 except AttributeError:
1117 pass
1117 pass
1118
1118
1119 def history_saving_wrapper(self, func):
1119 def history_saving_wrapper(self, func):
1120 """ Wrap func for readline history saving
1120 """ Wrap func for readline history saving
1121
1121
1122 Convert func into callable that saves & restores
1122 Convert func into callable that saves & restores
1123 history around the call """
1123 history around the call """
1124
1124
1125 if not self.has_readline:
1125 if not self.has_readline:
1126 return func
1126 return func
1127
1127
1128 def wrapper():
1128 def wrapper():
1129 self.savehist()
1129 self.savehist()
1130 try:
1130 try:
1131 func()
1131 func()
1132 finally:
1132 finally:
1133 readline.read_history_file(self.histfile)
1133 readline.read_history_file(self.histfile)
1134 return wrapper
1134 return wrapper
1135
1135
1136 #-------------------------------------------------------------------------
1136 #-------------------------------------------------------------------------
1137 # Things related to exception handling and tracebacks (not debugging)
1137 # Things related to exception handling and tracebacks (not debugging)
1138 #-------------------------------------------------------------------------
1138 #-------------------------------------------------------------------------
1139
1139
1140 def init_traceback_handlers(self, custom_exceptions):
1140 def init_traceback_handlers(self, custom_exceptions):
1141 # Syntax error handler.
1141 # Syntax error handler.
1142 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1142 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1143
1143
1144 # The interactive one is initialized with an offset, meaning we always
1144 # The interactive one is initialized with an offset, meaning we always
1145 # want to remove the topmost item in the traceback, which is our own
1145 # want to remove the topmost item in the traceback, which is our own
1146 # internal code. Valid modes: ['Plain','Context','Verbose']
1146 # internal code. Valid modes: ['Plain','Context','Verbose']
1147 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1147 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1148 color_scheme='NoColor',
1148 color_scheme='NoColor',
1149 tb_offset = 1)
1149 tb_offset = 1)
1150
1150
1151 # IPython itself shouldn't crash. This will produce a detailed
1151 # IPython itself shouldn't crash. This will produce a detailed
1152 # post-mortem if it does. But we only install the crash handler for
1152 # post-mortem if it does. But we only install the crash handler for
1153 # non-threaded shells, the threaded ones use a normal verbose reporter
1153 # non-threaded shells, the threaded ones use a normal verbose reporter
1154 # and lose the crash handler. This is because exceptions in the main
1154 # and lose the crash handler. This is because exceptions in the main
1155 # thread (such as in GUI code) propagate directly to sys.excepthook,
1155 # thread (such as in GUI code) propagate directly to sys.excepthook,
1156 # and there's no point in printing crash dumps for every user exception.
1156 # and there's no point in printing crash dumps for every user exception.
1157 if self.isthreaded:
1157 if self.isthreaded:
1158 ipCrashHandler = ultratb.FormattedTB()
1158 ipCrashHandler = ultratb.FormattedTB()
1159 else:
1159 else:
1160 from IPython.core import crashhandler
1160 from IPython.core import crashhandler
1161 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1161 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1162 self.set_crash_handler(ipCrashHandler)
1162 self.set_crash_handler(ipCrashHandler)
1163
1163
1164 # and add any custom exception handlers the user may have specified
1164 # and add any custom exception handlers the user may have specified
1165 self.set_custom_exc(*custom_exceptions)
1165 self.set_custom_exc(*custom_exceptions)
1166
1166
1167 def set_crash_handler(self, crashHandler):
1167 def set_crash_handler(self, crashHandler):
1168 """Set the IPython crash handler.
1168 """Set the IPython crash handler.
1169
1169
1170 This must be a callable with a signature suitable for use as
1170 This must be a callable with a signature suitable for use as
1171 sys.excepthook."""
1171 sys.excepthook."""
1172
1172
1173 # Install the given crash handler as the Python exception hook
1173 # Install the given crash handler as the Python exception hook
1174 sys.excepthook = crashHandler
1174 sys.excepthook = crashHandler
1175
1175
1176 # The instance will store a pointer to this, so that runtime code
1176 # The instance will store a pointer to this, so that runtime code
1177 # (such as magics) can access it. This is because during the
1177 # (such as magics) can access it. This is because during the
1178 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1178 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1179 # frameworks).
1179 # frameworks).
1180 self.sys_excepthook = sys.excepthook
1180 self.sys_excepthook = sys.excepthook
1181
1181
1182 def set_custom_exc(self,exc_tuple,handler):
1182 def set_custom_exc(self,exc_tuple,handler):
1183 """set_custom_exc(exc_tuple,handler)
1183 """set_custom_exc(exc_tuple,handler)
1184
1184
1185 Set a custom exception handler, which will be called if any of the
1185 Set a custom exception handler, which will be called if any of the
1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1187 runcode() method.
1187 runcode() method.
1188
1188
1189 Inputs:
1189 Inputs:
1190
1190
1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1192 handler for. It is very important that you use a tuple, and NOT A
1192 handler for. It is very important that you use a tuple, and NOT A
1193 LIST here, because of the way Python's except statement works. If
1193 LIST here, because of the way Python's except statement works. If
1194 you only want to trap a single exception, use a singleton tuple:
1194 you only want to trap a single exception, use a singleton tuple:
1195
1195
1196 exc_tuple == (MyCustomException,)
1196 exc_tuple == (MyCustomException,)
1197
1197
1198 - handler: this must be defined as a function with the following
1198 - handler: this must be defined as a function with the following
1199 basic interface: def my_handler(self,etype,value,tb).
1199 basic interface: def my_handler(self,etype,value,tb).
1200
1200
1201 This will be made into an instance method (via new.instancemethod)
1201 This will be made into an instance method (via new.instancemethod)
1202 of IPython itself, and it will be called if any of the exceptions
1202 of IPython itself, and it will be called if any of the exceptions
1203 listed in the exc_tuple are caught. If the handler is None, an
1203 listed in the exc_tuple are caught. If the handler is None, an
1204 internal basic one is used, which just prints basic info.
1204 internal basic one is used, which just prints basic info.
1205
1205
1206 WARNING: by putting in your own exception handler into IPython's main
1206 WARNING: by putting in your own exception handler into IPython's main
1207 execution loop, you run a very good chance of nasty crashes. This
1207 execution loop, you run a very good chance of nasty crashes. This
1208 facility should only be used if you really know what you are doing."""
1208 facility should only be used if you really know what you are doing."""
1209
1209
1210 assert type(exc_tuple)==type(()) , \
1210 assert type(exc_tuple)==type(()) , \
1211 "The custom exceptions must be given AS A TUPLE."
1211 "The custom exceptions must be given AS A TUPLE."
1212
1212
1213 def dummy_handler(self,etype,value,tb):
1213 def dummy_handler(self,etype,value,tb):
1214 print '*** Simple custom exception handler ***'
1214 print '*** Simple custom exception handler ***'
1215 print 'Exception type :',etype
1215 print 'Exception type :',etype
1216 print 'Exception value:',value
1216 print 'Exception value:',value
1217 print 'Traceback :',tb
1217 print 'Traceback :',tb
1218 print 'Source code :','\n'.join(self.buffer)
1218 print 'Source code :','\n'.join(self.buffer)
1219
1219
1220 if handler is None: handler = dummy_handler
1220 if handler is None: handler = dummy_handler
1221
1221
1222 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1222 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1223 self.custom_exceptions = exc_tuple
1223 self.custom_exceptions = exc_tuple
1224
1224
1225 def excepthook(self, etype, value, tb):
1225 def excepthook(self, etype, value, tb):
1226 """One more defense for GUI apps that call sys.excepthook.
1226 """One more defense for GUI apps that call sys.excepthook.
1227
1227
1228 GUI frameworks like wxPython trap exceptions and call
1228 GUI frameworks like wxPython trap exceptions and call
1229 sys.excepthook themselves. I guess this is a feature that
1229 sys.excepthook themselves. I guess this is a feature that
1230 enables them to keep running after exceptions that would
1230 enables them to keep running after exceptions that would
1231 otherwise kill their mainloop. This is a bother for IPython
1231 otherwise kill their mainloop. This is a bother for IPython
1232 which excepts to catch all of the program exceptions with a try:
1232 which excepts to catch all of the program exceptions with a try:
1233 except: statement.
1233 except: statement.
1234
1234
1235 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1235 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1236 any app directly invokes sys.excepthook, it will look to the user like
1236 any app directly invokes sys.excepthook, it will look to the user like
1237 IPython crashed. In order to work around this, we can disable the
1237 IPython crashed. In order to work around this, we can disable the
1238 CrashHandler and replace it with this excepthook instead, which prints a
1238 CrashHandler and replace it with this excepthook instead, which prints a
1239 regular traceback using our InteractiveTB. In this fashion, apps which
1239 regular traceback using our InteractiveTB. In this fashion, apps which
1240 call sys.excepthook will generate a regular-looking exception from
1240 call sys.excepthook will generate a regular-looking exception from
1241 IPython, and the CrashHandler will only be triggered by real IPython
1241 IPython, and the CrashHandler will only be triggered by real IPython
1242 crashes.
1242 crashes.
1243
1243
1244 This hook should be used sparingly, only in places which are not likely
1244 This hook should be used sparingly, only in places which are not likely
1245 to be true IPython errors.
1245 to be true IPython errors.
1246 """
1246 """
1247 self.showtraceback((etype,value,tb),tb_offset=0)
1247 self.showtraceback((etype,value,tb),tb_offset=0)
1248
1248
1249 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1249 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1250 """Display the exception that just occurred.
1250 """Display the exception that just occurred.
1251
1251
1252 If nothing is known about the exception, this is the method which
1252 If nothing is known about the exception, this is the method which
1253 should be used throughout the code for presenting user tracebacks,
1253 should be used throughout the code for presenting user tracebacks,
1254 rather than directly invoking the InteractiveTB object.
1254 rather than directly invoking the InteractiveTB object.
1255
1255
1256 A specific showsyntaxerror() also exists, but this method can take
1256 A specific showsyntaxerror() also exists, but this method can take
1257 care of calling it if needed, so unless you are explicitly catching a
1257 care of calling it if needed, so unless you are explicitly catching a
1258 SyntaxError exception, don't try to analyze the stack manually and
1258 SyntaxError exception, don't try to analyze the stack manually and
1259 simply call this method."""
1259 simply call this method."""
1260
1260
1261
1261
1262 # Though this won't be called by syntax errors in the input line,
1262 # Though this won't be called by syntax errors in the input line,
1263 # there may be SyntaxError cases whith imported code.
1263 # there may be SyntaxError cases whith imported code.
1264
1264
1265 try:
1265 try:
1266 if exc_tuple is None:
1266 if exc_tuple is None:
1267 etype, value, tb = sys.exc_info()
1267 etype, value, tb = sys.exc_info()
1268 else:
1268 else:
1269 etype, value, tb = exc_tuple
1269 etype, value, tb = exc_tuple
1270
1270
1271 if etype is SyntaxError:
1271 if etype is SyntaxError:
1272 self.showsyntaxerror(filename)
1272 self.showsyntaxerror(filename)
1273 elif etype is UsageError:
1273 elif etype is UsageError:
1274 print "UsageError:", value
1274 print "UsageError:", value
1275 else:
1275 else:
1276 # WARNING: these variables are somewhat deprecated and not
1276 # WARNING: these variables are somewhat deprecated and not
1277 # necessarily safe to use in a threaded environment, but tools
1277 # necessarily safe to use in a threaded environment, but tools
1278 # like pdb depend on their existence, so let's set them. If we
1278 # like pdb depend on their existence, so let's set them. If we
1279 # find problems in the field, we'll need to revisit their use.
1279 # find problems in the field, we'll need to revisit their use.
1280 sys.last_type = etype
1280 sys.last_type = etype
1281 sys.last_value = value
1281 sys.last_value = value
1282 sys.last_traceback = tb
1282 sys.last_traceback = tb
1283
1283
1284 if etype in self.custom_exceptions:
1284 if etype in self.custom_exceptions:
1285 self.CustomTB(etype,value,tb)
1285 self.CustomTB(etype,value,tb)
1286 else:
1286 else:
1287 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1287 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1288 if self.InteractiveTB.call_pdb:
1288 if self.InteractiveTB.call_pdb:
1289 # pdb mucks up readline, fix it back
1289 # pdb mucks up readline, fix it back
1290 self.set_completer()
1290 self.set_completer()
1291 except KeyboardInterrupt:
1291 except KeyboardInterrupt:
1292 self.write("\nKeyboardInterrupt\n")
1292 self.write("\nKeyboardInterrupt\n")
1293
1293
1294 def showsyntaxerror(self, filename=None):
1294 def showsyntaxerror(self, filename=None):
1295 """Display the syntax error that just occurred.
1295 """Display the syntax error that just occurred.
1296
1296
1297 This doesn't display a stack trace because there isn't one.
1297 This doesn't display a stack trace because there isn't one.
1298
1298
1299 If a filename is given, it is stuffed in the exception instead
1299 If a filename is given, it is stuffed in the exception instead
1300 of what was there before (because Python's parser always uses
1300 of what was there before (because Python's parser always uses
1301 "<string>" when reading from a string).
1301 "<string>" when reading from a string).
1302 """
1302 """
1303 etype, value, last_traceback = sys.exc_info()
1303 etype, value, last_traceback = sys.exc_info()
1304
1304
1305 # See note about these variables in showtraceback() below
1305 # See note about these variables in showtraceback() below
1306 sys.last_type = etype
1306 sys.last_type = etype
1307 sys.last_value = value
1307 sys.last_value = value
1308 sys.last_traceback = last_traceback
1308 sys.last_traceback = last_traceback
1309
1309
1310 if filename and etype is SyntaxError:
1310 if filename and etype is SyntaxError:
1311 # Work hard to stuff the correct filename in the exception
1311 # Work hard to stuff the correct filename in the exception
1312 try:
1312 try:
1313 msg, (dummy_filename, lineno, offset, line) = value
1313 msg, (dummy_filename, lineno, offset, line) = value
1314 except:
1314 except:
1315 # Not the format we expect; leave it alone
1315 # Not the format we expect; leave it alone
1316 pass
1316 pass
1317 else:
1317 else:
1318 # Stuff in the right filename
1318 # Stuff in the right filename
1319 try:
1319 try:
1320 # Assume SyntaxError is a class exception
1320 # Assume SyntaxError is a class exception
1321 value = SyntaxError(msg, (filename, lineno, offset, line))
1321 value = SyntaxError(msg, (filename, lineno, offset, line))
1322 except:
1322 except:
1323 # If that failed, assume SyntaxError is a string
1323 # If that failed, assume SyntaxError is a string
1324 value = msg, (filename, lineno, offset, line)
1324 value = msg, (filename, lineno, offset, line)
1325 self.SyntaxTB(etype,value,[])
1325 self.SyntaxTB(etype,value,[])
1326
1326
1327 def edit_syntax_error(self):
1327 def edit_syntax_error(self):
1328 """The bottom half of the syntax error handler called in the main loop.
1328 """The bottom half of the syntax error handler called in the main loop.
1329
1329
1330 Loop until syntax error is fixed or user cancels.
1330 Loop until syntax error is fixed or user cancels.
1331 """
1331 """
1332
1332
1333 while self.SyntaxTB.last_syntax_error:
1333 while self.SyntaxTB.last_syntax_error:
1334 # copy and clear last_syntax_error
1334 # copy and clear last_syntax_error
1335 err = self.SyntaxTB.clear_err_state()
1335 err = self.SyntaxTB.clear_err_state()
1336 if not self._should_recompile(err):
1336 if not self._should_recompile(err):
1337 return
1337 return
1338 try:
1338 try:
1339 # may set last_syntax_error again if a SyntaxError is raised
1339 # may set last_syntax_error again if a SyntaxError is raised
1340 self.safe_execfile(err.filename,self.user_ns)
1340 self.safe_execfile(err.filename,self.user_ns)
1341 except:
1341 except:
1342 self.showtraceback()
1342 self.showtraceback()
1343 else:
1343 else:
1344 try:
1344 try:
1345 f = file(err.filename)
1345 f = file(err.filename)
1346 try:
1346 try:
1347 # This should be inside a display_trap block and I
1347 # This should be inside a display_trap block and I
1348 # think it is.
1348 # think it is.
1349 sys.displayhook(f.read())
1349 sys.displayhook(f.read())
1350 finally:
1350 finally:
1351 f.close()
1351 f.close()
1352 except:
1352 except:
1353 self.showtraceback()
1353 self.showtraceback()
1354
1354
1355 def _should_recompile(self,e):
1355 def _should_recompile(self,e):
1356 """Utility routine for edit_syntax_error"""
1356 """Utility routine for edit_syntax_error"""
1357
1357
1358 if e.filename in ('<ipython console>','<input>','<string>',
1358 if e.filename in ('<ipython console>','<input>','<string>',
1359 '<console>','<BackgroundJob compilation>',
1359 '<console>','<BackgroundJob compilation>',
1360 None):
1360 None):
1361
1361
1362 return False
1362 return False
1363 try:
1363 try:
1364 if (self.autoedit_syntax and
1364 if (self.autoedit_syntax and
1365 not self.ask_yes_no('Return to editor to correct syntax error? '
1365 not self.ask_yes_no('Return to editor to correct syntax error? '
1366 '[Y/n] ','y')):
1366 '[Y/n] ','y')):
1367 return False
1367 return False
1368 except EOFError:
1368 except EOFError:
1369 return False
1369 return False
1370
1370
1371 def int0(x):
1371 def int0(x):
1372 try:
1372 try:
1373 return int(x)
1373 return int(x)
1374 except TypeError:
1374 except TypeError:
1375 return 0
1375 return 0
1376 # always pass integer line and offset values to editor hook
1376 # always pass integer line and offset values to editor hook
1377 try:
1377 try:
1378 self.hooks.fix_error_editor(e.filename,
1378 self.hooks.fix_error_editor(e.filename,
1379 int0(e.lineno),int0(e.offset),e.msg)
1379 int0(e.lineno),int0(e.offset),e.msg)
1380 except TryNext:
1380 except TryNext:
1381 warn('Could not open editor')
1381 warn('Could not open editor')
1382 return False
1382 return False
1383 return True
1383 return True
1384
1384
1385 #-------------------------------------------------------------------------
1385 #-------------------------------------------------------------------------
1386 # Things related to tab completion
1386 # Things related to tab completion
1387 #-------------------------------------------------------------------------
1387 #-------------------------------------------------------------------------
1388
1388
1389 def complete(self, text):
1389 def complete(self, text):
1390 """Return a sorted list of all possible completions on text.
1390 """Return a sorted list of all possible completions on text.
1391
1391
1392 Inputs:
1392 Inputs:
1393
1393
1394 - text: a string of text to be completed on.
1394 - text: a string of text to be completed on.
1395
1395
1396 This is a wrapper around the completion mechanism, similar to what
1396 This is a wrapper around the completion mechanism, similar to what
1397 readline does at the command line when the TAB key is hit. By
1397 readline does at the command line when the TAB key is hit. By
1398 exposing it as a method, it can be used by other non-readline
1398 exposing it as a method, it can be used by other non-readline
1399 environments (such as GUIs) for text completion.
1399 environments (such as GUIs) for text completion.
1400
1400
1401 Simple usage example:
1401 Simple usage example:
1402
1402
1403 In [7]: x = 'hello'
1403 In [7]: x = 'hello'
1404
1404
1405 In [8]: x
1405 In [8]: x
1406 Out[8]: 'hello'
1406 Out[8]: 'hello'
1407
1407
1408 In [9]: print x
1408 In [9]: print x
1409 hello
1409 hello
1410
1410
1411 In [10]: _ip.complete('x.l')
1411 In [10]: _ip.complete('x.l')
1412 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1412 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1413 """
1413 """
1414
1414
1415 # Inject names into __builtin__ so we can complete on the added names.
1415 # Inject names into __builtin__ so we can complete on the added names.
1416 with self.builtin_trap:
1416 with self.builtin_trap:
1417 complete = self.Completer.complete
1417 complete = self.Completer.complete
1418 state = 0
1418 state = 0
1419 # use a dict so we get unique keys, since ipyhton's multiple
1419 # use a dict so we get unique keys, since ipyhton's multiple
1420 # completers can return duplicates. When we make 2.4 a requirement,
1420 # completers can return duplicates. When we make 2.4 a requirement,
1421 # start using sets instead, which are faster.
1421 # start using sets instead, which are faster.
1422 comps = {}
1422 comps = {}
1423 while True:
1423 while True:
1424 newcomp = complete(text,state,line_buffer=text)
1424 newcomp = complete(text,state,line_buffer=text)
1425 if newcomp is None:
1425 if newcomp is None:
1426 break
1426 break
1427 comps[newcomp] = 1
1427 comps[newcomp] = 1
1428 state += 1
1428 state += 1
1429 outcomps = comps.keys()
1429 outcomps = comps.keys()
1430 outcomps.sort()
1430 outcomps.sort()
1431 #print "T:",text,"OC:",outcomps # dbg
1431 #print "T:",text,"OC:",outcomps # dbg
1432 #print "vars:",self.user_ns.keys()
1432 #print "vars:",self.user_ns.keys()
1433 return outcomps
1433 return outcomps
1434
1434
1435 def set_custom_completer(self,completer,pos=0):
1435 def set_custom_completer(self,completer,pos=0):
1436 """Adds a new custom completer function.
1436 """Adds a new custom completer function.
1437
1437
1438 The position argument (defaults to 0) is the index in the completers
1438 The position argument (defaults to 0) is the index in the completers
1439 list where you want the completer to be inserted."""
1439 list where you want the completer to be inserted."""
1440
1440
1441 newcomp = new.instancemethod(completer,self.Completer,
1441 newcomp = new.instancemethod(completer,self.Completer,
1442 self.Completer.__class__)
1442 self.Completer.__class__)
1443 self.Completer.matchers.insert(pos,newcomp)
1443 self.Completer.matchers.insert(pos,newcomp)
1444
1444
1445 def set_completer(self):
1445 def set_completer(self):
1446 """Reset readline's completer to be our own."""
1446 """Reset readline's completer to be our own."""
1447 self.readline.set_completer(self.Completer.complete)
1447 self.readline.set_completer(self.Completer.complete)
1448
1448
1449 def set_completer_frame(self, frame=None):
1449 def set_completer_frame(self, frame=None):
1450 """Set the frame of the completer."""
1450 """Set the frame of the completer."""
1451 if frame:
1451 if frame:
1452 self.Completer.namespace = frame.f_locals
1452 self.Completer.namespace = frame.f_locals
1453 self.Completer.global_namespace = frame.f_globals
1453 self.Completer.global_namespace = frame.f_globals
1454 else:
1454 else:
1455 self.Completer.namespace = self.user_ns
1455 self.Completer.namespace = self.user_ns
1456 self.Completer.global_namespace = self.user_global_ns
1456 self.Completer.global_namespace = self.user_global_ns
1457
1457
1458 #-------------------------------------------------------------------------
1458 #-------------------------------------------------------------------------
1459 # Things related to readline
1459 # Things related to readline
1460 #-------------------------------------------------------------------------
1460 #-------------------------------------------------------------------------
1461
1461
1462 def init_readline(self):
1462 def init_readline(self):
1463 """Command history completion/saving/reloading."""
1463 """Command history completion/saving/reloading."""
1464
1464
1465 if self.readline_use:
1465 if self.readline_use:
1466 import IPython.utils.rlineimpl as readline
1466 import IPython.utils.rlineimpl as readline
1467
1467
1468 self.rl_next_input = None
1468 self.rl_next_input = None
1469 self.rl_do_indent = False
1469 self.rl_do_indent = False
1470
1470
1471 if not self.readline_use or not readline.have_readline:
1471 if not self.readline_use or not readline.have_readline:
1472 self.has_readline = False
1472 self.has_readline = False
1473 self.readline = None
1473 self.readline = None
1474 # Set a number of methods that depend on readline to be no-op
1474 # Set a number of methods that depend on readline to be no-op
1475 self.savehist = no_op
1475 self.savehist = no_op
1476 self.reloadhist = no_op
1476 self.reloadhist = no_op
1477 self.set_completer = no_op
1477 self.set_completer = no_op
1478 self.set_custom_completer = no_op
1478 self.set_custom_completer = no_op
1479 self.set_completer_frame = no_op
1479 self.set_completer_frame = no_op
1480 warn('Readline services not available or not loaded.')
1480 warn('Readline services not available or not loaded.')
1481 else:
1481 else:
1482 self.has_readline = True
1482 self.has_readline = True
1483 self.readline = readline
1483 self.readline = readline
1484 sys.modules['readline'] = readline
1484 sys.modules['readline'] = readline
1485 import atexit
1485 import atexit
1486 from IPython.core.completer import IPCompleter
1486 from IPython.core.completer import IPCompleter
1487 self.Completer = IPCompleter(self,
1487 self.Completer = IPCompleter(self,
1488 self.user_ns,
1488 self.user_ns,
1489 self.user_global_ns,
1489 self.user_global_ns,
1490 self.readline_omit__names,
1490 self.readline_omit__names,
1491 self.alias_manager.alias_table)
1491 self.alias_manager.alias_table)
1492 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1492 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1493 self.strdispatchers['complete_command'] = sdisp
1493 self.strdispatchers['complete_command'] = sdisp
1494 self.Completer.custom_completers = sdisp
1494 self.Completer.custom_completers = sdisp
1495 # Platform-specific configuration
1495 # Platform-specific configuration
1496 if os.name == 'nt':
1496 if os.name == 'nt':
1497 self.readline_startup_hook = readline.set_pre_input_hook
1497 self.readline_startup_hook = readline.set_pre_input_hook
1498 else:
1498 else:
1499 self.readline_startup_hook = readline.set_startup_hook
1499 self.readline_startup_hook = readline.set_startup_hook
1500
1500
1501 # Load user's initrc file (readline config)
1501 # Load user's initrc file (readline config)
1502 # Or if libedit is used, load editrc.
1502 # Or if libedit is used, load editrc.
1503 inputrc_name = os.environ.get('INPUTRC')
1503 inputrc_name = os.environ.get('INPUTRC')
1504 if inputrc_name is None:
1504 if inputrc_name is None:
1505 home_dir = get_home_dir()
1505 home_dir = get_home_dir()
1506 if home_dir is not None:
1506 if home_dir is not None:
1507 inputrc_name = '.inputrc'
1507 inputrc_name = '.inputrc'
1508 if readline.uses_libedit:
1508 if readline.uses_libedit:
1509 inputrc_name = '.editrc'
1509 inputrc_name = '.editrc'
1510 inputrc_name = os.path.join(home_dir, inputrc_name)
1510 inputrc_name = os.path.join(home_dir, inputrc_name)
1511 if os.path.isfile(inputrc_name):
1511 if os.path.isfile(inputrc_name):
1512 try:
1512 try:
1513 readline.read_init_file(inputrc_name)
1513 readline.read_init_file(inputrc_name)
1514 except:
1514 except:
1515 warn('Problems reading readline initialization file <%s>'
1515 warn('Problems reading readline initialization file <%s>'
1516 % inputrc_name)
1516 % inputrc_name)
1517
1517
1518 # save this in sys so embedded copies can restore it properly
1518 # save this in sys so embedded copies can restore it properly
1519 sys.ipcompleter = self.Completer.complete
1519 sys.ipcompleter = self.Completer.complete
1520 self.set_completer()
1520 self.set_completer()
1521
1521
1522 # Configure readline according to user's prefs
1522 # Configure readline according to user's prefs
1523 # This is only done if GNU readline is being used. If libedit
1523 # This is only done if GNU readline is being used. If libedit
1524 # is being used (as on Leopard) the readline config is
1524 # is being used (as on Leopard) the readline config is
1525 # not run as the syntax for libedit is different.
1525 # not run as the syntax for libedit is different.
1526 if not readline.uses_libedit:
1526 if not readline.uses_libedit:
1527 for rlcommand in self.readline_parse_and_bind:
1527 for rlcommand in self.readline_parse_and_bind:
1528 #print "loading rl:",rlcommand # dbg
1528 #print "loading rl:",rlcommand # dbg
1529 readline.parse_and_bind(rlcommand)
1529 readline.parse_and_bind(rlcommand)
1530
1530
1531 # Remove some chars from the delimiters list. If we encounter
1531 # Remove some chars from the delimiters list. If we encounter
1532 # unicode chars, discard them.
1532 # unicode chars, discard them.
1533 delims = readline.get_completer_delims().encode("ascii", "ignore")
1533 delims = readline.get_completer_delims().encode("ascii", "ignore")
1534 delims = delims.translate(string._idmap,
1534 delims = delims.translate(string._idmap,
1535 self.readline_remove_delims)
1535 self.readline_remove_delims)
1536 readline.set_completer_delims(delims)
1536 readline.set_completer_delims(delims)
1537 # otherwise we end up with a monster history after a while:
1537 # otherwise we end up with a monster history after a while:
1538 readline.set_history_length(1000)
1538 readline.set_history_length(1000)
1539 try:
1539 try:
1540 #print '*** Reading readline history' # dbg
1540 #print '*** Reading readline history' # dbg
1541 readline.read_history_file(self.histfile)
1541 readline.read_history_file(self.histfile)
1542 except IOError:
1542 except IOError:
1543 pass # It doesn't exist yet.
1543 pass # It doesn't exist yet.
1544
1544
1545 atexit.register(self.atexit_operations)
1545 atexit.register(self.atexit_operations)
1546 del atexit
1546 del atexit
1547
1547
1548 # Configure auto-indent for all platforms
1548 # Configure auto-indent for all platforms
1549 self.set_autoindent(self.autoindent)
1549 self.set_autoindent(self.autoindent)
1550
1550
1551 def set_next_input(self, s):
1551 def set_next_input(self, s):
1552 """ Sets the 'default' input string for the next command line.
1552 """ Sets the 'default' input string for the next command line.
1553
1553
1554 Requires readline.
1554 Requires readline.
1555
1555
1556 Example:
1556 Example:
1557
1557
1558 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1558 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1559 [D:\ipython]|2> Hello Word_ # cursor is here
1559 [D:\ipython]|2> Hello Word_ # cursor is here
1560 """
1560 """
1561
1561
1562 self.rl_next_input = s
1562 self.rl_next_input = s
1563
1563
1564 def pre_readline(self):
1564 def pre_readline(self):
1565 """readline hook to be used at the start of each line.
1565 """readline hook to be used at the start of each line.
1566
1566
1567 Currently it handles auto-indent only."""
1567 Currently it handles auto-indent only."""
1568
1568
1569 #debugx('self.indent_current_nsp','pre_readline:')
1569 #debugx('self.indent_current_nsp','pre_readline:')
1570
1570
1571 if self.rl_do_indent:
1571 if self.rl_do_indent:
1572 self.readline.insert_text(self._indent_current_str())
1572 self.readline.insert_text(self._indent_current_str())
1573 if self.rl_next_input is not None:
1573 if self.rl_next_input is not None:
1574 self.readline.insert_text(self.rl_next_input)
1574 self.readline.insert_text(self.rl_next_input)
1575 self.rl_next_input = None
1575 self.rl_next_input = None
1576
1576
1577 def _indent_current_str(self):
1577 def _indent_current_str(self):
1578 """return the current level of indentation as a string"""
1578 """return the current level of indentation as a string"""
1579 return self.indent_current_nsp * ' '
1579 return self.indent_current_nsp * ' '
1580
1580
1581 #-------------------------------------------------------------------------
1581 #-------------------------------------------------------------------------
1582 # Things related to magics
1582 # Things related to magics
1583 #-------------------------------------------------------------------------
1583 #-------------------------------------------------------------------------
1584
1584
1585 def init_magics(self):
1585 def init_magics(self):
1586 # Set user colors (don't do it in the constructor above so that it
1586 # Set user colors (don't do it in the constructor above so that it
1587 # doesn't crash if colors option is invalid)
1587 # doesn't crash if colors option is invalid)
1588 self.magic_colors(self.colors)
1588 self.magic_colors(self.colors)
1589
1589
1590 def magic(self,arg_s):
1590 def magic(self,arg_s):
1591 """Call a magic function by name.
1591 """Call a magic function by name.
1592
1592
1593 Input: a string containing the name of the magic function to call and any
1593 Input: a string containing the name of the magic function to call and any
1594 additional arguments to be passed to the magic.
1594 additional arguments to be passed to the magic.
1595
1595
1596 magic('name -opt foo bar') is equivalent to typing at the ipython
1596 magic('name -opt foo bar') is equivalent to typing at the ipython
1597 prompt:
1597 prompt:
1598
1598
1599 In[1]: %name -opt foo bar
1599 In[1]: %name -opt foo bar
1600
1600
1601 To call a magic without arguments, simply use magic('name').
1601 To call a magic without arguments, simply use magic('name').
1602
1602
1603 This provides a proper Python function to call IPython's magics in any
1603 This provides a proper Python function to call IPython's magics in any
1604 valid Python code you can type at the interpreter, including loops and
1604 valid Python code you can type at the interpreter, including loops and
1605 compound statements.
1605 compound statements.
1606 """
1606 """
1607
1607
1608 args = arg_s.split(' ',1)
1608 args = arg_s.split(' ',1)
1609 magic_name = args[0]
1609 magic_name = args[0]
1610 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1610 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1611
1611
1612 try:
1612 try:
1613 magic_args = args[1]
1613 magic_args = args[1]
1614 except IndexError:
1614 except IndexError:
1615 magic_args = ''
1615 magic_args = ''
1616 fn = getattr(self,'magic_'+magic_name,None)
1616 fn = getattr(self,'magic_'+magic_name,None)
1617 if fn is None:
1617 if fn is None:
1618 error("Magic function `%s` not found." % magic_name)
1618 error("Magic function `%s` not found." % magic_name)
1619 else:
1619 else:
1620 magic_args = self.var_expand(magic_args,1)
1620 magic_args = self.var_expand(magic_args,1)
1621 with nested(self.builtin_trap,):
1621 with nested(self.builtin_trap,):
1622 result = fn(magic_args)
1622 result = fn(magic_args)
1623 return result
1623 return result
1624
1624
1625 def define_magic(self, magicname, func):
1625 def define_magic(self, magicname, func):
1626 """Expose own function as magic function for ipython
1626 """Expose own function as magic function for ipython
1627
1627
1628 def foo_impl(self,parameter_s=''):
1628 def foo_impl(self,parameter_s=''):
1629 'My very own magic!. (Use docstrings, IPython reads them).'
1629 'My very own magic!. (Use docstrings, IPython reads them).'
1630 print 'Magic function. Passed parameter is between < >:'
1630 print 'Magic function. Passed parameter is between < >:'
1631 print '<%s>' % parameter_s
1631 print '<%s>' % parameter_s
1632 print 'The self object is:',self
1632 print 'The self object is:',self
1633
1633
1634 self.define_magic('foo',foo_impl)
1634 self.define_magic('foo',foo_impl)
1635 """
1635 """
1636
1636
1637 import new
1637 import new
1638 im = new.instancemethod(func,self, self.__class__)
1638 im = new.instancemethod(func,self, self.__class__)
1639 old = getattr(self, "magic_" + magicname, None)
1639 old = getattr(self, "magic_" + magicname, None)
1640 setattr(self, "magic_" + magicname, im)
1640 setattr(self, "magic_" + magicname, im)
1641 return old
1641 return old
1642
1642
1643 #-------------------------------------------------------------------------
1643 #-------------------------------------------------------------------------
1644 # Things related to macros
1644 # Things related to macros
1645 #-------------------------------------------------------------------------
1645 #-------------------------------------------------------------------------
1646
1646
1647 def define_macro(self, name, themacro):
1647 def define_macro(self, name, themacro):
1648 """Define a new macro
1648 """Define a new macro
1649
1649
1650 Parameters
1650 Parameters
1651 ----------
1651 ----------
1652 name : str
1652 name : str
1653 The name of the macro.
1653 The name of the macro.
1654 themacro : str or Macro
1654 themacro : str or Macro
1655 The action to do upon invoking the macro. If a string, a new
1655 The action to do upon invoking the macro. If a string, a new
1656 Macro object is created by passing the string to it.
1656 Macro object is created by passing the string to it.
1657 """
1657 """
1658
1658
1659 from IPython.core import macro
1659 from IPython.core import macro
1660
1660
1661 if isinstance(themacro, basestring):
1661 if isinstance(themacro, basestring):
1662 themacro = macro.Macro(themacro)
1662 themacro = macro.Macro(themacro)
1663 if not isinstance(themacro, macro.Macro):
1663 if not isinstance(themacro, macro.Macro):
1664 raise ValueError('A macro must be a string or a Macro instance.')
1664 raise ValueError('A macro must be a string or a Macro instance.')
1665 self.user_ns[name] = themacro
1665 self.user_ns[name] = themacro
1666
1666
1667 #-------------------------------------------------------------------------
1667 #-------------------------------------------------------------------------
1668 # Things related to the running of system commands
1668 # Things related to the running of system commands
1669 #-------------------------------------------------------------------------
1669 #-------------------------------------------------------------------------
1670
1670
1671 def system(self, cmd):
1671 def system(self, cmd):
1672 """Make a system call, using IPython."""
1672 """Make a system call, using IPython."""
1673 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1673 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1674
1674
1675 #-------------------------------------------------------------------------
1675 #-------------------------------------------------------------------------
1676 # Things related to aliases
1676 # Things related to aliases
1677 #-------------------------------------------------------------------------
1677 #-------------------------------------------------------------------------
1678
1678
1679 def init_alias(self):
1679 def init_alias(self):
1680 self.alias_manager = AliasManager(self, config=self.config)
1680 self.alias_manager = AliasManager(self, config=self.config)
1681 self.ns_table['alias'] = self.alias_manager.alias_table,
1681 self.ns_table['alias'] = self.alias_manager.alias_table,
1682
1682
1683 #-------------------------------------------------------------------------
1683 #-------------------------------------------------------------------------
1684 # Things related to the running of code
1684 # Things related to the running of code
1685 #-------------------------------------------------------------------------
1685 #-------------------------------------------------------------------------
1686
1686
1687 def ex(self, cmd):
1687 def ex(self, cmd):
1688 """Execute a normal python statement in user namespace."""
1688 """Execute a normal python statement in user namespace."""
1689 with nested(self.builtin_trap,):
1689 with nested(self.builtin_trap,):
1690 exec cmd in self.user_global_ns, self.user_ns
1690 exec cmd in self.user_global_ns, self.user_ns
1691
1691
1692 def ev(self, expr):
1692 def ev(self, expr):
1693 """Evaluate python expression expr in user namespace.
1693 """Evaluate python expression expr in user namespace.
1694
1694
1695 Returns the result of evaluation
1695 Returns the result of evaluation
1696 """
1696 """
1697 with nested(self.builtin_trap,):
1697 with nested(self.builtin_trap,):
1698 return eval(expr, self.user_global_ns, self.user_ns)
1698 return eval(expr, self.user_global_ns, self.user_ns)
1699
1699
1700 def mainloop(self, display_banner=None):
1700 def mainloop(self, display_banner=None):
1701 """Start the mainloop.
1701 """Start the mainloop.
1702
1702
1703 If an optional banner argument is given, it will override the
1703 If an optional banner argument is given, it will override the
1704 internally created default banner.
1704 internally created default banner.
1705 """
1705 """
1706
1706
1707 with nested(self.builtin_trap, self.display_trap):
1707 with nested(self.builtin_trap, self.display_trap):
1708
1708
1709 # if you run stuff with -c <cmd>, raw hist is not updated
1709 # if you run stuff with -c <cmd>, raw hist is not updated
1710 # ensure that it's in sync
1710 # ensure that it's in sync
1711 if len(self.input_hist) != len (self.input_hist_raw):
1711 if len(self.input_hist) != len (self.input_hist_raw):
1712 self.input_hist_raw = InputList(self.input_hist)
1712 self.input_hist_raw = InputList(self.input_hist)
1713
1713
1714 while 1:
1714 while 1:
1715 try:
1715 try:
1716 self.interact(display_banner=display_banner)
1716 self.interact(display_banner=display_banner)
1717 #self.interact_with_readline()
1717 #self.interact_with_readline()
1718 # XXX for testing of a readline-decoupled repl loop, call
1718 # XXX for testing of a readline-decoupled repl loop, call
1719 # interact_with_readline above
1719 # interact_with_readline above
1720 break
1720 break
1721 except KeyboardInterrupt:
1721 except KeyboardInterrupt:
1722 # this should not be necessary, but KeyboardInterrupt
1722 # this should not be necessary, but KeyboardInterrupt
1723 # handling seems rather unpredictable...
1723 # handling seems rather unpredictable...
1724 self.write("\nKeyboardInterrupt in interact()\n")
1724 self.write("\nKeyboardInterrupt in interact()\n")
1725
1725
1726 def interact_prompt(self):
1726 def interact_prompt(self):
1727 """ Print the prompt (in read-eval-print loop)
1727 """ Print the prompt (in read-eval-print loop)
1728
1728
1729 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1729 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1730 used in standard IPython flow.
1730 used in standard IPython flow.
1731 """
1731 """
1732 if self.more:
1732 if self.more:
1733 try:
1733 try:
1734 prompt = self.hooks.generate_prompt(True)
1734 prompt = self.hooks.generate_prompt(True)
1735 except:
1735 except:
1736 self.showtraceback()
1736 self.showtraceback()
1737 if self.autoindent:
1737 if self.autoindent:
1738 self.rl_do_indent = True
1738 self.rl_do_indent = True
1739
1739
1740 else:
1740 else:
1741 try:
1741 try:
1742 prompt = self.hooks.generate_prompt(False)
1742 prompt = self.hooks.generate_prompt(False)
1743 except:
1743 except:
1744 self.showtraceback()
1744 self.showtraceback()
1745 self.write(prompt)
1745 self.write(prompt)
1746
1746
1747 def interact_handle_input(self,line):
1747 def interact_handle_input(self,line):
1748 """ Handle the input line (in read-eval-print loop)
1748 """ Handle the input line (in read-eval-print loop)
1749
1749
1750 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1750 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1751 used in standard IPython flow.
1751 used in standard IPython flow.
1752 """
1752 """
1753 if line.lstrip() == line:
1753 if line.lstrip() == line:
1754 self.shadowhist.add(line.strip())
1754 self.shadowhist.add(line.strip())
1755 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1755 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1756
1756
1757 if line.strip():
1757 if line.strip():
1758 if self.more:
1758 if self.more:
1759 self.input_hist_raw[-1] += '%s\n' % line
1759 self.input_hist_raw[-1] += '%s\n' % line
1760 else:
1760 else:
1761 self.input_hist_raw.append('%s\n' % line)
1761 self.input_hist_raw.append('%s\n' % line)
1762
1762
1763
1763
1764 self.more = self.push_line(lineout)
1764 self.more = self.push_line(lineout)
1765 if (self.SyntaxTB.last_syntax_error and
1765 if (self.SyntaxTB.last_syntax_error and
1766 self.autoedit_syntax):
1766 self.autoedit_syntax):
1767 self.edit_syntax_error()
1767 self.edit_syntax_error()
1768
1768
1769 def interact_with_readline(self):
1769 def interact_with_readline(self):
1770 """ Demo of using interact_handle_input, interact_prompt
1770 """ Demo of using interact_handle_input, interact_prompt
1771
1771
1772 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1772 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1773 it should work like this.
1773 it should work like this.
1774 """
1774 """
1775 self.readline_startup_hook(self.pre_readline)
1775 self.readline_startup_hook(self.pre_readline)
1776 while not self.exit_now:
1776 while not self.exit_now:
1777 self.interact_prompt()
1777 self.interact_prompt()
1778 if self.more:
1778 if self.more:
1779 self.rl_do_indent = True
1779 self.rl_do_indent = True
1780 else:
1780 else:
1781 self.rl_do_indent = False
1781 self.rl_do_indent = False
1782 line = raw_input_original().decode(self.stdin_encoding)
1782 line = raw_input_original().decode(self.stdin_encoding)
1783 self.interact_handle_input(line)
1783 self.interact_handle_input(line)
1784
1784
1785 def interact(self, display_banner=None):
1785 def interact(self, display_banner=None):
1786 """Closely emulate the interactive Python console."""
1786 """Closely emulate the interactive Python console."""
1787
1787
1788 # batch run -> do not interact
1788 # batch run -> do not interact
1789 if self.exit_now:
1789 if self.exit_now:
1790 return
1790 return
1791
1791
1792 if display_banner is None:
1792 if display_banner is None:
1793 display_banner = self.display_banner
1793 display_banner = self.display_banner
1794 if display_banner:
1794 if display_banner:
1795 self.show_banner()
1795 self.show_banner()
1796
1796
1797 more = 0
1797 more = 0
1798
1798
1799 # Mark activity in the builtins
1799 # Mark activity in the builtins
1800 __builtin__.__dict__['__IPYTHON__active'] += 1
1800 __builtin__.__dict__['__IPYTHON__active'] += 1
1801
1801
1802 if self.has_readline:
1802 if self.has_readline:
1803 self.readline_startup_hook(self.pre_readline)
1803 self.readline_startup_hook(self.pre_readline)
1804 # exit_now is set by a call to %Exit or %Quit, through the
1804 # exit_now is set by a call to %Exit or %Quit, through the
1805 # ask_exit callback.
1805 # ask_exit callback.
1806
1806
1807 while not self.exit_now:
1807 while not self.exit_now:
1808 self.hooks.pre_prompt_hook()
1808 self.hooks.pre_prompt_hook()
1809 if more:
1809 if more:
1810 try:
1810 try:
1811 prompt = self.hooks.generate_prompt(True)
1811 prompt = self.hooks.generate_prompt(True)
1812 except:
1812 except:
1813 self.showtraceback()
1813 self.showtraceback()
1814 if self.autoindent:
1814 if self.autoindent:
1815 self.rl_do_indent = True
1815 self.rl_do_indent = True
1816
1816
1817 else:
1817 else:
1818 try:
1818 try:
1819 prompt = self.hooks.generate_prompt(False)
1819 prompt = self.hooks.generate_prompt(False)
1820 except:
1820 except:
1821 self.showtraceback()
1821 self.showtraceback()
1822 try:
1822 try:
1823 line = self.raw_input(prompt, more)
1823 line = self.raw_input(prompt, more)
1824 if self.exit_now:
1824 if self.exit_now:
1825 # quick exit on sys.std[in|out] close
1825 # quick exit on sys.std[in|out] close
1826 break
1826 break
1827 if self.autoindent:
1827 if self.autoindent:
1828 self.rl_do_indent = False
1828 self.rl_do_indent = False
1829
1829
1830 except KeyboardInterrupt:
1830 except KeyboardInterrupt:
1831 #double-guard against keyboardinterrupts during kbdint handling
1831 #double-guard against keyboardinterrupts during kbdint handling
1832 try:
1832 try:
1833 self.write('\nKeyboardInterrupt\n')
1833 self.write('\nKeyboardInterrupt\n')
1834 self.resetbuffer()
1834 self.resetbuffer()
1835 # keep cache in sync with the prompt counter:
1835 # keep cache in sync with the prompt counter:
1836 self.outputcache.prompt_count -= 1
1836 self.outputcache.prompt_count -= 1
1837
1837
1838 if self.autoindent:
1838 if self.autoindent:
1839 self.indent_current_nsp = 0
1839 self.indent_current_nsp = 0
1840 more = 0
1840 more = 0
1841 except KeyboardInterrupt:
1841 except KeyboardInterrupt:
1842 pass
1842 pass
1843 except EOFError:
1843 except EOFError:
1844 if self.autoindent:
1844 if self.autoindent:
1845 self.rl_do_indent = False
1845 self.rl_do_indent = False
1846 if self.has_readline:
1846 if self.has_readline:
1847 self.readline_startup_hook(None)
1847 self.readline_startup_hook(None)
1848 self.write('\n')
1848 self.write('\n')
1849 self.exit()
1849 self.exit()
1850 except bdb.BdbQuit:
1850 except bdb.BdbQuit:
1851 warn('The Python debugger has exited with a BdbQuit exception.\n'
1851 warn('The Python debugger has exited with a BdbQuit exception.\n'
1852 'Because of how pdb handles the stack, it is impossible\n'
1852 'Because of how pdb handles the stack, it is impossible\n'
1853 'for IPython to properly format this particular exception.\n'
1853 'for IPython to properly format this particular exception.\n'
1854 'IPython will resume normal operation.')
1854 'IPython will resume normal operation.')
1855 except:
1855 except:
1856 # exceptions here are VERY RARE, but they can be triggered
1856 # exceptions here are VERY RARE, but they can be triggered
1857 # asynchronously by signal handlers, for example.
1857 # asynchronously by signal handlers, for example.
1858 self.showtraceback()
1858 self.showtraceback()
1859 else:
1859 else:
1860 more = self.push_line(line)
1860 more = self.push_line(line)
1861 if (self.SyntaxTB.last_syntax_error and
1861 if (self.SyntaxTB.last_syntax_error and
1862 self.autoedit_syntax):
1862 self.autoedit_syntax):
1863 self.edit_syntax_error()
1863 self.edit_syntax_error()
1864
1864
1865 # We are off again...
1865 # We are off again...
1866 __builtin__.__dict__['__IPYTHON__active'] -= 1
1866 __builtin__.__dict__['__IPYTHON__active'] -= 1
1867
1867
1868 def safe_execfile(self, fname, *where, **kw):
1868 def safe_execfile(self, fname, *where, **kw):
1869 """A safe version of the builtin execfile().
1869 """A safe version of the builtin execfile().
1870
1870
1871 This version will never throw an exception, but instead print
1871 This version will never throw an exception, but instead print
1872 helpful error messages to the screen. This only works on pure
1872 helpful error messages to the screen. This only works on pure
1873 Python files with the .py extension.
1873 Python files with the .py extension.
1874
1874
1875 Parameters
1875 Parameters
1876 ----------
1876 ----------
1877 fname : string
1877 fname : string
1878 The name of the file to be executed.
1878 The name of the file to be executed.
1879 where : tuple
1879 where : tuple
1880 One or two namespaces, passed to execfile() as (globals,locals).
1880 One or two namespaces, passed to execfile() as (globals,locals).
1881 If only one is given, it is passed as both.
1881 If only one is given, it is passed as both.
1882 exit_ignore : bool (False)
1882 exit_ignore : bool (False)
1883 If True, then don't print errors for non-zero exit statuses.
1883 If True, then don't print errors for non-zero exit statuses.
1884 """
1884 """
1885 kw.setdefault('exit_ignore', False)
1885 kw.setdefault('exit_ignore', False)
1886
1886
1887 fname = os.path.abspath(os.path.expanduser(fname))
1887 fname = os.path.abspath(os.path.expanduser(fname))
1888
1888
1889 # Make sure we have a .py file
1889 # Make sure we have a .py file
1890 if not fname.endswith('.py'):
1890 if not fname.endswith('.py'):
1891 warn('File must end with .py to be run using execfile: <%s>' % fname)
1891 warn('File must end with .py to be run using execfile: <%s>' % fname)
1892
1892
1893 # Make sure we can open the file
1893 # Make sure we can open the file
1894 try:
1894 try:
1895 with open(fname) as thefile:
1895 with open(fname) as thefile:
1896 pass
1896 pass
1897 except:
1897 except:
1898 warn('Could not open file <%s> for safe execution.' % fname)
1898 warn('Could not open file <%s> for safe execution.' % fname)
1899 return
1899 return
1900
1900
1901 # Find things also in current directory. This is needed to mimic the
1901 # Find things also in current directory. This is needed to mimic the
1902 # behavior of running a script from the system command line, where
1902 # behavior of running a script from the system command line, where
1903 # Python inserts the script's directory into sys.path
1903 # Python inserts the script's directory into sys.path
1904 dname = os.path.dirname(fname)
1904 dname = os.path.dirname(fname)
1905
1905
1906 with prepended_to_syspath(dname):
1906 with prepended_to_syspath(dname):
1907 try:
1907 try:
1908 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1908 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1909 # Work around a bug in Python for Windows. The bug was
1909 # Work around a bug in Python for Windows. The bug was
1910 # fixed in in Python 2.5 r54159 and 54158, but that's still
1910 # fixed in in Python 2.5 r54159 and 54158, but that's still
1911 # SVN Python as of March/07. For details, see:
1911 # SVN Python as of March/07. For details, see:
1912 # http://projects.scipy.org/ipython/ipython/ticket/123
1912 # http://projects.scipy.org/ipython/ipython/ticket/123
1913 try:
1913 try:
1914 globs,locs = where[0:2]
1914 globs,locs = where[0:2]
1915 except:
1915 except:
1916 try:
1916 try:
1917 globs = locs = where[0]
1917 globs = locs = where[0]
1918 except:
1918 except:
1919 globs = locs = globals()
1919 globs = locs = globals()
1920 exec file(fname) in globs,locs
1920 exec file(fname) in globs,locs
1921 else:
1921 else:
1922 execfile(fname,*where)
1922 execfile(fname,*where)
1923 except SyntaxError:
1923 except SyntaxError:
1924 self.showsyntaxerror()
1924 self.showsyntaxerror()
1925 warn('Failure executing file: <%s>' % fname)
1925 warn('Failure executing file: <%s>' % fname)
1926 except SystemExit, status:
1926 except SystemExit, status:
1927 # Code that correctly sets the exit status flag to success (0)
1927 # Code that correctly sets the exit status flag to success (0)
1928 # shouldn't be bothered with a traceback. Note that a plain
1928 # shouldn't be bothered with a traceback. Note that a plain
1929 # sys.exit() does NOT set the message to 0 (it's empty) so that
1929 # sys.exit() does NOT set the message to 0 (it's empty) so that
1930 # will still get a traceback. Note that the structure of the
1930 # will still get a traceback. Note that the structure of the
1931 # SystemExit exception changed between Python 2.4 and 2.5, so
1931 # SystemExit exception changed between Python 2.4 and 2.5, so
1932 # the checks must be done in a version-dependent way.
1932 # the checks must be done in a version-dependent way.
1933 show = False
1933 show = False
1934 if status.args[0]==0 and not kw['exit_ignore']:
1934 if status.args[0]==0 and not kw['exit_ignore']:
1935 show = True
1935 show = True
1936 if show:
1936 if show:
1937 self.showtraceback()
1937 self.showtraceback()
1938 warn('Failure executing file: <%s>' % fname)
1938 warn('Failure executing file: <%s>' % fname)
1939 except:
1939 except:
1940 self.showtraceback()
1940 self.showtraceback()
1941 warn('Failure executing file: <%s>' % fname)
1941 warn('Failure executing file: <%s>' % fname)
1942
1942
1943 def safe_execfile_ipy(self, fname):
1943 def safe_execfile_ipy(self, fname):
1944 """Like safe_execfile, but for .ipy files with IPython syntax.
1944 """Like safe_execfile, but for .ipy files with IPython syntax.
1945
1945
1946 Parameters
1946 Parameters
1947 ----------
1947 ----------
1948 fname : str
1948 fname : str
1949 The name of the file to execute. The filename must have a
1949 The name of the file to execute. The filename must have a
1950 .ipy extension.
1950 .ipy extension.
1951 """
1951 """
1952 fname = os.path.abspath(os.path.expanduser(fname))
1952 fname = os.path.abspath(os.path.expanduser(fname))
1953
1953
1954 # Make sure we have a .py file
1954 # Make sure we have a .py file
1955 if not fname.endswith('.ipy'):
1955 if not fname.endswith('.ipy'):
1956 warn('File must end with .py to be run using execfile: <%s>' % fname)
1956 warn('File must end with .py to be run using execfile: <%s>' % fname)
1957
1957
1958 # Make sure we can open the file
1958 # Make sure we can open the file
1959 try:
1959 try:
1960 with open(fname) as thefile:
1960 with open(fname) as thefile:
1961 pass
1961 pass
1962 except:
1962 except:
1963 warn('Could not open file <%s> for safe execution.' % fname)
1963 warn('Could not open file <%s> for safe execution.' % fname)
1964 return
1964 return
1965
1965
1966 # Find things also in current directory. This is needed to mimic the
1966 # Find things also in current directory. This is needed to mimic the
1967 # behavior of running a script from the system command line, where
1967 # behavior of running a script from the system command line, where
1968 # Python inserts the script's directory into sys.path
1968 # Python inserts the script's directory into sys.path
1969 dname = os.path.dirname(fname)
1969 dname = os.path.dirname(fname)
1970
1970
1971 with prepended_to_syspath(dname):
1971 with prepended_to_syspath(dname):
1972 try:
1972 try:
1973 with open(fname) as thefile:
1973 with open(fname) as thefile:
1974 script = thefile.read()
1974 script = thefile.read()
1975 # self.runlines currently captures all exceptions
1975 # self.runlines currently captures all exceptions
1976 # raise in user code. It would be nice if there were
1976 # raise in user code. It would be nice if there were
1977 # versions of runlines, execfile that did raise, so
1977 # versions of runlines, execfile that did raise, so
1978 # we could catch the errors.
1978 # we could catch the errors.
1979 self.runlines(script, clean=True)
1979 self.runlines(script, clean=True)
1980 except:
1980 except:
1981 self.showtraceback()
1981 self.showtraceback()
1982 warn('Unknown failure executing file: <%s>' % fname)
1982 warn('Unknown failure executing file: <%s>' % fname)
1983
1983
1984 def _is_secondary_block_start(self, s):
1984 def _is_secondary_block_start(self, s):
1985 if not s.endswith(':'):
1985 if not s.endswith(':'):
1986 return False
1986 return False
1987 if (s.startswith('elif') or
1987 if (s.startswith('elif') or
1988 s.startswith('else') or
1988 s.startswith('else') or
1989 s.startswith('except') or
1989 s.startswith('except') or
1990 s.startswith('finally')):
1990 s.startswith('finally')):
1991 return True
1991 return True
1992
1992
1993 def cleanup_ipy_script(self, script):
1993 def cleanup_ipy_script(self, script):
1994 """Make a script safe for self.runlines()
1994 """Make a script safe for self.runlines()
1995
1995
1996 Currently, IPython is lines based, with blocks being detected by
1996 Currently, IPython is lines based, with blocks being detected by
1997 empty lines. This is a problem for block based scripts that may
1997 empty lines. This is a problem for block based scripts that may
1998 not have empty lines after blocks. This script adds those empty
1998 not have empty lines after blocks. This script adds those empty
1999 lines to make scripts safe for running in the current line based
1999 lines to make scripts safe for running in the current line based
2000 IPython.
2000 IPython.
2001 """
2001 """
2002 res = []
2002 res = []
2003 lines = script.splitlines()
2003 lines = script.splitlines()
2004 level = 0
2004 level = 0
2005
2005
2006 for l in lines:
2006 for l in lines:
2007 lstripped = l.lstrip()
2007 lstripped = l.lstrip()
2008 stripped = l.strip()
2008 stripped = l.strip()
2009 if not stripped:
2009 if not stripped:
2010 continue
2010 continue
2011 newlevel = len(l) - len(lstripped)
2011 newlevel = len(l) - len(lstripped)
2012 if level > 0 and newlevel == 0 and \
2012 if level > 0 and newlevel == 0 and \
2013 not self._is_secondary_block_start(stripped):
2013 not self._is_secondary_block_start(stripped):
2014 # add empty line
2014 # add empty line
2015 res.append('')
2015 res.append('')
2016 res.append(l)
2016 res.append(l)
2017 level = newlevel
2017 level = newlevel
2018
2018
2019 return '\n'.join(res) + '\n'
2019 return '\n'.join(res) + '\n'
2020
2020
2021 def runlines(self, lines, clean=False):
2021 def runlines(self, lines, clean=False):
2022 """Run a string of one or more lines of source.
2022 """Run a string of one or more lines of source.
2023
2023
2024 This method is capable of running a string containing multiple source
2024 This method is capable of running a string containing multiple source
2025 lines, as if they had been entered at the IPython prompt. Since it
2025 lines, as if they had been entered at the IPython prompt. Since it
2026 exposes IPython's processing machinery, the given strings can contain
2026 exposes IPython's processing machinery, the given strings can contain
2027 magic calls (%magic), special shell access (!cmd), etc.
2027 magic calls (%magic), special shell access (!cmd), etc.
2028 """
2028 """
2029
2029
2030 if isinstance(lines, (list, tuple)):
2030 if isinstance(lines, (list, tuple)):
2031 lines = '\n'.join(lines)
2031 lines = '\n'.join(lines)
2032
2032
2033 if clean:
2033 if clean:
2034 lines = self.cleanup_ipy_script(lines)
2034 lines = self.cleanup_ipy_script(lines)
2035
2035
2036 # We must start with a clean buffer, in case this is run from an
2036 # We must start with a clean buffer, in case this is run from an
2037 # interactive IPython session (via a magic, for example).
2037 # interactive IPython session (via a magic, for example).
2038 self.resetbuffer()
2038 self.resetbuffer()
2039 lines = lines.splitlines()
2039 lines = lines.splitlines()
2040 more = 0
2040 more = 0
2041
2041
2042 with nested(self.builtin_trap, self.display_trap):
2042 with nested(self.builtin_trap, self.display_trap):
2043 for line in lines:
2043 for line in lines:
2044 # skip blank lines so we don't mess up the prompt counter, but do
2044 # skip blank lines so we don't mess up the prompt counter, but do
2045 # NOT skip even a blank line if we are in a code block (more is
2045 # NOT skip even a blank line if we are in a code block (more is
2046 # true)
2046 # true)
2047
2047
2048 if line or more:
2048 if line or more:
2049 # push to raw history, so hist line numbers stay in sync
2049 # push to raw history, so hist line numbers stay in sync
2050 self.input_hist_raw.append("# " + line + "\n")
2050 self.input_hist_raw.append("# " + line + "\n")
2051 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2051 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2052 more = self.push_line(prefiltered)
2052 more = self.push_line(prefiltered)
2053 # IPython's runsource returns None if there was an error
2053 # IPython's runsource returns None if there was an error
2054 # compiling the code. This allows us to stop processing right
2054 # compiling the code. This allows us to stop processing right
2055 # away, so the user gets the error message at the right place.
2055 # away, so the user gets the error message at the right place.
2056 if more is None:
2056 if more is None:
2057 break
2057 break
2058 else:
2058 else:
2059 self.input_hist_raw.append("\n")
2059 self.input_hist_raw.append("\n")
2060 # final newline in case the input didn't have it, so that the code
2060 # final newline in case the input didn't have it, so that the code
2061 # actually does get executed
2061 # actually does get executed
2062 if more:
2062 if more:
2063 self.push_line('\n')
2063 self.push_line('\n')
2064
2064
2065 def runsource(self, source, filename='<input>', symbol='single'):
2065 def runsource(self, source, filename='<input>', symbol='single'):
2066 """Compile and run some source in the interpreter.
2066 """Compile and run some source in the interpreter.
2067
2067
2068 Arguments are as for compile_command().
2068 Arguments are as for compile_command().
2069
2069
2070 One several things can happen:
2070 One several things can happen:
2071
2071
2072 1) The input is incorrect; compile_command() raised an
2072 1) The input is incorrect; compile_command() raised an
2073 exception (SyntaxError or OverflowError). A syntax traceback
2073 exception (SyntaxError or OverflowError). A syntax traceback
2074 will be printed by calling the showsyntaxerror() method.
2074 will be printed by calling the showsyntaxerror() method.
2075
2075
2076 2) The input is incomplete, and more input is required;
2076 2) The input is incomplete, and more input is required;
2077 compile_command() returned None. Nothing happens.
2077 compile_command() returned None. Nothing happens.
2078
2078
2079 3) The input is complete; compile_command() returned a code
2079 3) The input is complete; compile_command() returned a code
2080 object. The code is executed by calling self.runcode() (which
2080 object. The code is executed by calling self.runcode() (which
2081 also handles run-time exceptions, except for SystemExit).
2081 also handles run-time exceptions, except for SystemExit).
2082
2082
2083 The return value is:
2083 The return value is:
2084
2084
2085 - True in case 2
2085 - True in case 2
2086
2086
2087 - False in the other cases, unless an exception is raised, where
2087 - False in the other cases, unless an exception is raised, where
2088 None is returned instead. This can be used by external callers to
2088 None is returned instead. This can be used by external callers to
2089 know whether to continue feeding input or not.
2089 know whether to continue feeding input or not.
2090
2090
2091 The return value can be used to decide whether to use sys.ps1 or
2091 The return value can be used to decide whether to use sys.ps1 or
2092 sys.ps2 to prompt the next line."""
2092 sys.ps2 to prompt the next line."""
2093
2093
2094 # if the source code has leading blanks, add 'if 1:\n' to it
2094 # if the source code has leading blanks, add 'if 1:\n' to it
2095 # this allows execution of indented pasted code. It is tempting
2095 # this allows execution of indented pasted code. It is tempting
2096 # to add '\n' at the end of source to run commands like ' a=1'
2096 # to add '\n' at the end of source to run commands like ' a=1'
2097 # directly, but this fails for more complicated scenarios
2097 # directly, but this fails for more complicated scenarios
2098 source=source.encode(self.stdin_encoding)
2098 source=source.encode(self.stdin_encoding)
2099 if source[:1] in [' ', '\t']:
2099 if source[:1] in [' ', '\t']:
2100 source = 'if 1:\n%s' % source
2100 source = 'if 1:\n%s' % source
2101
2101
2102 try:
2102 try:
2103 code = self.compile(source,filename,symbol)
2103 code = self.compile(source,filename,symbol)
2104 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2104 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2105 # Case 1
2105 # Case 1
2106 self.showsyntaxerror(filename)
2106 self.showsyntaxerror(filename)
2107 return None
2107 return None
2108
2108
2109 if code is None:
2109 if code is None:
2110 # Case 2
2110 # Case 2
2111 return True
2111 return True
2112
2112
2113 # Case 3
2113 # Case 3
2114 # We store the code object so that threaded shells and
2114 # We store the code object so that threaded shells and
2115 # custom exception handlers can access all this info if needed.
2115 # custom exception handlers can access all this info if needed.
2116 # The source corresponding to this can be obtained from the
2116 # The source corresponding to this can be obtained from the
2117 # buffer attribute as '\n'.join(self.buffer).
2117 # buffer attribute as '\n'.join(self.buffer).
2118 self.code_to_run = code
2118 self.code_to_run = code
2119 # now actually execute the code object
2119 # now actually execute the code object
2120 if self.runcode(code) == 0:
2120 if self.runcode(code) == 0:
2121 return False
2121 return False
2122 else:
2122 else:
2123 return None
2123 return None
2124
2124
2125 def runcode(self,code_obj):
2125 def runcode(self,code_obj):
2126 """Execute a code object.
2126 """Execute a code object.
2127
2127
2128 When an exception occurs, self.showtraceback() is called to display a
2128 When an exception occurs, self.showtraceback() is called to display a
2129 traceback.
2129 traceback.
2130
2130
2131 Return value: a flag indicating whether the code to be run completed
2131 Return value: a flag indicating whether the code to be run completed
2132 successfully:
2132 successfully:
2133
2133
2134 - 0: successful execution.
2134 - 0: successful execution.
2135 - 1: an error occurred.
2135 - 1: an error occurred.
2136 """
2136 """
2137
2137
2138 # Set our own excepthook in case the user code tries to call it
2138 # Set our own excepthook in case the user code tries to call it
2139 # directly, so that the IPython crash handler doesn't get triggered
2139 # directly, so that the IPython crash handler doesn't get triggered
2140 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2140 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2141
2141
2142 # we save the original sys.excepthook in the instance, in case config
2142 # we save the original sys.excepthook in the instance, in case config
2143 # code (such as magics) needs access to it.
2143 # code (such as magics) needs access to it.
2144 self.sys_excepthook = old_excepthook
2144 self.sys_excepthook = old_excepthook
2145 outflag = 1 # happens in more places, so it's easier as default
2145 outflag = 1 # happens in more places, so it's easier as default
2146 try:
2146 try:
2147 try:
2147 try:
2148 self.hooks.pre_runcode_hook()
2148 self.hooks.pre_runcode_hook()
2149 exec code_obj in self.user_global_ns, self.user_ns
2149 exec code_obj in self.user_global_ns, self.user_ns
2150 finally:
2150 finally:
2151 # Reset our crash handler in place
2151 # Reset our crash handler in place
2152 sys.excepthook = old_excepthook
2152 sys.excepthook = old_excepthook
2153 except SystemExit:
2153 except SystemExit:
2154 self.resetbuffer()
2154 self.resetbuffer()
2155 self.showtraceback()
2155 self.showtraceback()
2156 warn("Type %exit or %quit to exit IPython "
2156 warn("Type %exit or %quit to exit IPython "
2157 "(%Exit or %Quit do so unconditionally).",level=1)
2157 "(%Exit or %Quit do so unconditionally).",level=1)
2158 except self.custom_exceptions:
2158 except self.custom_exceptions:
2159 etype,value,tb = sys.exc_info()
2159 etype,value,tb = sys.exc_info()
2160 self.CustomTB(etype,value,tb)
2160 self.CustomTB(etype,value,tb)
2161 except:
2161 except:
2162 self.showtraceback()
2162 self.showtraceback()
2163 else:
2163 else:
2164 outflag = 0
2164 outflag = 0
2165 if softspace(sys.stdout, 0):
2165 if softspace(sys.stdout, 0):
2166 print
2166 print
2167 # Flush out code object which has been run (and source)
2167 # Flush out code object which has been run (and source)
2168 self.code_to_run = None
2168 self.code_to_run = None
2169 return outflag
2169 return outflag
2170
2170
2171 def push_line(self, line):
2171 def push_line(self, line):
2172 """Push a line to the interpreter.
2172 """Push a line to the interpreter.
2173
2173
2174 The line should not have a trailing newline; it may have
2174 The line should not have a trailing newline; it may have
2175 internal newlines. The line is appended to a buffer and the
2175 internal newlines. The line is appended to a buffer and the
2176 interpreter's runsource() method is called with the
2176 interpreter's runsource() method is called with the
2177 concatenated contents of the buffer as source. If this
2177 concatenated contents of the buffer as source. If this
2178 indicates that the command was executed or invalid, the buffer
2178 indicates that the command was executed or invalid, the buffer
2179 is reset; otherwise, the command is incomplete, and the buffer
2179 is reset; otherwise, the command is incomplete, and the buffer
2180 is left as it was after the line was appended. The return
2180 is left as it was after the line was appended. The return
2181 value is 1 if more input is required, 0 if the line was dealt
2181 value is 1 if more input is required, 0 if the line was dealt
2182 with in some way (this is the same as runsource()).
2182 with in some way (this is the same as runsource()).
2183 """
2183 """
2184
2184
2185 # autoindent management should be done here, and not in the
2185 # autoindent management should be done here, and not in the
2186 # interactive loop, since that one is only seen by keyboard input. We
2186 # interactive loop, since that one is only seen by keyboard input. We
2187 # need this done correctly even for code run via runlines (which uses
2187 # need this done correctly even for code run via runlines (which uses
2188 # push).
2188 # push).
2189
2189
2190 #print 'push line: <%s>' % line # dbg
2190 #print 'push line: <%s>' % line # dbg
2191 for subline in line.splitlines():
2191 for subline in line.splitlines():
2192 self._autoindent_update(subline)
2192 self._autoindent_update(subline)
2193 self.buffer.append(line)
2193 self.buffer.append(line)
2194 more = self.runsource('\n'.join(self.buffer), self.filename)
2194 more = self.runsource('\n'.join(self.buffer), self.filename)
2195 if not more:
2195 if not more:
2196 self.resetbuffer()
2196 self.resetbuffer()
2197 return more
2197 return more
2198
2198
2199 def _autoindent_update(self,line):
2199 def _autoindent_update(self,line):
2200 """Keep track of the indent level."""
2200 """Keep track of the indent level."""
2201
2201
2202 #debugx('line')
2202 #debugx('line')
2203 #debugx('self.indent_current_nsp')
2203 #debugx('self.indent_current_nsp')
2204 if self.autoindent:
2204 if self.autoindent:
2205 if line:
2205 if line:
2206 inisp = num_ini_spaces(line)
2206 inisp = num_ini_spaces(line)
2207 if inisp < self.indent_current_nsp:
2207 if inisp < self.indent_current_nsp:
2208 self.indent_current_nsp = inisp
2208 self.indent_current_nsp = inisp
2209
2209
2210 if line[-1] == ':':
2210 if line[-1] == ':':
2211 self.indent_current_nsp += 4
2211 self.indent_current_nsp += 4
2212 elif dedent_re.match(line):
2212 elif dedent_re.match(line):
2213 self.indent_current_nsp -= 4
2213 self.indent_current_nsp -= 4
2214 else:
2214 else:
2215 self.indent_current_nsp = 0
2215 self.indent_current_nsp = 0
2216
2216
2217 def resetbuffer(self):
2217 def resetbuffer(self):
2218 """Reset the input buffer."""
2218 """Reset the input buffer."""
2219 self.buffer[:] = []
2219 self.buffer[:] = []
2220
2220
2221 def raw_input(self,prompt='',continue_prompt=False):
2221 def raw_input(self,prompt='',continue_prompt=False):
2222 """Write a prompt and read a line.
2222 """Write a prompt and read a line.
2223
2223
2224 The returned line does not include the trailing newline.
2224 The returned line does not include the trailing newline.
2225 When the user enters the EOF key sequence, EOFError is raised.
2225 When the user enters the EOF key sequence, EOFError is raised.
2226
2226
2227 Optional inputs:
2227 Optional inputs:
2228
2228
2229 - prompt(''): a string to be printed to prompt the user.
2229 - prompt(''): a string to be printed to prompt the user.
2230
2230
2231 - continue_prompt(False): whether this line is the first one or a
2231 - continue_prompt(False): whether this line is the first one or a
2232 continuation in a sequence of inputs.
2232 continuation in a sequence of inputs.
2233 """
2233 """
2234 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2234 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2235
2235
2236 # Code run by the user may have modified the readline completer state.
2236 # Code run by the user may have modified the readline completer state.
2237 # We must ensure that our completer is back in place.
2237 # We must ensure that our completer is back in place.
2238
2238
2239 if self.has_readline:
2239 if self.has_readline:
2240 self.set_completer()
2240 self.set_completer()
2241
2241
2242 try:
2242 try:
2243 line = raw_input_original(prompt).decode(self.stdin_encoding)
2243 line = raw_input_original(prompt).decode(self.stdin_encoding)
2244 except ValueError:
2244 except ValueError:
2245 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2245 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2246 " or sys.stdout.close()!\nExiting IPython!")
2246 " or sys.stdout.close()!\nExiting IPython!")
2247 self.ask_exit()
2247 self.ask_exit()
2248 return ""
2248 return ""
2249
2249
2250 # Try to be reasonably smart about not re-indenting pasted input more
2250 # Try to be reasonably smart about not re-indenting pasted input more
2251 # than necessary. We do this by trimming out the auto-indent initial
2251 # than necessary. We do this by trimming out the auto-indent initial
2252 # spaces, if the user's actual input started itself with whitespace.
2252 # spaces, if the user's actual input started itself with whitespace.
2253 #debugx('self.buffer[-1]')
2253 #debugx('self.buffer[-1]')
2254
2254
2255 if self.autoindent:
2255 if self.autoindent:
2256 if num_ini_spaces(line) > self.indent_current_nsp:
2256 if num_ini_spaces(line) > self.indent_current_nsp:
2257 line = line[self.indent_current_nsp:]
2257 line = line[self.indent_current_nsp:]
2258 self.indent_current_nsp = 0
2258 self.indent_current_nsp = 0
2259
2259
2260 # store the unfiltered input before the user has any chance to modify
2260 # store the unfiltered input before the user has any chance to modify
2261 # it.
2261 # it.
2262 if line.strip():
2262 if line.strip():
2263 if continue_prompt:
2263 if continue_prompt:
2264 self.input_hist_raw[-1] += '%s\n' % line
2264 self.input_hist_raw[-1] += '%s\n' % line
2265 if self.has_readline and self.readline_use:
2265 if self.has_readline and self.readline_use:
2266 try:
2266 try:
2267 histlen = self.readline.get_current_history_length()
2267 histlen = self.readline.get_current_history_length()
2268 if histlen > 1:
2268 if histlen > 1:
2269 newhist = self.input_hist_raw[-1].rstrip()
2269 newhist = self.input_hist_raw[-1].rstrip()
2270 self.readline.remove_history_item(histlen-1)
2270 self.readline.remove_history_item(histlen-1)
2271 self.readline.replace_history_item(histlen-2,
2271 self.readline.replace_history_item(histlen-2,
2272 newhist.encode(self.stdin_encoding))
2272 newhist.encode(self.stdin_encoding))
2273 except AttributeError:
2273 except AttributeError:
2274 pass # re{move,place}_history_item are new in 2.4.
2274 pass # re{move,place}_history_item are new in 2.4.
2275 else:
2275 else:
2276 self.input_hist_raw.append('%s\n' % line)
2276 self.input_hist_raw.append('%s\n' % line)
2277 # only entries starting at first column go to shadow history
2277 # only entries starting at first column go to shadow history
2278 if line.lstrip() == line:
2278 if line.lstrip() == line:
2279 self.shadowhist.add(line.strip())
2279 self.shadowhist.add(line.strip())
2280 elif not continue_prompt:
2280 elif not continue_prompt:
2281 self.input_hist_raw.append('\n')
2281 self.input_hist_raw.append('\n')
2282 try:
2282 try:
2283 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2283 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2284 except:
2284 except:
2285 # blanket except, in case a user-defined prefilter crashes, so it
2285 # blanket except, in case a user-defined prefilter crashes, so it
2286 # can't take all of ipython with it.
2286 # can't take all of ipython with it.
2287 self.showtraceback()
2287 self.showtraceback()
2288 return ''
2288 return ''
2289 else:
2289 else:
2290 return lineout
2290 return lineout
2291
2291
2292 #-------------------------------------------------------------------------
2292 #-------------------------------------------------------------------------
2293 # Working with components
2293 # Working with components
2294 #-------------------------------------------------------------------------
2294 #-------------------------------------------------------------------------
2295
2295
2296 def get_component(self, name=None, klass=None):
2296 def get_component(self, name=None, klass=None):
2297 """Fetch a component by name and klass in my tree."""
2297 """Fetch a component by name and klass in my tree."""
2298 c = Component.get_instances(root=self, name=name, klass=klass)
2298 c = Component.get_instances(root=self, name=name, klass=klass)
2299 if len(c) == 0:
2299 if len(c) == 0:
2300 return None
2300 return None
2301 if len(c) == 1:
2301 if len(c) == 1:
2302 return c[0]
2302 return c[0]
2303 else:
2303 else:
2304 return c
2304 return c
2305
2305
2306 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2307 # IPython extensions
2307 # IPython extensions
2308 #-------------------------------------------------------------------------
2308 #-------------------------------------------------------------------------
2309
2309
2310 def load_extension(self, module_str):
2310 def load_extension(self, module_str):
2311 """Load an IPython extension by its module name.
2311 """Load an IPython extension by its module name.
2312
2312
2313 An IPython extension is an importable Python module that has
2313 An IPython extension is an importable Python module that has
2314 a function with the signature::
2314 a function with the signature::
2315
2315
2316 def load_ipython_extension(ipython):
2316 def load_ipython_extension(ipython):
2317 # Do things with ipython
2317 # Do things with ipython
2318
2318
2319 This function is called after your extension is imported and the
2319 This function is called after your extension is imported and the
2320 currently active :class:`InteractiveShell` instance is passed as
2320 currently active :class:`InteractiveShell` instance is passed as
2321 the only argument. You can do anything you want with IPython at
2321 the only argument. You can do anything you want with IPython at
2322 that point, including defining new magic and aliases, adding new
2322 that point, including defining new magic and aliases, adding new
2323 components, etc.
2323 components, etc.
2324
2324
2325 The :func:`load_ipython_extension` will be called again is you
2325 The :func:`load_ipython_extension` will be called again is you
2326 load or reload the extension again. It is up to the extension
2326 load or reload the extension again. It is up to the extension
2327 author to add code to manage that.
2327 author to add code to manage that.
2328
2328
2329 You can put your extension modules anywhere you want, as long as
2329 You can put your extension modules anywhere you want, as long as
2330 they can be imported by Python's standard import mechanism. However,
2330 they can be imported by Python's standard import mechanism. However,
2331 to make it easy to write extensions, you can also put your extensions
2331 to make it easy to write extensions, you can also put your extensions
2332 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2332 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2333 is added to ``sys.path`` automatically.
2333 is added to ``sys.path`` automatically.
2334 """
2334 """
2335 from IPython.utils.syspathcontext import prepended_to_syspath
2335 from IPython.utils.syspathcontext import prepended_to_syspath
2336
2336
2337 if module_str not in sys.modules:
2337 if module_str not in sys.modules:
2338 with prepended_to_syspath(self.ipython_extension_dir):
2338 with prepended_to_syspath(self.ipython_extension_dir):
2339 __import__(module_str)
2339 __import__(module_str)
2340 mod = sys.modules[module_str]
2340 mod = sys.modules[module_str]
2341 self._call_load_ipython_extension(mod)
2341 self._call_load_ipython_extension(mod)
2342
2342
2343 def unload_extension(self, module_str):
2343 def unload_extension(self, module_str):
2344 """Unload an IPython extension by its module name.
2344 """Unload an IPython extension by its module name.
2345
2345
2346 This function looks up the extension's name in ``sys.modules`` and
2346 This function looks up the extension's name in ``sys.modules`` and
2347 simply calls ``mod.unload_ipython_extension(self)``.
2347 simply calls ``mod.unload_ipython_extension(self)``.
2348 """
2348 """
2349 if module_str in sys.modules:
2349 if module_str in sys.modules:
2350 mod = sys.modules[module_str]
2350 mod = sys.modules[module_str]
2351 self._call_unload_ipython_extension(mod)
2351 self._call_unload_ipython_extension(mod)
2352
2352
2353 def reload_extension(self, module_str):
2353 def reload_extension(self, module_str):
2354 """Reload an IPython extension by calling reload.
2354 """Reload an IPython extension by calling reload.
2355
2355
2356 If the module has not been loaded before,
2356 If the module has not been loaded before,
2357 :meth:`InteractiveShell.load_extension` is called. Otherwise
2357 :meth:`InteractiveShell.load_extension` is called. Otherwise
2358 :func:`reload` is called and then the :func:`load_ipython_extension`
2358 :func:`reload` is called and then the :func:`load_ipython_extension`
2359 function of the module, if it exists is called.
2359 function of the module, if it exists is called.
2360 """
2360 """
2361 from IPython.utils.syspathcontext import prepended_to_syspath
2361 from IPython.utils.syspathcontext import prepended_to_syspath
2362
2362
2363 with prepended_to_syspath(self.ipython_extension_dir):
2363 with prepended_to_syspath(self.ipython_extension_dir):
2364 if module_str in sys.modules:
2364 if module_str in sys.modules:
2365 mod = sys.modules[module_str]
2365 mod = sys.modules[module_str]
2366 reload(mod)
2366 reload(mod)
2367 self._call_load_ipython_extension(mod)
2367 self._call_load_ipython_extension(mod)
2368 else:
2368 else:
2369 self.load_extension(module_str)
2369 self.load_extension(module_str)
2370
2370
2371 def _call_load_ipython_extension(self, mod):
2371 def _call_load_ipython_extension(self, mod):
2372 if hasattr(mod, 'load_ipython_extension'):
2372 if hasattr(mod, 'load_ipython_extension'):
2373 mod.load_ipython_extension(self)
2373 mod.load_ipython_extension(self)
2374
2374
2375 def _call_unload_ipython_extension(self, mod):
2375 def _call_unload_ipython_extension(self, mod):
2376 if hasattr(mod, 'unload_ipython_extension'):
2376 if hasattr(mod, 'unload_ipython_extension'):
2377 mod.unload_ipython_extension(self)
2377 mod.unload_ipython_extension(self)
2378
2378
2379 #-------------------------------------------------------------------------
2379 #-------------------------------------------------------------------------
2380 # Things related to the prefilter
2380 # Things related to the prefilter
2381 #-------------------------------------------------------------------------
2381 #-------------------------------------------------------------------------
2382
2382
2383 def init_prefilter(self):
2383 def init_prefilter(self):
2384 self.prefilter_manager = PrefilterManager(self, config=self.config)
2384 self.prefilter_manager = PrefilterManager(self, config=self.config)
2385
2385
2386 #-------------------------------------------------------------------------
2386 #-------------------------------------------------------------------------
2387 # Utilities
2387 # Utilities
2388 #-------------------------------------------------------------------------
2388 #-------------------------------------------------------------------------
2389
2389
2390 def getoutput(self, cmd):
2390 def getoutput(self, cmd):
2391 return getoutput(self.var_expand(cmd,depth=2),
2391 return getoutput(self.var_expand(cmd,depth=2),
2392 header=self.system_header,
2392 header=self.system_header,
2393 verbose=self.system_verbose)
2393 verbose=self.system_verbose)
2394
2394
2395 def getoutputerror(self, cmd):
2395 def getoutputerror(self, cmd):
2396 return getoutputerror(self.var_expand(cmd,depth=2),
2396 return getoutputerror(self.var_expand(cmd,depth=2),
2397 header=self.system_header,
2397 header=self.system_header,
2398 verbose=self.system_verbose)
2398 verbose=self.system_verbose)
2399
2399
2400 def var_expand(self,cmd,depth=0):
2400 def var_expand(self,cmd,depth=0):
2401 """Expand python variables in a string.
2401 """Expand python variables in a string.
2402
2402
2403 The depth argument indicates how many frames above the caller should
2403 The depth argument indicates how many frames above the caller should
2404 be walked to look for the local namespace where to expand variables.
2404 be walked to look for the local namespace where to expand variables.
2405
2405
2406 The global namespace for expansion is always the user's interactive
2406 The global namespace for expansion is always the user's interactive
2407 namespace.
2407 namespace.
2408 """
2408 """
2409
2409
2410 return str(ItplNS(cmd,
2410 return str(ItplNS(cmd,
2411 self.user_ns, # globals
2411 self.user_ns, # globals
2412 # Skip our own frame in searching for locals:
2412 # Skip our own frame in searching for locals:
2413 sys._getframe(depth+1).f_locals # locals
2413 sys._getframe(depth+1).f_locals # locals
2414 ))
2414 ))
2415
2415
2416 def mktempfile(self,data=None):
2416 def mktempfile(self,data=None):
2417 """Make a new tempfile and return its filename.
2417 """Make a new tempfile and return its filename.
2418
2418
2419 This makes a call to tempfile.mktemp, but it registers the created
2419 This makes a call to tempfile.mktemp, but it registers the created
2420 filename internally so ipython cleans it up at exit time.
2420 filename internally so ipython cleans it up at exit time.
2421
2421
2422 Optional inputs:
2422 Optional inputs:
2423
2423
2424 - data(None): if data is given, it gets written out to the temp file
2424 - data(None): if data is given, it gets written out to the temp file
2425 immediately, and the file is closed again."""
2425 immediately, and the file is closed again."""
2426
2426
2427 filename = tempfile.mktemp('.py','ipython_edit_')
2427 filename = tempfile.mktemp('.py','ipython_edit_')
2428 self.tempfiles.append(filename)
2428 self.tempfiles.append(filename)
2429
2429
2430 if data:
2430 if data:
2431 tmp_file = open(filename,'w')
2431 tmp_file = open(filename,'w')
2432 tmp_file.write(data)
2432 tmp_file.write(data)
2433 tmp_file.close()
2433 tmp_file.close()
2434 return filename
2434 return filename
2435
2435
2436 def write(self,data):
2436 def write(self,data):
2437 """Write a string to the default output"""
2437 """Write a string to the default output"""
2438 Term.cout.write(data)
2438 Term.cout.write(data)
2439
2439
2440 def write_err(self,data):
2440 def write_err(self,data):
2441 """Write a string to the default error output"""
2441 """Write a string to the default error output"""
2442 Term.cerr.write(data)
2442 Term.cerr.write(data)
2443
2443
2444 def ask_yes_no(self,prompt,default=True):
2444 def ask_yes_no(self,prompt,default=True):
2445 if self.quiet:
2445 if self.quiet:
2446 return True
2446 return True
2447 return ask_yes_no(prompt,default)
2447 return ask_yes_no(prompt,default)
2448
2448
2449 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2450 # Things related to GUI support and pylab
2450 # Things related to GUI support and pylab
2451 #-------------------------------------------------------------------------
2451 #-------------------------------------------------------------------------
2452
2452
2453 def enable_pylab(self, gui=None):
2453 def enable_pylab(self, gui=None):
2454 """Activate pylab support at runtime.
2455
2456 This turns on support for matplotlib, preloads into the interactive
2457 namespace all of numpy and pylab, and configures IPython to correcdtly
2458 interact with the GUI event loop. The GUI backend to be used can be
2459 optionally selected with the optional :param:`gui` argument.
2460
2461 Parameters
2462 ----------
2463 gui : optional, string
2464
2465 If given, dictates the choice of matplotlib GUI backend to use
2466 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2467 'gtk'), otherwise we use the default chosen by matplotlib (as
2468 dictated by the matplotlib build-time options plus the user's
2469 matplotlibrc configuration file).
2454 """
2470 """
2455 """
2471 # We want to prevent the loading of pylab to pollute the user's
2456 gui = pylab_activate(self.user_ns, gui)
2472 # namespace as shown by the %who* magics, so we execute the activation
2473 # code in an empty namespace, and we update *both* user_ns and
2474 # user_config_ns with this information.
2475 ns = {}
2476 gui = pylab_activate(ns, gui)
2477 self.user_ns.update(ns)
2478 self.user_config_ns.update(ns)
2479 # Now we must activate the gui pylab wants to use, and fix %run to take
2480 # plot updates into account
2457 enable_gui(gui)
2481 enable_gui(gui)
2458 self.magic_run = self._pylab_magic_run
2482 self.magic_run = self._pylab_magic_run
2459
2483
2460
2461 #-------------------------------------------------------------------------
2484 #-------------------------------------------------------------------------
2462 # Things related to IPython exiting
2485 # Things related to IPython exiting
2463 #-------------------------------------------------------------------------
2486 #-------------------------------------------------------------------------
2464
2487
2465 def ask_exit(self):
2488 def ask_exit(self):
2466 """ Ask the shell to exit. Can be overiden and used as a callback. """
2489 """ Ask the shell to exit. Can be overiden and used as a callback. """
2467 self.exit_now = True
2490 self.exit_now = True
2468
2491
2469 def exit(self):
2492 def exit(self):
2470 """Handle interactive exit.
2493 """Handle interactive exit.
2471
2494
2472 This method calls the ask_exit callback."""
2495 This method calls the ask_exit callback."""
2473 if self.confirm_exit:
2496 if self.confirm_exit:
2474 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2497 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2475 self.ask_exit()
2498 self.ask_exit()
2476 else:
2499 else:
2477 self.ask_exit()
2500 self.ask_exit()
2478
2501
2479 def atexit_operations(self):
2502 def atexit_operations(self):
2480 """This will be executed at the time of exit.
2503 """This will be executed at the time of exit.
2481
2504
2482 Saving of persistent data should be performed here.
2505 Saving of persistent data should be performed here.
2483 """
2506 """
2484 self.savehist()
2507 self.savehist()
2485
2508
2486 # Cleanup all tempfiles left around
2509 # Cleanup all tempfiles left around
2487 for tfile in self.tempfiles:
2510 for tfile in self.tempfiles:
2488 try:
2511 try:
2489 os.unlink(tfile)
2512 os.unlink(tfile)
2490 except OSError:
2513 except OSError:
2491 pass
2514 pass
2492
2515
2493 # Clear all user namespaces to release all references cleanly.
2516 # Clear all user namespaces to release all references cleanly.
2494 self.reset()
2517 self.reset()
2495
2518
2496 # Run user hooks
2519 # Run user hooks
2497 self.hooks.shutdown_hook()
2520 self.hooks.shutdown_hook()
2498
2521
2499 def cleanup(self):
2522 def cleanup(self):
2500 self.restore_sys_module_state()
2523 self.restore_sys_module_state()
2501
2524
2502
2525
@@ -1,999 +1,994 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import keyword
30 import keyword
31 import os
31 import os
32 import re
32 import re
33 import sys
33 import sys
34
34
35 from IPython.core.alias import AliasManager
35 from IPython.core.alias import AliasManager
36 from IPython.core.autocall import IPyAutocall
36 from IPython.core.autocall import IPyAutocall
37 from IPython.core.component import Component
37 from IPython.core.component import Component
38 from IPython.core.splitinput import split_user_input
38 from IPython.core.splitinput import split_user_input
39 from IPython.core.page import page
39 from IPython.core.page import page
40
40
41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
41 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
42 from IPython.utils.genutils import make_quoted_expr, Term
42 from IPython.utils.genutils import make_quoted_expr, Term
43 from IPython.utils.autoattr import auto_attr
43 from IPython.utils.autoattr import auto_attr
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Global utilities, errors and constants
46 # Global utilities, errors and constants
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49 # Warning, these cannot be changed unless various regular expressions
49 # Warning, these cannot be changed unless various regular expressions
50 # are updated in a number of places. Not great, but at least we told you.
50 # are updated in a number of places. Not great, but at least we told you.
51 ESC_SHELL = '!'
51 ESC_SHELL = '!'
52 ESC_SH_CAP = '!!'
52 ESC_SH_CAP = '!!'
53 ESC_HELP = '?'
53 ESC_HELP = '?'
54 ESC_MAGIC = '%'
54 ESC_MAGIC = '%'
55 ESC_QUOTE = ','
55 ESC_QUOTE = ','
56 ESC_QUOTE2 = ';'
56 ESC_QUOTE2 = ';'
57 ESC_PAREN = '/'
57 ESC_PAREN = '/'
58
58
59
59
60 class PrefilterError(Exception):
60 class PrefilterError(Exception):
61 pass
61 pass
62
62
63
63
64 # RegExp to identify potential function names
64 # RegExp to identify potential function names
65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
65 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
66
66
67 # RegExp to exclude strings with this start from autocalling. In
67 # RegExp to exclude strings with this start from autocalling. In
68 # particular, all binary operators should be excluded, so that if foo is
68 # particular, all binary operators should be excluded, so that if foo is
69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
69 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
70 # characters '!=()' don't need to be checked for, as the checkPythonChars
70 # characters '!=()' don't need to be checked for, as the checkPythonChars
71 # routine explicitely does so, to catch direct calls and rebindings of
71 # routine explicitely does so, to catch direct calls and rebindings of
72 # existing names.
72 # existing names.
73
73
74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
74 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
75 # it affects the rest of the group in square brackets.
75 # it affects the rest of the group in square brackets.
76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
76 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
77 r'|^is |^not |^in |^and |^or ')
77 r'|^is |^not |^in |^and |^or ')
78
78
79 # try to catch also methods for stuff in lists/tuples/dicts: off
79 # try to catch also methods for stuff in lists/tuples/dicts: off
80 # (experimental). For this to work, the line_split regexp would need
80 # (experimental). For this to work, the line_split regexp would need
81 # to be modified so it wouldn't break things at '['. That line is
81 # to be modified so it wouldn't break things at '['. That line is
82 # nasty enough that I shouldn't change it until I can test it _well_.
82 # nasty enough that I shouldn't change it until I can test it _well_.
83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
83 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
84
84
85
85
86 # Handler Check Utilities
86 # Handler Check Utilities
87 def is_shadowed(identifier, ip):
87 def is_shadowed(identifier, ip):
88 """Is the given identifier defined in one of the namespaces which shadow
88 """Is the given identifier defined in one of the namespaces which shadow
89 the alias and magic namespaces? Note that an identifier is different
89 the alias and magic namespaces? Note that an identifier is different
90 than ifun, because it can not contain a '.' character."""
90 than ifun, because it can not contain a '.' character."""
91 # This is much safer than calling ofind, which can change state
91 # This is much safer than calling ofind, which can change state
92 return (identifier in ip.user_ns \
92 return (identifier in ip.user_ns \
93 or identifier in ip.internal_ns \
93 or identifier in ip.internal_ns \
94 or identifier in ip.ns_table['builtin'])
94 or identifier in ip.ns_table['builtin'])
95
95
96
96
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # The LineInfo class used throughout
98 # The LineInfo class used throughout
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101
101
102 class LineInfo(object):
102 class LineInfo(object):
103 """A single line of input and associated info.
103 """A single line of input and associated info.
104
104
105 Includes the following as properties:
105 Includes the following as properties:
106
106
107 line
107 line
108 The original, raw line
108 The original, raw line
109
109
110 continue_prompt
110 continue_prompt
111 Is this line a continuation in a sequence of multiline input?
111 Is this line a continuation in a sequence of multiline input?
112
112
113 pre
113 pre
114 The initial esc character or whitespace.
114 The initial esc character or whitespace.
115
115
116 pre_char
116 pre_char
117 The escape character(s) in pre or the empty string if there isn't one.
117 The escape character(s) in pre or the empty string if there isn't one.
118 Note that '!!' is a possible value for pre_char. Otherwise it will
118 Note that '!!' is a possible value for pre_char. Otherwise it will
119 always be a single character.
119 always be a single character.
120
120
121 pre_whitespace
121 pre_whitespace
122 The leading whitespace from pre if it exists. If there is a pre_char,
122 The leading whitespace from pre if it exists. If there is a pre_char,
123 this is just ''.
123 this is just ''.
124
124
125 ifun
125 ifun
126 The 'function part', which is basically the maximal initial sequence
126 The 'function part', which is basically the maximal initial sequence
127 of valid python identifiers and the '.' character. This is what is
127 of valid python identifiers and the '.' character. This is what is
128 checked for alias and magic transformations, used for auto-calling,
128 checked for alias and magic transformations, used for auto-calling,
129 etc.
129 etc.
130
130
131 the_rest
131 the_rest
132 Everything else on the line.
132 Everything else on the line.
133 """
133 """
134 def __init__(self, line, continue_prompt):
134 def __init__(self, line, continue_prompt):
135 self.line = line
135 self.line = line
136 self.continue_prompt = continue_prompt
136 self.continue_prompt = continue_prompt
137 self.pre, self.ifun, self.the_rest = split_user_input(line)
137 self.pre, self.ifun, self.the_rest = split_user_input(line)
138
138
139 self.pre_char = self.pre.strip()
139 self.pre_char = self.pre.strip()
140 if self.pre_char:
140 if self.pre_char:
141 self.pre_whitespace = '' # No whitespace allowd before esc chars
141 self.pre_whitespace = '' # No whitespace allowd before esc chars
142 else:
142 else:
143 self.pre_whitespace = self.pre
143 self.pre_whitespace = self.pre
144
144
145 self._oinfo = None
145 self._oinfo = None
146
146
147 def ofind(self, ip):
147 def ofind(self, ip):
148 """Do a full, attribute-walking lookup of the ifun in the various
148 """Do a full, attribute-walking lookup of the ifun in the various
149 namespaces for the given IPython InteractiveShell instance.
149 namespaces for the given IPython InteractiveShell instance.
150
150
151 Return a dict with keys: found,obj,ospace,ismagic
151 Return a dict with keys: found,obj,ospace,ismagic
152
152
153 Note: can cause state changes because of calling getattr, but should
153 Note: can cause state changes because of calling getattr, but should
154 only be run if autocall is on and if the line hasn't matched any
154 only be run if autocall is on and if the line hasn't matched any
155 other, less dangerous handlers.
155 other, less dangerous handlers.
156
156
157 Does cache the results of the call, so can be called multiple times
157 Does cache the results of the call, so can be called multiple times
158 without worrying about *further* damaging state.
158 without worrying about *further* damaging state.
159 """
159 """
160 if not self._oinfo:
160 if not self._oinfo:
161 self._oinfo = ip.shell._ofind(self.ifun)
161 self._oinfo = ip.shell._ofind(self.ifun)
162 return self._oinfo
162 return self._oinfo
163
163
164 def __str__(self):
164 def __str__(self):
165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
165 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
166
166
167
167
168 #-----------------------------------------------------------------------------
168 #-----------------------------------------------------------------------------
169 # Main Prefilter manager
169 # Main Prefilter manager
170 #-----------------------------------------------------------------------------
170 #-----------------------------------------------------------------------------
171
171
172
172
173 class PrefilterManager(Component):
173 class PrefilterManager(Component):
174 """Main prefilter component.
174 """Main prefilter component.
175
175
176 The IPython prefilter is run on all user input before it is run. The
176 The IPython prefilter is run on all user input before it is run. The
177 prefilter consumes lines of input and produces transformed lines of
177 prefilter consumes lines of input and produces transformed lines of
178 input.
178 input.
179
179
180 The iplementation consists of two phases:
180 The iplementation consists of two phases:
181
181
182 1. Transformers
182 1. Transformers
183 2. Checkers and handlers
183 2. Checkers and handlers
184
184
185 Over time, we plan on deprecating the checkers and handlers and doing
185 Over time, we plan on deprecating the checkers and handlers and doing
186 everything in the transformers.
186 everything in the transformers.
187
187
188 The transformers are instances of :class:`PrefilterTransformer` and have
188 The transformers are instances of :class:`PrefilterTransformer` and have
189 a single method :meth:`transform` that takes a line and returns a
189 a single method :meth:`transform` that takes a line and returns a
190 transformed line. The transformation can be accomplished using any
190 transformed line. The transformation can be accomplished using any
191 tool, but our current ones use regular expressions for speed. We also
191 tool, but our current ones use regular expressions for speed. We also
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
193
193
194 After all the transformers have been run, the line is fed to the checkers,
194 After all the transformers have been run, the line is fed to the checkers,
195 which are instances of :class:`PrefilterChecker`. The line is passed to
195 which are instances of :class:`PrefilterChecker`. The line is passed to
196 the :meth:`check` method, which either returns `None` or a
196 the :meth:`check` method, which either returns `None` or a
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
199 the line is passed to the :meth:`handle` method of the returned
199 the line is passed to the :meth:`handle` method of the returned
200 handler and no further checkers are tried.
200 handler and no further checkers are tried.
201
201
202 Both transformers and checkers have a `priority` attribute, that determines
202 Both transformers and checkers have a `priority` attribute, that determines
203 the order in which they are called. Smaller priorities are tried first.
203 the order in which they are called. Smaller priorities are tried first.
204
204
205 Both transformers and checkers also have `enabled` attribute, which is
205 Both transformers and checkers also have `enabled` attribute, which is
206 a boolean that determines if the instance is used.
206 a boolean that determines if the instance is used.
207
207
208 Users or developers can change the priority or enabled attribute of
208 Users or developers can change the priority or enabled attribute of
209 transformers or checkers, but they must call the :meth:`sort_checkers`
209 transformers or checkers, but they must call the :meth:`sort_checkers`
210 or :meth:`sort_transformers` method after changing the priority.
210 or :meth:`sort_transformers` method after changing the priority.
211 """
211 """
212
212
213 multi_line_specials = CBool(True, config=True)
213 multi_line_specials = CBool(True, config=True)
214
214
215 def __init__(self, parent, config=None):
215 def __init__(self, parent, config=None):
216 super(PrefilterManager, self).__init__(parent, config=config)
216 super(PrefilterManager, self).__init__(parent, config=config)
217 self.init_transformers()
217 self.init_transformers()
218 self.init_handlers()
218 self.init_handlers()
219 self.init_checkers()
219 self.init_checkers()
220
220
221 @auto_attr
221 @auto_attr
222 def shell(self):
222 def shell(self):
223 return Component.get_instances(
223 return Component.get_instances(
224 root=self.root,
224 root=self.root,
225 klass='IPython.core.iplib.InteractiveShell')[0]
225 klass='IPython.core.iplib.InteractiveShell')[0]
226
226
227 #-------------------------------------------------------------------------
227 #-------------------------------------------------------------------------
228 # API for managing transformers
228 # API for managing transformers
229 #-------------------------------------------------------------------------
229 #-------------------------------------------------------------------------
230
230
231 def init_transformers(self):
231 def init_transformers(self):
232 """Create the default transformers."""
232 """Create the default transformers."""
233 self._transformers = []
233 self._transformers = []
234 for transformer_cls in _default_transformers:
234 for transformer_cls in _default_transformers:
235 transformer_cls(self, config=self.config)
235 transformer_cls(self, config=self.config)
236
236
237 def sort_transformers(self):
237 def sort_transformers(self):
238 """Sort the transformers by priority.
238 """Sort the transformers by priority.
239
239
240 This must be called after the priority of a transformer is changed.
240 This must be called after the priority of a transformer is changed.
241 The :meth:`register_transformer` method calls this automatically.
241 The :meth:`register_transformer` method calls this automatically.
242 """
242 """
243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
243 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
244
244
245 @property
245 @property
246 def transformers(self):
246 def transformers(self):
247 """Return a list of checkers, sorted by priority."""
247 """Return a list of checkers, sorted by priority."""
248 return self._transformers
248 return self._transformers
249
249
250 def register_transformer(self, transformer):
250 def register_transformer(self, transformer):
251 """Register a transformer instance."""
251 """Register a transformer instance."""
252 if transformer not in self._transformers:
252 if transformer not in self._transformers:
253 self._transformers.append(transformer)
253 self._transformers.append(transformer)
254 self.sort_transformers()
254 self.sort_transformers()
255
255
256 def unregister_transformer(self, transformer):
256 def unregister_transformer(self, transformer):
257 """Unregister a transformer instance."""
257 """Unregister a transformer instance."""
258 if transformer in self._transformers:
258 if transformer in self._transformers:
259 self._transformers.remove(transformer)
259 self._transformers.remove(transformer)
260
260
261 #-------------------------------------------------------------------------
261 #-------------------------------------------------------------------------
262 # API for managing checkers
262 # API for managing checkers
263 #-------------------------------------------------------------------------
263 #-------------------------------------------------------------------------
264
264
265 def init_checkers(self):
265 def init_checkers(self):
266 """Create the default checkers."""
266 """Create the default checkers."""
267 self._checkers = []
267 self._checkers = []
268 for checker in _default_checkers:
268 for checker in _default_checkers:
269 checker(self, config=self.config)
269 checker(self, config=self.config)
270
270
271 def sort_checkers(self):
271 def sort_checkers(self):
272 """Sort the checkers by priority.
272 """Sort the checkers by priority.
273
273
274 This must be called after the priority of a checker is changed.
274 This must be called after the priority of a checker is changed.
275 The :meth:`register_checker` method calls this automatically.
275 The :meth:`register_checker` method calls this automatically.
276 """
276 """
277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
278
278
279 @property
279 @property
280 def checkers(self):
280 def checkers(self):
281 """Return a list of checkers, sorted by priority."""
281 """Return a list of checkers, sorted by priority."""
282 return self._checkers
282 return self._checkers
283
283
284 def register_checker(self, checker):
284 def register_checker(self, checker):
285 """Register a checker instance."""
285 """Register a checker instance."""
286 if checker not in self._checkers:
286 if checker not in self._checkers:
287 self._checkers.append(checker)
287 self._checkers.append(checker)
288 self.sort_checkers()
288 self.sort_checkers()
289
289
290 def unregister_checker(self, checker):
290 def unregister_checker(self, checker):
291 """Unregister a checker instance."""
291 """Unregister a checker instance."""
292 if checker in self._checkers:
292 if checker in self._checkers:
293 self._checkers.remove(checker)
293 self._checkers.remove(checker)
294
294
295 #-------------------------------------------------------------------------
295 #-------------------------------------------------------------------------
296 # API for managing checkers
296 # API for managing checkers
297 #-------------------------------------------------------------------------
297 #-------------------------------------------------------------------------
298
298
299 def init_handlers(self):
299 def init_handlers(self):
300 """Create the default handlers."""
300 """Create the default handlers."""
301 self._handlers = {}
301 self._handlers = {}
302 self._esc_handlers = {}
302 self._esc_handlers = {}
303 for handler in _default_handlers:
303 for handler in _default_handlers:
304 handler(self, config=self.config)
304 handler(self, config=self.config)
305
305
306 @property
306 @property
307 def handlers(self):
307 def handlers(self):
308 """Return a dict of all the handlers."""
308 """Return a dict of all the handlers."""
309 return self._handlers
309 return self._handlers
310
310
311 def register_handler(self, name, handler, esc_strings):
311 def register_handler(self, name, handler, esc_strings):
312 """Register a handler instance by name with esc_strings."""
312 """Register a handler instance by name with esc_strings."""
313 self._handlers[name] = handler
313 self._handlers[name] = handler
314 for esc_str in esc_strings:
314 for esc_str in esc_strings:
315 self._esc_handlers[esc_str] = handler
315 self._esc_handlers[esc_str] = handler
316
316
317 def unregister_handler(self, name, handler, esc_strings):
317 def unregister_handler(self, name, handler, esc_strings):
318 """Unregister a handler instance by name with esc_strings."""
318 """Unregister a handler instance by name with esc_strings."""
319 try:
319 try:
320 del self._handlers[name]
320 del self._handlers[name]
321 except KeyError:
321 except KeyError:
322 pass
322 pass
323 for esc_str in esc_strings:
323 for esc_str in esc_strings:
324 h = self._esc_handlers.get(esc_str)
324 h = self._esc_handlers.get(esc_str)
325 if h is handler:
325 if h is handler:
326 del self._esc_handlers[esc_str]
326 del self._esc_handlers[esc_str]
327
327
328 def get_handler_by_name(self, name):
328 def get_handler_by_name(self, name):
329 """Get a handler by its name."""
329 """Get a handler by its name."""
330 return self._handlers.get(name)
330 return self._handlers.get(name)
331
331
332 def get_handler_by_esc(self, esc_str):
332 def get_handler_by_esc(self, esc_str):
333 """Get a handler by its escape string."""
333 """Get a handler by its escape string."""
334 return self._esc_handlers.get(esc_str)
334 return self._esc_handlers.get(esc_str)
335
335
336 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
337 # Main prefiltering API
337 # Main prefiltering API
338 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
339
339
340 def prefilter_line_info(self, line_info):
340 def prefilter_line_info(self, line_info):
341 """Prefilter a line that has been converted to a LineInfo object.
341 """Prefilter a line that has been converted to a LineInfo object.
342
342
343 This implements the checker/handler part of the prefilter pipe.
343 This implements the checker/handler part of the prefilter pipe.
344 """
344 """
345 # print "prefilter_line_info: ", line_info
345 # print "prefilter_line_info: ", line_info
346 handler = self.find_handler(line_info)
346 handler = self.find_handler(line_info)
347 return handler.handle(line_info)
347 return handler.handle(line_info)
348
348
349 def find_handler(self, line_info):
349 def find_handler(self, line_info):
350 """Find a handler for the line_info by trying checkers."""
350 """Find a handler for the line_info by trying checkers."""
351 for checker in self.checkers:
351 for checker in self.checkers:
352 if checker.enabled:
352 if checker.enabled:
353 handler = checker.check(line_info)
353 handler = checker.check(line_info)
354 if handler:
354 if handler:
355 return handler
355 return handler
356 return self.get_handler_by_name('normal')
356 return self.get_handler_by_name('normal')
357
357
358 def transform_line(self, line, continue_prompt):
358 def transform_line(self, line, continue_prompt):
359 """Calls the enabled transformers in order of increasing priority."""
359 """Calls the enabled transformers in order of increasing priority."""
360 for transformer in self.transformers:
360 for transformer in self.transformers:
361 if transformer.enabled:
361 if transformer.enabled:
362 line = transformer.transform(line, continue_prompt)
362 line = transformer.transform(line, continue_prompt)
363 return line
363 return line
364
364
365 def prefilter_line(self, line, continue_prompt):
365 def prefilter_line(self, line, continue_prompt):
366 """Prefilter a single input line as text.
366 """Prefilter a single input line as text.
367
367
368 This method prefilters a single line of text by calling the
368 This method prefilters a single line of text by calling the
369 transformers and then the checkers/handlers.
369 transformers and then the checkers/handlers.
370 """
370 """
371
371
372 # print "prefilter_line: ", line, continue_prompt
372 # print "prefilter_line: ", line, continue_prompt
373 # All handlers *must* return a value, even if it's blank ('').
373 # All handlers *must* return a value, even if it's blank ('').
374
374
375 # Lines are NOT logged here. Handlers should process the line as
375 # Lines are NOT logged here. Handlers should process the line as
376 # needed, update the cache AND log it (so that the input cache array
376 # needed, update the cache AND log it (so that the input cache array
377 # stays synced).
377 # stays synced).
378
378
379 # save the line away in case we crash, so the post-mortem handler can
379 # save the line away in case we crash, so the post-mortem handler can
380 # record it
380 # record it
381 self.shell._last_input_line = line
381 self.shell._last_input_line = line
382
382
383 if not line:
383 if not line:
384 # Return immediately on purely empty lines, so that if the user
384 # Return immediately on purely empty lines, so that if the user
385 # previously typed some whitespace that started a continuation
385 # previously typed some whitespace that started a continuation
386 # prompt, he can break out of that loop with just an empty line.
386 # prompt, he can break out of that loop with just an empty line.
387 # This is how the default python prompt works.
387 # This is how the default python prompt works.
388
388
389 # Only return if the accumulated input buffer was just whitespace!
389 # Only return if the accumulated input buffer was just whitespace!
390 if ''.join(self.shell.buffer).isspace():
390 if ''.join(self.shell.buffer).isspace():
391 self.shell.buffer[:] = []
391 self.shell.buffer[:] = []
392 return ''
392 return ''
393
393
394 # At this point, we invoke our transformers.
394 # At this point, we invoke our transformers.
395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
395 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 line = self.transform_line(line, continue_prompt)
396 line = self.transform_line(line, continue_prompt)
397
397
398 # Now we compute line_info for the checkers and handlers
398 # Now we compute line_info for the checkers and handlers
399 line_info = LineInfo(line, continue_prompt)
399 line_info = LineInfo(line, continue_prompt)
400
400
401 # the input history needs to track even empty lines
401 # the input history needs to track even empty lines
402 stripped = line.strip()
402 stripped = line.strip()
403
403
404 normal_handler = self.get_handler_by_name('normal')
404 normal_handler = self.get_handler_by_name('normal')
405 if not stripped:
405 if not stripped:
406 if not continue_prompt:
406 if not continue_prompt:
407 self.shell.outputcache.prompt_count -= 1
407 self.shell.outputcache.prompt_count -= 1
408
408
409 return normal_handler.handle(line_info)
409 return normal_handler.handle(line_info)
410
410
411 # special handlers are only allowed for single line statements
411 # special handlers are only allowed for single line statements
412 if continue_prompt and not self.multi_line_specials:
412 if continue_prompt and not self.multi_line_specials:
413 return normal_handler.handle(line_info)
413 return normal_handler.handle(line_info)
414
414
415 prefiltered = self.prefilter_line_info(line_info)
415 prefiltered = self.prefilter_line_info(line_info)
416 # print "prefiltered line: %r" % prefiltered
416 # print "prefiltered line: %r" % prefiltered
417 return prefiltered
417 return prefiltered
418
418
419 def prefilter_lines(self, lines, continue_prompt):
419 def prefilter_lines(self, lines, continue_prompt):
420 """Prefilter multiple input lines of text.
420 """Prefilter multiple input lines of text.
421
421
422 This is the main entry point for prefiltering multiple lines of
422 This is the main entry point for prefiltering multiple lines of
423 input. This simply calls :meth:`prefilter_line` for each line of
423 input. This simply calls :meth:`prefilter_line` for each line of
424 input.
424 input.
425
425
426 This covers cases where there are multiple lines in the user entry,
426 This covers cases where there are multiple lines in the user entry,
427 which is the case when the user goes back to a multiline history
427 which is the case when the user goes back to a multiline history
428 entry and presses enter.
428 entry and presses enter.
429 """
429 """
430 out = []
430 out = []
431 for line in lines.rstrip('\n').split('\n'):
431 for line in lines.rstrip('\n').split('\n'):
432 out.append(self.prefilter_line(line, continue_prompt))
432 out.append(self.prefilter_line(line, continue_prompt))
433 return '\n'.join(out)
433 return '\n'.join(out)
434
434
435
435
436 #-----------------------------------------------------------------------------
436 #-----------------------------------------------------------------------------
437 # Prefilter transformers
437 # Prefilter transformers
438 #-----------------------------------------------------------------------------
438 #-----------------------------------------------------------------------------
439
439
440
440
441 class PrefilterTransformer(Component):
441 class PrefilterTransformer(Component):
442 """Transform a line of user input."""
442 """Transform a line of user input."""
443
443
444 priority = Int(100, config=True)
444 priority = Int(100, config=True)
445 shell = Any
445 shell = Any
446 prefilter_manager = Any
446 prefilter_manager = Any
447 enabled = Bool(True, config=True)
447 enabled = Bool(True, config=True)
448
448
449 def __init__(self, parent, config=None):
449 def __init__(self, parent, config=None):
450 super(PrefilterTransformer, self).__init__(parent, config=config)
450 super(PrefilterTransformer, self).__init__(parent, config=config)
451 self.prefilter_manager.register_transformer(self)
451 self.prefilter_manager.register_transformer(self)
452
452
453 @auto_attr
453 @auto_attr
454 def shell(self):
454 def shell(self):
455 return Component.get_instances(
455 return Component.get_instances(
456 root=self.root,
456 root=self.root,
457 klass='IPython.core.iplib.InteractiveShell')[0]
457 klass='IPython.core.iplib.InteractiveShell')[0]
458
458
459 @auto_attr
459 @auto_attr
460 def prefilter_manager(self):
460 def prefilter_manager(self):
461 return PrefilterManager.get_instances(root=self.root)[0]
461 return PrefilterManager.get_instances(root=self.root)[0]
462
462
463 def transform(self, line, continue_prompt):
463 def transform(self, line, continue_prompt):
464 """Transform a line, returning the new one."""
464 """Transform a line, returning the new one."""
465 return None
465 return None
466
466
467 def __repr__(self):
467 def __repr__(self):
468 return "<%s(priority=%r, enabled=%r)>" % (
468 return "<%s(priority=%r, enabled=%r)>" % (
469 self.__class__.__name__, self.priority, self.enabled)
469 self.__class__.__name__, self.priority, self.enabled)
470
470
471
471
472 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
472 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
473 r'\s*=\s*!(?P<cmd>.*)')
473 r'\s*=\s*!(?P<cmd>.*)')
474
474
475
475
476 class AssignSystemTransformer(PrefilterTransformer):
476 class AssignSystemTransformer(PrefilterTransformer):
477 """Handle the `files = !ls` syntax."""
477 """Handle the `files = !ls` syntax."""
478
478
479 priority = Int(100, config=True)
479 priority = Int(100, config=True)
480
480
481 def transform(self, line, continue_prompt):
481 def transform(self, line, continue_prompt):
482 m = _assign_system_re.match(line)
482 m = _assign_system_re.match(line)
483 if m is not None:
483 if m is not None:
484 cmd = m.group('cmd')
484 cmd = m.group('cmd')
485 lhs = m.group('lhs')
485 lhs = m.group('lhs')
486 expr = make_quoted_expr("sc -l =%s" % cmd)
486 expr = make_quoted_expr("sc -l =%s" % cmd)
487 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
487 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
488 return new_line
488 return new_line
489 return line
489 return line
490
490
491
491
492 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
492 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
493 r'\s*=\s*%(?P<cmd>.*)')
493 r'\s*=\s*%(?P<cmd>.*)')
494
494
495 class AssignMagicTransformer(PrefilterTransformer):
495 class AssignMagicTransformer(PrefilterTransformer):
496 """Handle the `a = %who` syntax."""
496 """Handle the `a = %who` syntax."""
497
497
498 priority = Int(200, config=True)
498 priority = Int(200, config=True)
499
499
500 def transform(self, line, continue_prompt):
500 def transform(self, line, continue_prompt):
501 m = _assign_magic_re.match(line)
501 m = _assign_magic_re.match(line)
502 if m is not None:
502 if m is not None:
503 cmd = m.group('cmd')
503 cmd = m.group('cmd')
504 lhs = m.group('lhs')
504 lhs = m.group('lhs')
505 expr = make_quoted_expr(cmd)
505 expr = make_quoted_expr(cmd)
506 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
506 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
507 return new_line
507 return new_line
508 return line
508 return line
509
509
510
510
511 #-----------------------------------------------------------------------------
511 #-----------------------------------------------------------------------------
512 # Prefilter checkers
512 # Prefilter checkers
513 #-----------------------------------------------------------------------------
513 #-----------------------------------------------------------------------------
514
514
515
515
516 class PrefilterChecker(Component):
516 class PrefilterChecker(Component):
517 """Inspect an input line and return a handler for that line."""
517 """Inspect an input line and return a handler for that line."""
518
518
519 priority = Int(100, config=True)
519 priority = Int(100, config=True)
520 shell = Any
520 shell = Any
521 prefilter_manager = Any
521 prefilter_manager = Any
522 enabled = Bool(True, config=True)
522 enabled = Bool(True, config=True)
523
523
524 def __init__(self, parent, config=None):
524 def __init__(self, parent, config=None):
525 super(PrefilterChecker, self).__init__(parent, config=config)
525 super(PrefilterChecker, self).__init__(parent, config=config)
526 self.prefilter_manager.register_checker(self)
526 self.prefilter_manager.register_checker(self)
527
527
528 @auto_attr
528 @auto_attr
529 def shell(self):
529 def shell(self):
530 return Component.get_instances(
530 return Component.get_instances(
531 root=self.root,
531 root=self.root,
532 klass='IPython.core.iplib.InteractiveShell')[0]
532 klass='IPython.core.iplib.InteractiveShell')[0]
533
533
534 @auto_attr
534 @auto_attr
535 def prefilter_manager(self):
535 def prefilter_manager(self):
536 return PrefilterManager.get_instances(root=self.root)[0]
536 return PrefilterManager.get_instances(root=self.root)[0]
537
537
538 def check(self, line_info):
538 def check(self, line_info):
539 """Inspect line_info and return a handler instance or None."""
539 """Inspect line_info and return a handler instance or None."""
540 return None
540 return None
541
541
542 def __repr__(self):
542 def __repr__(self):
543 return "<%s(priority=%r, enabled=%r)>" % (
543 return "<%s(priority=%r, enabled=%r)>" % (
544 self.__class__.__name__, self.priority, self.enabled)
544 self.__class__.__name__, self.priority, self.enabled)
545
545
546
546
547 class EmacsChecker(PrefilterChecker):
547 class EmacsChecker(PrefilterChecker):
548
548
549 priority = Int(100, config=True)
549 priority = Int(100, config=True)
550 enabled = Bool(False, config=True)
550 enabled = Bool(False, config=True)
551
551
552 def check(self, line_info):
552 def check(self, line_info):
553 "Emacs ipython-mode tags certain input lines."
553 "Emacs ipython-mode tags certain input lines."
554 if line_info.line.endswith('# PYTHON-MODE'):
554 if line_info.line.endswith('# PYTHON-MODE'):
555 return self.prefilter_manager.get_handler_by_name('emacs')
555 return self.prefilter_manager.get_handler_by_name('emacs')
556 else:
556 else:
557 return None
557 return None
558
558
559
559
560 class ShellEscapeChecker(PrefilterChecker):
560 class ShellEscapeChecker(PrefilterChecker):
561
561
562 priority = Int(200, config=True)
562 priority = Int(200, config=True)
563
563
564 def check(self, line_info):
564 def check(self, line_info):
565 if line_info.line.lstrip().startswith(ESC_SHELL):
565 if line_info.line.lstrip().startswith(ESC_SHELL):
566 return self.prefilter_manager.get_handler_by_name('shell')
566 return self.prefilter_manager.get_handler_by_name('shell')
567
567
568
568
569 class IPyAutocallChecker(PrefilterChecker):
569 class IPyAutocallChecker(PrefilterChecker):
570
570
571 priority = Int(300, config=True)
571 priority = Int(300, config=True)
572
572
573 def check(self, line_info):
573 def check(self, line_info):
574 "Instances of IPyAutocall in user_ns get autocalled immediately"
574 "Instances of IPyAutocall in user_ns get autocalled immediately"
575 obj = self.shell.user_ns.get(line_info.ifun, None)
575 obj = self.shell.user_ns.get(line_info.ifun, None)
576 if isinstance(obj, IPyAutocall):
576 if isinstance(obj, IPyAutocall):
577 obj.set_ip(self.shell)
577 obj.set_ip(self.shell)
578 return self.prefilter_manager.get_handler_by_name('auto')
578 return self.prefilter_manager.get_handler_by_name('auto')
579 else:
579 else:
580 return None
580 return None
581
581
582
582
583 class MultiLineMagicChecker(PrefilterChecker):
583 class MultiLineMagicChecker(PrefilterChecker):
584
584
585 priority = Int(400, config=True)
585 priority = Int(400, config=True)
586
586
587 def check(self, line_info):
587 def check(self, line_info):
588 "Allow ! and !! in multi-line statements if multi_line_specials is on"
588 "Allow ! and !! in multi-line statements if multi_line_specials is on"
589 # Note that this one of the only places we check the first character of
589 # Note that this one of the only places we check the first character of
590 # ifun and *not* the pre_char. Also note that the below test matches
590 # ifun and *not* the pre_char. Also note that the below test matches
591 # both ! and !!.
591 # both ! and !!.
592 if line_info.continue_prompt \
592 if line_info.continue_prompt \
593 and self.prefilter_manager.multi_line_specials:
593 and self.prefilter_manager.multi_line_specials:
594 if line_info.ifun.startswith(ESC_MAGIC):
594 if line_info.ifun.startswith(ESC_MAGIC):
595 return self.prefilter_manager.get_handler_by_name('magic')
595 return self.prefilter_manager.get_handler_by_name('magic')
596 else:
596 else:
597 return None
597 return None
598
598
599
599
600 class EscCharsChecker(PrefilterChecker):
600 class EscCharsChecker(PrefilterChecker):
601
601
602 priority = Int(500, config=True)
602 priority = Int(500, config=True)
603
603
604 def check(self, line_info):
604 def check(self, line_info):
605 """Check for escape character and return either a handler to handle it,
605 """Check for escape character and return either a handler to handle it,
606 or None if there is no escape char."""
606 or None if there is no escape char."""
607 if line_info.line[-1] == ESC_HELP \
607 if line_info.line[-1] == ESC_HELP \
608 and line_info.pre_char != ESC_SHELL \
608 and line_info.pre_char != ESC_SHELL \
609 and line_info.pre_char != ESC_SH_CAP:
609 and line_info.pre_char != ESC_SH_CAP:
610 # the ? can be at the end, but *not* for either kind of shell escape,
610 # the ? can be at the end, but *not* for either kind of shell escape,
611 # because a ? can be a vaild final char in a shell cmd
611 # because a ? can be a vaild final char in a shell cmd
612 return self.prefilter_manager.get_handler_by_name('help')
612 return self.prefilter_manager.get_handler_by_name('help')
613 else:
613 else:
614 # This returns None like it should if no handler exists
614 # This returns None like it should if no handler exists
615 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
615 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
616
616
617
617
618 class AssignmentChecker(PrefilterChecker):
618 class AssignmentChecker(PrefilterChecker):
619
619
620 priority = Int(600, config=True)
620 priority = Int(600, config=True)
621
621
622 def check(self, line_info):
622 def check(self, line_info):
623 """Check to see if user is assigning to a var for the first time, in
623 """Check to see if user is assigning to a var for the first time, in
624 which case we want to avoid any sort of automagic / autocall games.
624 which case we want to avoid any sort of automagic / autocall games.
625
625
626 This allows users to assign to either alias or magic names true python
626 This allows users to assign to either alias or magic names true python
627 variables (the magic/alias systems always take second seat to true
627 variables (the magic/alias systems always take second seat to true
628 python code). E.g. ls='hi', or ls,that=1,2"""
628 python code). E.g. ls='hi', or ls,that=1,2"""
629 if line_info.the_rest:
629 if line_info.the_rest:
630 if line_info.the_rest[0] in '=,':
630 if line_info.the_rest[0] in '=,':
631 return self.prefilter_manager.get_handler_by_name('normal')
631 return self.prefilter_manager.get_handler_by_name('normal')
632 else:
632 else:
633 return None
633 return None
634
634
635
635
636 class AutoMagicChecker(PrefilterChecker):
636 class AutoMagicChecker(PrefilterChecker):
637
637
638 priority = Int(700, config=True)
638 priority = Int(700, config=True)
639
639
640 def check(self, line_info):
640 def check(self, line_info):
641 """If the ifun is magic, and automagic is on, run it. Note: normal,
641 """If the ifun is magic, and automagic is on, run it. Note: normal,
642 non-auto magic would already have been triggered via '%' in
642 non-auto magic would already have been triggered via '%' in
643 check_esc_chars. This just checks for automagic. Also, before
643 check_esc_chars. This just checks for automagic. Also, before
644 triggering the magic handler, make sure that there is nothing in the
644 triggering the magic handler, make sure that there is nothing in the
645 user namespace which could shadow it."""
645 user namespace which could shadow it."""
646 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
646 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
647 return None
647 return None
648
648
649 # We have a likely magic method. Make sure we should actually call it.
649 # We have a likely magic method. Make sure we should actually call it.
650 if line_info.continue_prompt and not self.shell.multi_line_specials:
650 if line_info.continue_prompt and not self.shell.multi_line_specials:
651 return None
651 return None
652
652
653 head = line_info.ifun.split('.',1)[0]
653 head = line_info.ifun.split('.',1)[0]
654 if is_shadowed(head, self.shell):
654 if is_shadowed(head, self.shell):
655 return None
655 return None
656
656
657 return self.prefilter_manager.get_handler_by_name('magic')
657 return self.prefilter_manager.get_handler_by_name('magic')
658
658
659
659
660 class AliasChecker(PrefilterChecker):
660 class AliasChecker(PrefilterChecker):
661
661
662 priority = Int(800, config=True)
662 priority = Int(800, config=True)
663
663
664 @auto_attr
664 @auto_attr
665 def alias_manager(self):
665 def alias_manager(self):
666 return AliasManager.get_instances(root=self.root)[0]
666 return AliasManager.get_instances(root=self.root)[0]
667
667
668 def check(self, line_info):
668 def check(self, line_info):
669 "Check if the initital identifier on the line is an alias."
669 "Check if the initital identifier on the line is an alias."
670 # Note: aliases can not contain '.'
670 # Note: aliases can not contain '.'
671 head = line_info.ifun.split('.',1)[0]
671 head = line_info.ifun.split('.',1)[0]
672 if line_info.ifun not in self.alias_manager \
672 if line_info.ifun not in self.alias_manager \
673 or head not in self.alias_manager \
673 or head not in self.alias_manager \
674 or is_shadowed(head, self.shell):
674 or is_shadowed(head, self.shell):
675 return None
675 return None
676
676
677 return self.prefilter_manager.get_handler_by_name('alias')
677 return self.prefilter_manager.get_handler_by_name('alias')
678
678
679
679
680 class PythonOpsChecker(PrefilterChecker):
680 class PythonOpsChecker(PrefilterChecker):
681
681
682 priority = Int(900, config=True)
682 priority = Int(900, config=True)
683
683
684 def check(self, line_info):
684 def check(self, line_info):
685 """If the 'rest' of the line begins with a function call or pretty much
685 """If the 'rest' of the line begins with a function call or pretty much
686 any python operator, we should simply execute the line (regardless of
686 any python operator, we should simply execute the line (regardless of
687 whether or not there's a possible autocall expansion). This avoids
687 whether or not there's a possible autocall expansion). This avoids
688 spurious (and very confusing) geattr() accesses."""
688 spurious (and very confusing) geattr() accesses."""
689 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
689 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
690 return self.prefilter_manager.get_handler_by_name('normal')
690 return self.prefilter_manager.get_handler_by_name('normal')
691 else:
691 else:
692 return None
692 return None
693
693
694
694
695 class AutocallChecker(PrefilterChecker):
695 class AutocallChecker(PrefilterChecker):
696
696
697 priority = Int(1000, config=True)
697 priority = Int(1000, config=True)
698
698
699 def check(self, line_info):
699 def check(self, line_info):
700 "Check if the initial word/function is callable and autocall is on."
700 "Check if the initial word/function is callable and autocall is on."
701 if not self.shell.autocall:
701 if not self.shell.autocall:
702 return None
702 return None
703
703
704 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
704 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
705 if not oinfo['found']:
705 if not oinfo['found']:
706 return None
706 return None
707
707
708 if callable(oinfo['obj']) \
708 if callable(oinfo['obj']) \
709 and (not re_exclude_auto.match(line_info.the_rest)) \
709 and (not re_exclude_auto.match(line_info.the_rest)) \
710 and re_fun_name.match(line_info.ifun):
710 and re_fun_name.match(line_info.ifun):
711 return self.prefilter_manager.get_handler_by_name('auto')
711 return self.prefilter_manager.get_handler_by_name('auto')
712 else:
712 else:
713 return None
713 return None
714
714
715
715
716 #-----------------------------------------------------------------------------
716 #-----------------------------------------------------------------------------
717 # Prefilter handlers
717 # Prefilter handlers
718 #-----------------------------------------------------------------------------
718 #-----------------------------------------------------------------------------
719
719
720
720
721 class PrefilterHandler(Component):
721 class PrefilterHandler(Component):
722
722
723 handler_name = Str('normal')
723 handler_name = Str('normal')
724 esc_strings = List([])
724 esc_strings = List([])
725 shell = Any
725 shell = Any
726 prefilter_manager = Any
726 prefilter_manager = Any
727
727
728 def __init__(self, parent, config=None):
728 def __init__(self, parent, config=None):
729 super(PrefilterHandler, self).__init__(parent, config=config)
729 super(PrefilterHandler, self).__init__(parent, config=config)
730 self.prefilter_manager.register_handler(
730 self.prefilter_manager.register_handler(
731 self.handler_name,
731 self.handler_name,
732 self,
732 self,
733 self.esc_strings
733 self.esc_strings
734 )
734 )
735
735
736 @auto_attr
736 @auto_attr
737 def shell(self):
737 def shell(self):
738 return Component.get_instances(
738 return Component.get_instances(
739 root=self.root,
739 root=self.root,
740 klass='IPython.core.iplib.InteractiveShell')[0]
740 klass='IPython.core.iplib.InteractiveShell')[0]
741
741
742 @auto_attr
742 @auto_attr
743 def prefilter_manager(self):
743 def prefilter_manager(self):
744 return PrefilterManager.get_instances(root=self.root)[0]
744 return PrefilterManager.get_instances(root=self.root)[0]
745
745
746 def handle(self, line_info):
746 def handle(self, line_info):
747 # print "normal: ", line_info
747 # print "normal: ", line_info
748 """Handle normal input lines. Use as a template for handlers."""
748 """Handle normal input lines. Use as a template for handlers."""
749
749
750 # With autoindent on, we need some way to exit the input loop, and I
750 # With autoindent on, we need some way to exit the input loop, and I
751 # don't want to force the user to have to backspace all the way to
751 # don't want to force the user to have to backspace all the way to
752 # clear the line. The rule will be in this case, that either two
752 # clear the line. The rule will be in this case, that either two
753 # lines of pure whitespace in a row, or a line of pure whitespace but
753 # lines of pure whitespace in a row, or a line of pure whitespace but
754 # of a size different to the indent level, will exit the input loop.
754 # of a size different to the indent level, will exit the input loop.
755 line = line_info.line
755 line = line_info.line
756 continue_prompt = line_info.continue_prompt
756 continue_prompt = line_info.continue_prompt
757
757
758 if (continue_prompt and self.shell.autoindent and line.isspace() and
758 if (continue_prompt and self.shell.autoindent and line.isspace() and
759 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 or
759 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 or
760 (self.shell.buffer[-1]).isspace() )):
760 (self.shell.buffer[-1]).isspace() )):
761 line = ''
761 line = ''
762
762
763 self.shell.log(line, line, continue_prompt)
763 self.shell.log(line, line, continue_prompt)
764 return line
764 return line
765
765
766 def __str__(self):
766 def __str__(self):
767 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
767 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
768
768
769
769
770 class AliasHandler(PrefilterHandler):
770 class AliasHandler(PrefilterHandler):
771
771
772 handler_name = Str('alias')
772 handler_name = Str('alias')
773
773
774 @auto_attr
774 @auto_attr
775 def alias_manager(self):
775 def alias_manager(self):
776 return AliasManager.get_instances(root=self.root)[0]
776 return AliasManager.get_instances(root=self.root)[0]
777
777
778 def handle(self, line_info):
778 def handle(self, line_info):
779 """Handle alias input lines. """
779 """Handle alias input lines. """
780 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
780 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
781 # pre is needed, because it carries the leading whitespace. Otherwise
781 # pre is needed, because it carries the leading whitespace. Otherwise
782 # aliases won't work in indented sections.
782 # aliases won't work in indented sections.
783 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
783 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
784 make_quoted_expr(transformed))
784 make_quoted_expr(transformed))
785
785
786 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
786 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
787 return line_out
787 return line_out
788
788
789
789
790 class ShellEscapeHandler(PrefilterHandler):
790 class ShellEscapeHandler(PrefilterHandler):
791
791
792 handler_name = Str('shell')
792 handler_name = Str('shell')
793 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
793 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
794
794
795 def handle(self, line_info):
795 def handle(self, line_info):
796 """Execute the line in a shell, empty return value"""
796 """Execute the line in a shell, empty return value"""
797 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
797 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
798
798
799 line = line_info.line
799 line = line_info.line
800 if line.lstrip().startswith(ESC_SH_CAP):
800 if line.lstrip().startswith(ESC_SH_CAP):
801 # rewrite LineInfo's line, ifun and the_rest to properly hold the
801 # rewrite LineInfo's line, ifun and the_rest to properly hold the
802 # call to %sx and the actual command to be executed, so
802 # call to %sx and the actual command to be executed, so
803 # handle_magic can work correctly. Note that this works even if
803 # handle_magic can work correctly. Note that this works even if
804 # the line is indented, so it handles multi_line_specials
804 # the line is indented, so it handles multi_line_specials
805 # properly.
805 # properly.
806 new_rest = line.lstrip()[2:]
806 new_rest = line.lstrip()[2:]
807 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
807 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
808 line_info.ifun = 'sx'
808 line_info.ifun = 'sx'
809 line_info.the_rest = new_rest
809 line_info.the_rest = new_rest
810 return magic_handler.handle(line_info)
810 return magic_handler.handle(line_info)
811 else:
811 else:
812 cmd = line.lstrip().lstrip(ESC_SHELL)
812 cmd = line.lstrip().lstrip(ESC_SHELL)
813 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
813 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
814 make_quoted_expr(cmd))
814 make_quoted_expr(cmd))
815 # update cache/log and return
815 # update cache/log and return
816 self.shell.log(line, line_out, line_info.continue_prompt)
816 self.shell.log(line, line_out, line_info.continue_prompt)
817 return line_out
817 return line_out
818
818
819
819
820 class MagicHandler(PrefilterHandler):
820 class MagicHandler(PrefilterHandler):
821
821
822 handler_name = Str('magic')
822 handler_name = Str('magic')
823 esc_strings = List([ESC_MAGIC])
823 esc_strings = List([ESC_MAGIC])
824
824
825 def handle(self, line_info):
825 def handle(self, line_info):
826 """Execute magic functions."""
826 """Execute magic functions."""
827 ifun = line_info.ifun
827 ifun = line_info.ifun
828 the_rest = line_info.the_rest
828 the_rest = line_info.the_rest
829 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
829 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
830 make_quoted_expr(ifun + " " + the_rest))
830 make_quoted_expr(ifun + " " + the_rest))
831 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
831 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
832 return cmd
832 return cmd
833
833
834
834
835 class AutoHandler(PrefilterHandler):
835 class AutoHandler(PrefilterHandler):
836
836
837 handler_name = Str('auto')
837 handler_name = Str('auto')
838 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
838 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
839
839
840 def handle(self, line_info):
840 def handle(self, line_info):
841 """Hande lines which can be auto-executed, quoting if requested."""
841 """Hande lines which can be auto-executed, quoting if requested."""
842 line = line_info.line
842 line = line_info.line
843 ifun = line_info.ifun
843 ifun = line_info.ifun
844 the_rest = line_info.the_rest
844 the_rest = line_info.the_rest
845 pre = line_info.pre
845 pre = line_info.pre
846 continue_prompt = line_info.continue_prompt
846 continue_prompt = line_info.continue_prompt
847 obj = line_info.ofind(self)['obj']
847 obj = line_info.ofind(self)['obj']
848
849 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
848 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
850
849
851 # This should only be active for single-line input!
850 # This should only be active for single-line input!
852 if continue_prompt:
851 if continue_prompt:
853 # XXX - Ugly hack! We are breaking on multiline input and I'm out
854 # of time tonight to disentangle the component hirerarchy issue
855 # here... Fix this more cleanly later.
856 self.shell.log(line,line,continue_prompt)
852 self.shell.log(line,line,continue_prompt)
857
858 return line
853 return line
859
854
860 force_auto = isinstance(obj, IPyAutocall)
855 force_auto = isinstance(obj, IPyAutocall)
861 auto_rewrite = True
856 auto_rewrite = True
862
857
863 if pre == ESC_QUOTE:
858 if pre == ESC_QUOTE:
864 # Auto-quote splitting on whitespace
859 # Auto-quote splitting on whitespace
865 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
860 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
866 elif pre == ESC_QUOTE2:
861 elif pre == ESC_QUOTE2:
867 # Auto-quote whole string
862 # Auto-quote whole string
868 newcmd = '%s("%s")' % (ifun,the_rest)
863 newcmd = '%s("%s")' % (ifun,the_rest)
869 elif pre == ESC_PAREN:
864 elif pre == ESC_PAREN:
870 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
865 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
871 else:
866 else:
872 # Auto-paren.
867 # Auto-paren.
873 # We only apply it to argument-less calls if the autocall
868 # We only apply it to argument-less calls if the autocall
874 # parameter is set to 2. We only need to check that autocall is <
869 # parameter is set to 2. We only need to check that autocall is <
875 # 2, since this function isn't called unless it's at least 1.
870 # 2, since this function isn't called unless it's at least 1.
876 if not the_rest and (self.shell.autocall < 2) and not force_auto:
871 if not the_rest and (self.shell.autocall < 2) and not force_auto:
877 newcmd = '%s %s' % (ifun,the_rest)
872 newcmd = '%s %s' % (ifun,the_rest)
878 auto_rewrite = False
873 auto_rewrite = False
879 else:
874 else:
880 if not force_auto and the_rest.startswith('['):
875 if not force_auto and the_rest.startswith('['):
881 if hasattr(obj,'__getitem__'):
876 if hasattr(obj,'__getitem__'):
882 # Don't autocall in this case: item access for an object
877 # Don't autocall in this case: item access for an object
883 # which is BOTH callable and implements __getitem__.
878 # which is BOTH callable and implements __getitem__.
884 newcmd = '%s %s' % (ifun,the_rest)
879 newcmd = '%s %s' % (ifun,the_rest)
885 auto_rewrite = False
880 auto_rewrite = False
886 else:
881 else:
887 # if the object doesn't support [] access, go ahead and
882 # if the object doesn't support [] access, go ahead and
888 # autocall
883 # autocall
889 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
884 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
890 elif the_rest.endswith(';'):
885 elif the_rest.endswith(';'):
891 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
886 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
892 else:
887 else:
893 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
888 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
894
889
895 if auto_rewrite:
890 if auto_rewrite:
896 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
891 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
897
892
898 try:
893 try:
899 # plain ascii works better w/ pyreadline, on some machines, so
894 # plain ascii works better w/ pyreadline, on some machines, so
900 # we use it and only print uncolored rewrite if we have unicode
895 # we use it and only print uncolored rewrite if we have unicode
901 rw = str(rw)
896 rw = str(rw)
902 print >>Term.cout, rw
897 print >>Term.cout, rw
903 except UnicodeEncodeError:
898 except UnicodeEncodeError:
904 print "-------------->" + newcmd
899 print "-------------->" + newcmd
905
900
906 # log what is now valid Python, not the actual user input (without the
901 # log what is now valid Python, not the actual user input (without the
907 # final newline)
902 # final newline)
908 self.shell.log(line,newcmd,continue_prompt)
903 self.shell.log(line,newcmd,continue_prompt)
909 return newcmd
904 return newcmd
910
905
911
906
912 class HelpHandler(PrefilterHandler):
907 class HelpHandler(PrefilterHandler):
913
908
914 handler_name = Str('help')
909 handler_name = Str('help')
915 esc_strings = List([ESC_HELP])
910 esc_strings = List([ESC_HELP])
916
911
917 def handle(self, line_info):
912 def handle(self, line_info):
918 """Try to get some help for the object.
913 """Try to get some help for the object.
919
914
920 obj? or ?obj -> basic information.
915 obj? or ?obj -> basic information.
921 obj?? or ??obj -> more details.
916 obj?? or ??obj -> more details.
922 """
917 """
923 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
918 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
924 line = line_info.line
919 line = line_info.line
925 # We need to make sure that we don't process lines which would be
920 # We need to make sure that we don't process lines which would be
926 # otherwise valid python, such as "x=1 # what?"
921 # otherwise valid python, such as "x=1 # what?"
927 try:
922 try:
928 codeop.compile_command(line)
923 codeop.compile_command(line)
929 except SyntaxError:
924 except SyntaxError:
930 # We should only handle as help stuff which is NOT valid syntax
925 # We should only handle as help stuff which is NOT valid syntax
931 if line[0]==ESC_HELP:
926 if line[0]==ESC_HELP:
932 line = line[1:]
927 line = line[1:]
933 elif line[-1]==ESC_HELP:
928 elif line[-1]==ESC_HELP:
934 line = line[:-1]
929 line = line[:-1]
935 self.shell.log(line, '#?'+line, line_info.continue_prompt)
930 self.shell.log(line, '#?'+line, line_info.continue_prompt)
936 if line:
931 if line:
937 #print 'line:<%r>' % line # dbg
932 #print 'line:<%r>' % line # dbg
938 self.shell.magic_pinfo(line)
933 self.shell.magic_pinfo(line)
939 else:
934 else:
940 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
935 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
941 return '' # Empty string is needed here!
936 return '' # Empty string is needed here!
942 except:
937 except:
943 raise
938 raise
944 # Pass any other exceptions through to the normal handler
939 # Pass any other exceptions through to the normal handler
945 return normal_handler.handle(line_info)
940 return normal_handler.handle(line_info)
946 else:
941 else:
947 raise
942 raise
948 # If the code compiles ok, we should handle it normally
943 # If the code compiles ok, we should handle it normally
949 return normal_handler.handle(line_info)
944 return normal_handler.handle(line_info)
950
945
951
946
952 class EmacsHandler(PrefilterHandler):
947 class EmacsHandler(PrefilterHandler):
953
948
954 handler_name = Str('emacs')
949 handler_name = Str('emacs')
955 esc_strings = List([])
950 esc_strings = List([])
956
951
957 def handle(self, line_info):
952 def handle(self, line_info):
958 """Handle input lines marked by python-mode."""
953 """Handle input lines marked by python-mode."""
959
954
960 # Currently, nothing is done. Later more functionality can be added
955 # Currently, nothing is done. Later more functionality can be added
961 # here if needed.
956 # here if needed.
962
957
963 # The input cache shouldn't be updated
958 # The input cache shouldn't be updated
964 return line_info.line
959 return line_info.line
965
960
966
961
967 #-----------------------------------------------------------------------------
962 #-----------------------------------------------------------------------------
968 # Defaults
963 # Defaults
969 #-----------------------------------------------------------------------------
964 #-----------------------------------------------------------------------------
970
965
971
966
972 _default_transformers = [
967 _default_transformers = [
973 AssignSystemTransformer,
968 AssignSystemTransformer,
974 AssignMagicTransformer
969 AssignMagicTransformer
975 ]
970 ]
976
971
977 _default_checkers = [
972 _default_checkers = [
978 EmacsChecker,
973 EmacsChecker,
979 ShellEscapeChecker,
974 ShellEscapeChecker,
980 IPyAutocallChecker,
975 IPyAutocallChecker,
981 MultiLineMagicChecker,
976 MultiLineMagicChecker,
982 EscCharsChecker,
977 EscCharsChecker,
983 AssignmentChecker,
978 AssignmentChecker,
984 AutoMagicChecker,
979 AutoMagicChecker,
985 AliasChecker,
980 AliasChecker,
986 PythonOpsChecker,
981 PythonOpsChecker,
987 AutocallChecker
982 AutocallChecker
988 ]
983 ]
989
984
990 _default_handlers = [
985 _default_handlers = [
991 PrefilterHandler,
986 PrefilterHandler,
992 AliasHandler,
987 AliasHandler,
993 ShellEscapeHandler,
988 ShellEscapeHandler,
994 MagicHandler,
989 MagicHandler,
995 AutoHandler,
990 AutoHandler,
996 HelpHandler,
991 HelpHandler,
997 EmacsHandler
992 EmacsHandler
998 ]
993 ]
999
994
General Comments 0
You need to be logged in to leave comments. Login now