##// END OF EJS Templates
New magic: %reset_selective....
Brad Reisfeld -
Show More
@@ -1,2561 +1,2582 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 from __future__ import absolute_import
20 from __future__ import absolute_import
21
21
22 import __builtin__
22 import __builtin__
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.usage import interactive_usage, default_banner
49 from IPython.core.usage import interactive_usage, default_banner
50 import IPython.core.hooks
50 import IPython.core.hooks
51 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.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.lib.pylabtools import pylab_activate
54 from IPython.lib.pylabtools import pylab_activate
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils import pickleshare
56 from IPython.utils import pickleshare
57 from IPython.utils.doctestreload import doctest_reload
57 from IPython.utils.doctestreload import doctest_reload
58 from IPython.utils.ipstruct import Struct
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.io import Term, ask_yes_no
59 from IPython.utils.io import Term, ask_yes_no
60 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
60 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
61 from IPython.utils.process import (
61 from IPython.utils.process import (
62 abbrev_cwd,
62 abbrev_cwd,
63 getoutput,
63 getoutput,
64 getoutputerror
64 getoutputerror
65 )
65 )
66 # import IPython.utils.rlineimpl as readline
66 # import IPython.utils.rlineimpl as readline
67 from IPython.utils.strdispatch import StrDispatch
67 from IPython.utils.strdispatch import StrDispatch
68 from IPython.utils.syspathcontext import prepended_to_syspath
68 from IPython.utils.syspathcontext import prepended_to_syspath
69 from IPython.utils.terminal import toggle_set_term_title, set_term_title
69 from IPython.utils.terminal import toggle_set_term_title, set_term_title
70 from IPython.utils.warn import warn, error, fatal
70 from IPython.utils.warn import warn, error, fatal
71 from IPython.utils.traitlets import (
71 from IPython.utils.traitlets import (
72 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
72 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
73 )
73 )
74
74
75 # from IPython.utils import growl
75 # from IPython.utils import growl
76 # growl.start("IPython")
76 # growl.start("IPython")
77
77
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79 # Globals
79 # Globals
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81
81
82 # store the builtin raw_input globally, and use this always, in case user code
82 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
84 raw_input_original = raw_input
85
85
86 # compiled regexps for autoindent management
86 # compiled regexps for autoindent management
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88
88
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90 # Utilities
90 # Utilities
91 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
92
92
93 ini_spaces_re = re.compile(r'^(\s+)')
93 ini_spaces_re = re.compile(r'^(\s+)')
94
94
95
95
96 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
98
98
99 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
100 if ini_spaces:
101 return ini_spaces.end()
101 return ini_spaces.end()
102 else:
102 else:
103 return 0
103 return 0
104
104
105
105
106 def softspace(file, newvalue):
106 def softspace(file, newvalue):
107 """Copied from code.py, to remove the dependency"""
107 """Copied from code.py, to remove the dependency"""
108
108
109 oldvalue = 0
109 oldvalue = 0
110 try:
110 try:
111 oldvalue = file.softspace
111 oldvalue = file.softspace
112 except AttributeError:
112 except AttributeError:
113 pass
113 pass
114 try:
114 try:
115 file.softspace = newvalue
115 file.softspace = newvalue
116 except (AttributeError, TypeError):
116 except (AttributeError, TypeError):
117 # "attribute-less object" or "read-only attributes"
117 # "attribute-less object" or "read-only attributes"
118 pass
118 pass
119 return oldvalue
119 return oldvalue
120
120
121
121
122 def no_op(*a, **kw): pass
122 def no_op(*a, **kw): pass
123
123
124 class SpaceInInput(exceptions.Exception): pass
124 class SpaceInInput(exceptions.Exception): pass
125
125
126 class Bunch: pass
126 class Bunch: pass
127
127
128 class InputList(list):
128 class InputList(list):
129 """Class to store user input.
129 """Class to store user input.
130
130
131 It's basically a list, but slices return a string instead of a list, thus
131 It's basically a list, but slices return a string instead of a list, thus
132 allowing things like (assuming 'In' is an instance):
132 allowing things like (assuming 'In' is an instance):
133
133
134 exec In[4:7]
134 exec In[4:7]
135
135
136 or
136 or
137
137
138 exec In[5:9] + In[14] + In[21:25]"""
138 exec In[5:9] + In[14] + In[21:25]"""
139
139
140 def __getslice__(self,i,j):
140 def __getslice__(self,i,j):
141 return ''.join(list.__getslice__(self,i,j))
141 return ''.join(list.__getslice__(self,i,j))
142
142
143
143
144 class SyntaxTB(ultratb.ListTB):
144 class SyntaxTB(ultratb.ListTB):
145 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
146
146
147 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
148 ultratb.ListTB.__init__(self,color_scheme)
148 ultratb.ListTB.__init__(self,color_scheme)
149 self.last_syntax_error = None
149 self.last_syntax_error = None
150
150
151 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
152 self.last_syntax_error = value
152 self.last_syntax_error = value
153 ultratb.ListTB.__call__(self,etype,value,elist)
153 ultratb.ListTB.__call__(self,etype,value,elist)
154
154
155 def clear_err_state(self):
155 def clear_err_state(self):
156 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
157 e = self.last_syntax_error
157 e = self.last_syntax_error
158 self.last_syntax_error = None
158 self.last_syntax_error = None
159 return e
159 return e
160
160
161
161
162 def get_default_editor():
162 def get_default_editor():
163 try:
163 try:
164 ed = os.environ['EDITOR']
164 ed = os.environ['EDITOR']
165 except KeyError:
165 except KeyError:
166 if os.name == 'posix':
166 if os.name == 'posix':
167 ed = 'vi' # the only one guaranteed to be there!
167 ed = 'vi' # the only one guaranteed to be there!
168 else:
168 else:
169 ed = 'notepad' # same in Windows!
169 ed = 'notepad' # same in Windows!
170 return ed
170 return ed
171
171
172
172
173 def get_default_colors():
173 def get_default_colors():
174 if sys.platform=='darwin':
174 if sys.platform=='darwin':
175 return "LightBG"
175 return "LightBG"
176 elif os.name=='nt':
176 elif os.name=='nt':
177 return 'Linux'
177 return 'Linux'
178 else:
178 else:
179 return 'Linux'
179 return 'Linux'
180
180
181
181
182 class SeparateStr(Str):
182 class SeparateStr(Str):
183 """A Str subclass to validate separate_in, separate_out, etc.
183 """A Str subclass to validate separate_in, separate_out, etc.
184
184
185 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
185 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
186 """
186 """
187
187
188 def validate(self, obj, value):
188 def validate(self, obj, value):
189 if value == '0': value = ''
189 if value == '0': value = ''
190 value = value.replace('\\n','\n')
190 value = value.replace('\\n','\n')
191 return super(SeparateStr, self).validate(obj, value)
191 return super(SeparateStr, self).validate(obj, value)
192
192
193
193
194 #-----------------------------------------------------------------------------
194 #-----------------------------------------------------------------------------
195 # Main IPython class
195 # Main IPython class
196 #-----------------------------------------------------------------------------
196 #-----------------------------------------------------------------------------
197
197
198
198
199 class InteractiveShell(Component, Magic):
199 class InteractiveShell(Component, Magic):
200 """An enhanced, interactive shell for Python."""
200 """An enhanced, interactive shell for Python."""
201
201
202 autocall = Enum((0,1,2), default_value=1, config=True)
202 autocall = Enum((0,1,2), default_value=1, config=True)
203 autoedit_syntax = CBool(False, config=True)
203 autoedit_syntax = CBool(False, config=True)
204 autoindent = CBool(True, config=True)
204 autoindent = CBool(True, config=True)
205 automagic = CBool(True, config=True)
205 automagic = CBool(True, config=True)
206 banner = Str('')
206 banner = Str('')
207 banner1 = Str(default_banner, config=True)
207 banner1 = Str(default_banner, config=True)
208 banner2 = Str('', config=True)
208 banner2 = Str('', config=True)
209 cache_size = Int(1000, config=True)
209 cache_size = Int(1000, config=True)
210 color_info = CBool(True, config=True)
210 color_info = CBool(True, config=True)
211 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
211 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
212 default_value=get_default_colors(), config=True)
212 default_value=get_default_colors(), config=True)
213 confirm_exit = CBool(True, config=True)
213 confirm_exit = CBool(True, config=True)
214 debug = CBool(False, config=True)
214 debug = CBool(False, config=True)
215 deep_reload = CBool(False, config=True)
215 deep_reload = CBool(False, config=True)
216 # This display_banner only controls whether or not self.show_banner()
216 # This display_banner only controls whether or not self.show_banner()
217 # is called when mainloop/interact are called. The default is False
217 # is called when mainloop/interact are called. The default is False
218 # because for the terminal based application, the banner behavior
218 # because for the terminal based application, the banner behavior
219 # is controlled by Global.display_banner, which IPythonApp looks at
219 # is controlled by Global.display_banner, which IPythonApp looks at
220 # to determine if *it* should call show_banner() by hand or not.
220 # to determine if *it* should call show_banner() by hand or not.
221 display_banner = CBool(False) # This isn't configurable!
221 display_banner = CBool(False) # This isn't configurable!
222 embedded = CBool(False)
222 embedded = CBool(False)
223 embedded_active = CBool(False)
223 embedded_active = CBool(False)
224 editor = Str(get_default_editor(), config=True)
224 editor = Str(get_default_editor(), config=True)
225 filename = Str("<ipython console>")
225 filename = Str("<ipython console>")
226 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
226 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
227 logstart = CBool(False, config=True)
227 logstart = CBool(False, config=True)
228 logfile = Str('', config=True)
228 logfile = Str('', config=True)
229 logappend = Str('', config=True)
229 logappend = Str('', config=True)
230 object_info_string_level = Enum((0,1,2), default_value=0,
230 object_info_string_level = Enum((0,1,2), default_value=0,
231 config=True)
231 config=True)
232 pager = Str('less', config=True)
232 pager = Str('less', config=True)
233 pdb = CBool(False, config=True)
233 pdb = CBool(False, config=True)
234 pprint = CBool(True, config=True)
234 pprint = CBool(True, config=True)
235 profile = Str('', config=True)
235 profile = Str('', config=True)
236 prompt_in1 = Str('In [\\#]: ', config=True)
236 prompt_in1 = Str('In [\\#]: ', config=True)
237 prompt_in2 = Str(' .\\D.: ', config=True)
237 prompt_in2 = Str(' .\\D.: ', config=True)
238 prompt_out = Str('Out[\\#]: ', config=True)
238 prompt_out = Str('Out[\\#]: ', config=True)
239 prompts_pad_left = CBool(True, config=True)
239 prompts_pad_left = CBool(True, config=True)
240 quiet = CBool(False, config=True)
240 quiet = CBool(False, config=True)
241
241
242 readline_use = CBool(True, config=True)
242 readline_use = CBool(True, config=True)
243 readline_merge_completions = CBool(True, config=True)
243 readline_merge_completions = CBool(True, config=True)
244 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
244 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
245 readline_remove_delims = Str('-/~', config=True)
245 readline_remove_delims = Str('-/~', config=True)
246 readline_parse_and_bind = List([
246 readline_parse_and_bind = List([
247 'tab: complete',
247 'tab: complete',
248 '"\C-l": clear-screen',
248 '"\C-l": clear-screen',
249 'set show-all-if-ambiguous on',
249 'set show-all-if-ambiguous on',
250 '"\C-o": tab-insert',
250 '"\C-o": tab-insert',
251 '"\M-i": " "',
251 '"\M-i": " "',
252 '"\M-o": "\d\d\d\d"',
252 '"\M-o": "\d\d\d\d"',
253 '"\M-I": "\d\d\d\d"',
253 '"\M-I": "\d\d\d\d"',
254 '"\C-r": reverse-search-history',
254 '"\C-r": reverse-search-history',
255 '"\C-s": forward-search-history',
255 '"\C-s": forward-search-history',
256 '"\C-p": history-search-backward',
256 '"\C-p": history-search-backward',
257 '"\C-n": history-search-forward',
257 '"\C-n": history-search-forward',
258 '"\e[A": history-search-backward',
258 '"\e[A": history-search-backward',
259 '"\e[B": history-search-forward',
259 '"\e[B": history-search-forward',
260 '"\C-k": kill-line',
260 '"\C-k": kill-line',
261 '"\C-u": unix-line-discard',
261 '"\C-u": unix-line-discard',
262 ], allow_none=False, config=True)
262 ], allow_none=False, config=True)
263
263
264 screen_length = Int(0, config=True)
264 screen_length = Int(0, config=True)
265
265
266 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
266 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
267 separate_in = SeparateStr('\n', config=True)
267 separate_in = SeparateStr('\n', config=True)
268 separate_out = SeparateStr('', config=True)
268 separate_out = SeparateStr('', config=True)
269 separate_out2 = SeparateStr('', config=True)
269 separate_out2 = SeparateStr('', config=True)
270
270
271 system_header = Str('IPython system call: ', config=True)
271 system_header = Str('IPython system call: ', config=True)
272 system_verbose = CBool(False, config=True)
272 system_verbose = CBool(False, config=True)
273 term_title = CBool(False, config=True)
273 term_title = CBool(False, config=True)
274 wildcards_case_sensitive = CBool(True, config=True)
274 wildcards_case_sensitive = CBool(True, config=True)
275 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
275 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
276 default_value='Context', config=True)
276 default_value='Context', config=True)
277
277
278 autoexec = List(allow_none=False)
278 autoexec = List(allow_none=False)
279
279
280 # class attribute to indicate whether the class supports threads or not.
280 # class attribute to indicate whether the class supports threads or not.
281 # Subclasses with thread support should override this as needed.
281 # Subclasses with thread support should override this as needed.
282 isthreaded = False
282 isthreaded = False
283
283
284 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
284 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
285 user_ns=None, user_global_ns=None,
285 user_ns=None, user_global_ns=None,
286 banner1=None, banner2=None, display_banner=None,
286 banner1=None, banner2=None, display_banner=None,
287 custom_exceptions=((),None)):
287 custom_exceptions=((),None)):
288
288
289 # This is where traits with a config_key argument are updated
289 # This is where traits with a config_key argument are updated
290 # from the values on config.
290 # from the values on config.
291 super(InteractiveShell, self).__init__(parent, config=config)
291 super(InteractiveShell, self).__init__(parent, config=config)
292
292
293 # These are relatively independent and stateless
293 # These are relatively independent and stateless
294 self.init_ipython_dir(ipython_dir)
294 self.init_ipython_dir(ipython_dir)
295 self.init_instance_attrs()
295 self.init_instance_attrs()
296 self.init_term_title()
296 self.init_term_title()
297 self.init_usage(usage)
297 self.init_usage(usage)
298 self.init_banner(banner1, banner2, display_banner)
298 self.init_banner(banner1, banner2, display_banner)
299
299
300 # Create namespaces (user_ns, user_global_ns, etc.)
300 # Create namespaces (user_ns, user_global_ns, etc.)
301 self.init_create_namespaces(user_ns, user_global_ns)
301 self.init_create_namespaces(user_ns, user_global_ns)
302 # This has to be done after init_create_namespaces because it uses
302 # This has to be done after init_create_namespaces because it uses
303 # something in self.user_ns, but before init_sys_modules, which
303 # something in self.user_ns, but before init_sys_modules, which
304 # is the first thing to modify sys.
304 # is the first thing to modify sys.
305 self.save_sys_module_state()
305 self.save_sys_module_state()
306 self.init_sys_modules()
306 self.init_sys_modules()
307
307
308 self.init_history()
308 self.init_history()
309 self.init_encoding()
309 self.init_encoding()
310 self.init_prefilter()
310 self.init_prefilter()
311
311
312 Magic.__init__(self, self)
312 Magic.__init__(self, self)
313
313
314 self.init_syntax_highlighting()
314 self.init_syntax_highlighting()
315 self.init_hooks()
315 self.init_hooks()
316 self.init_pushd_popd_magic()
316 self.init_pushd_popd_magic()
317 self.init_traceback_handlers(custom_exceptions)
317 self.init_traceback_handlers(custom_exceptions)
318 self.init_user_ns()
318 self.init_user_ns()
319 self.init_logger()
319 self.init_logger()
320 self.init_alias()
320 self.init_alias()
321 self.init_builtins()
321 self.init_builtins()
322
322
323 # pre_config_initialization
323 # pre_config_initialization
324 self.init_shadow_hist()
324 self.init_shadow_hist()
325
325
326 # The next section should contain averything that was in ipmaker.
326 # The next section should contain averything that was in ipmaker.
327 self.init_logstart()
327 self.init_logstart()
328
328
329 # The following was in post_config_initialization
329 # The following was in post_config_initialization
330 self.init_inspector()
330 self.init_inspector()
331 self.init_readline()
331 self.init_readline()
332 self.init_prompts()
332 self.init_prompts()
333 self.init_displayhook()
333 self.init_displayhook()
334 self.init_reload_doctest()
334 self.init_reload_doctest()
335 self.init_magics()
335 self.init_magics()
336 self.init_pdb()
336 self.init_pdb()
337 self.hooks.late_startup_hook()
337 self.hooks.late_startup_hook()
338
338
339 def get_ipython(self):
339 def get_ipython(self):
340 """Return the currently running IPython instance."""
340 """Return the currently running IPython instance."""
341 return self
341 return self
342
342
343 #-------------------------------------------------------------------------
343 #-------------------------------------------------------------------------
344 # Trait changed handlers
344 # Trait changed handlers
345 #-------------------------------------------------------------------------
345 #-------------------------------------------------------------------------
346
346
347 def _banner1_changed(self):
347 def _banner1_changed(self):
348 self.compute_banner()
348 self.compute_banner()
349
349
350 def _banner2_changed(self):
350 def _banner2_changed(self):
351 self.compute_banner()
351 self.compute_banner()
352
352
353 def _ipython_dir_changed(self, name, new):
353 def _ipython_dir_changed(self, name, new):
354 if not os.path.isdir(new):
354 if not os.path.isdir(new):
355 os.makedirs(new, mode = 0777)
355 os.makedirs(new, mode = 0777)
356 if not os.path.isdir(self.ipython_extension_dir):
356 if not os.path.isdir(self.ipython_extension_dir):
357 os.makedirs(self.ipython_extension_dir, mode = 0777)
357 os.makedirs(self.ipython_extension_dir, mode = 0777)
358
358
359 @property
359 @property
360 def ipython_extension_dir(self):
360 def ipython_extension_dir(self):
361 return os.path.join(self.ipython_dir, 'extensions')
361 return os.path.join(self.ipython_dir, 'extensions')
362
362
363 @property
363 @property
364 def usable_screen_length(self):
364 def usable_screen_length(self):
365 if self.screen_length == 0:
365 if self.screen_length == 0:
366 return 0
366 return 0
367 else:
367 else:
368 num_lines_bot = self.separate_in.count('\n')+1
368 num_lines_bot = self.separate_in.count('\n')+1
369 return self.screen_length - num_lines_bot
369 return self.screen_length - num_lines_bot
370
370
371 def _term_title_changed(self, name, new_value):
371 def _term_title_changed(self, name, new_value):
372 self.init_term_title()
372 self.init_term_title()
373
373
374 def set_autoindent(self,value=None):
374 def set_autoindent(self,value=None):
375 """Set the autoindent flag, checking for readline support.
375 """Set the autoindent flag, checking for readline support.
376
376
377 If called with no arguments, it acts as a toggle."""
377 If called with no arguments, it acts as a toggle."""
378
378
379 if not self.has_readline:
379 if not self.has_readline:
380 if os.name == 'posix':
380 if os.name == 'posix':
381 warn("The auto-indent feature requires the readline library")
381 warn("The auto-indent feature requires the readline library")
382 self.autoindent = 0
382 self.autoindent = 0
383 return
383 return
384 if value is None:
384 if value is None:
385 self.autoindent = not self.autoindent
385 self.autoindent = not self.autoindent
386 else:
386 else:
387 self.autoindent = value
387 self.autoindent = value
388
388
389 #-------------------------------------------------------------------------
389 #-------------------------------------------------------------------------
390 # init_* methods called by __init__
390 # init_* methods called by __init__
391 #-------------------------------------------------------------------------
391 #-------------------------------------------------------------------------
392
392
393 def init_ipython_dir(self, ipython_dir):
393 def init_ipython_dir(self, ipython_dir):
394 if ipython_dir is not None:
394 if ipython_dir is not None:
395 self.ipython_dir = ipython_dir
395 self.ipython_dir = ipython_dir
396 self.config.Global.ipython_dir = self.ipython_dir
396 self.config.Global.ipython_dir = self.ipython_dir
397 return
397 return
398
398
399 if hasattr(self.config.Global, 'ipython_dir'):
399 if hasattr(self.config.Global, 'ipython_dir'):
400 self.ipython_dir = self.config.Global.ipython_dir
400 self.ipython_dir = self.config.Global.ipython_dir
401 else:
401 else:
402 self.ipython_dir = get_ipython_dir()
402 self.ipython_dir = get_ipython_dir()
403
403
404 # All children can just read this
404 # All children can just read this
405 self.config.Global.ipython_dir = self.ipython_dir
405 self.config.Global.ipython_dir = self.ipython_dir
406
406
407 def init_instance_attrs(self):
407 def init_instance_attrs(self):
408 self.jobs = BackgroundJobManager()
408 self.jobs = BackgroundJobManager()
409 self.more = False
409 self.more = False
410
410
411 # command compiler
411 # command compiler
412 self.compile = codeop.CommandCompiler()
412 self.compile = codeop.CommandCompiler()
413
413
414 # User input buffer
414 # User input buffer
415 self.buffer = []
415 self.buffer = []
416
416
417 # Make an empty namespace, which extension writers can rely on both
417 # Make an empty namespace, which extension writers can rely on both
418 # existing and NEVER being used by ipython itself. This gives them a
418 # existing and NEVER being used by ipython itself. This gives them a
419 # convenient location for storing additional information and state
419 # convenient location for storing additional information and state
420 # their extensions may require, without fear of collisions with other
420 # their extensions may require, without fear of collisions with other
421 # ipython names that may develop later.
421 # ipython names that may develop later.
422 self.meta = Struct()
422 self.meta = Struct()
423
423
424 # Object variable to store code object waiting execution. This is
424 # Object variable to store code object waiting execution. This is
425 # used mainly by the multithreaded shells, but it can come in handy in
425 # used mainly by the multithreaded shells, but it can come in handy in
426 # other situations. No need to use a Queue here, since it's a single
426 # other situations. No need to use a Queue here, since it's a single
427 # item which gets cleared once run.
427 # item which gets cleared once run.
428 self.code_to_run = None
428 self.code_to_run = None
429
429
430 # Flag to mark unconditional exit
430 # Flag to mark unconditional exit
431 self.exit_now = False
431 self.exit_now = False
432
432
433 # Temporary files used for various purposes. Deleted at exit.
433 # Temporary files used for various purposes. Deleted at exit.
434 self.tempfiles = []
434 self.tempfiles = []
435
435
436 # Keep track of readline usage (later set by init_readline)
436 # Keep track of readline usage (later set by init_readline)
437 self.has_readline = False
437 self.has_readline = False
438
438
439 # keep track of where we started running (mainly for crash post-mortem)
439 # keep track of where we started running (mainly for crash post-mortem)
440 # This is not being used anywhere currently.
440 # This is not being used anywhere currently.
441 self.starting_dir = os.getcwd()
441 self.starting_dir = os.getcwd()
442
442
443 # Indentation management
443 # Indentation management
444 self.indent_current_nsp = 0
444 self.indent_current_nsp = 0
445
445
446 def init_term_title(self):
446 def init_term_title(self):
447 # Enable or disable the terminal title.
447 # Enable or disable the terminal title.
448 if self.term_title:
448 if self.term_title:
449 toggle_set_term_title(True)
449 toggle_set_term_title(True)
450 set_term_title('IPython: ' + abbrev_cwd())
450 set_term_title('IPython: ' + abbrev_cwd())
451 else:
451 else:
452 toggle_set_term_title(False)
452 toggle_set_term_title(False)
453
453
454 def init_usage(self, usage=None):
454 def init_usage(self, usage=None):
455 if usage is None:
455 if usage is None:
456 self.usage = interactive_usage
456 self.usage = interactive_usage
457 else:
457 else:
458 self.usage = usage
458 self.usage = usage
459
459
460 def init_encoding(self):
460 def init_encoding(self):
461 # Get system encoding at startup time. Certain terminals (like Emacs
461 # Get system encoding at startup time. Certain terminals (like Emacs
462 # under Win32 have it set to None, and we need to have a known valid
462 # under Win32 have it set to None, and we need to have a known valid
463 # encoding to use in the raw_input() method
463 # encoding to use in the raw_input() method
464 try:
464 try:
465 self.stdin_encoding = sys.stdin.encoding or 'ascii'
465 self.stdin_encoding = sys.stdin.encoding or 'ascii'
466 except AttributeError:
466 except AttributeError:
467 self.stdin_encoding = 'ascii'
467 self.stdin_encoding = 'ascii'
468
468
469 def init_syntax_highlighting(self):
469 def init_syntax_highlighting(self):
470 # Python source parser/formatter for syntax highlighting
470 # Python source parser/formatter for syntax highlighting
471 pyformat = PyColorize.Parser().format
471 pyformat = PyColorize.Parser().format
472 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
472 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
473
473
474 def init_pushd_popd_magic(self):
474 def init_pushd_popd_magic(self):
475 # for pushd/popd management
475 # for pushd/popd management
476 try:
476 try:
477 self.home_dir = get_home_dir()
477 self.home_dir = get_home_dir()
478 except HomeDirError, msg:
478 except HomeDirError, msg:
479 fatal(msg)
479 fatal(msg)
480
480
481 self.dir_stack = []
481 self.dir_stack = []
482
482
483 def init_logger(self):
483 def init_logger(self):
484 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
484 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
485 # local shortcut, this is used a LOT
485 # local shortcut, this is used a LOT
486 self.log = self.logger.log
486 self.log = self.logger.log
487
487
488 def init_logstart(self):
488 def init_logstart(self):
489 if self.logappend:
489 if self.logappend:
490 self.magic_logstart(self.logappend + ' append')
490 self.magic_logstart(self.logappend + ' append')
491 elif self.logfile:
491 elif self.logfile:
492 self.magic_logstart(self.logfile)
492 self.magic_logstart(self.logfile)
493 elif self.logstart:
493 elif self.logstart:
494 self.magic_logstart()
494 self.magic_logstart()
495
495
496 def init_builtins(self):
496 def init_builtins(self):
497 self.builtin_trap = BuiltinTrap(self)
497 self.builtin_trap = BuiltinTrap(self)
498
498
499 def init_inspector(self):
499 def init_inspector(self):
500 # Object inspector
500 # Object inspector
501 self.inspector = oinspect.Inspector(oinspect.InspectColors,
501 self.inspector = oinspect.Inspector(oinspect.InspectColors,
502 PyColorize.ANSICodeColors,
502 PyColorize.ANSICodeColors,
503 'NoColor',
503 'NoColor',
504 self.object_info_string_level)
504 self.object_info_string_level)
505
505
506 def init_prompts(self):
506 def init_prompts(self):
507 # Initialize cache, set in/out prompts and printing system
507 # Initialize cache, set in/out prompts and printing system
508 self.outputcache = CachedOutput(self,
508 self.outputcache = CachedOutput(self,
509 self.cache_size,
509 self.cache_size,
510 self.pprint,
510 self.pprint,
511 input_sep = self.separate_in,
511 input_sep = self.separate_in,
512 output_sep = self.separate_out,
512 output_sep = self.separate_out,
513 output_sep2 = self.separate_out2,
513 output_sep2 = self.separate_out2,
514 ps1 = self.prompt_in1,
514 ps1 = self.prompt_in1,
515 ps2 = self.prompt_in2,
515 ps2 = self.prompt_in2,
516 ps_out = self.prompt_out,
516 ps_out = self.prompt_out,
517 pad_left = self.prompts_pad_left)
517 pad_left = self.prompts_pad_left)
518
518
519 # user may have over-ridden the default print hook:
519 # user may have over-ridden the default print hook:
520 try:
520 try:
521 self.outputcache.__class__.display = self.hooks.display
521 self.outputcache.__class__.display = self.hooks.display
522 except AttributeError:
522 except AttributeError:
523 pass
523 pass
524
524
525 def init_displayhook(self):
525 def init_displayhook(self):
526 self.display_trap = DisplayTrap(self, self.outputcache)
526 self.display_trap = DisplayTrap(self, self.outputcache)
527
527
528 def init_reload_doctest(self):
528 def init_reload_doctest(self):
529 # Do a proper resetting of doctest, including the necessary displayhook
529 # Do a proper resetting of doctest, including the necessary displayhook
530 # monkeypatching
530 # monkeypatching
531 try:
531 try:
532 doctest_reload()
532 doctest_reload()
533 except ImportError:
533 except ImportError:
534 warn("doctest module does not exist.")
534 warn("doctest module does not exist.")
535
535
536 #-------------------------------------------------------------------------
536 #-------------------------------------------------------------------------
537 # Things related to the banner
537 # Things related to the banner
538 #-------------------------------------------------------------------------
538 #-------------------------------------------------------------------------
539
539
540 def init_banner(self, banner1, banner2, display_banner):
540 def init_banner(self, banner1, banner2, display_banner):
541 if banner1 is not None:
541 if banner1 is not None:
542 self.banner1 = banner1
542 self.banner1 = banner1
543 if banner2 is not None:
543 if banner2 is not None:
544 self.banner2 = banner2
544 self.banner2 = banner2
545 if display_banner is not None:
545 if display_banner is not None:
546 self.display_banner = display_banner
546 self.display_banner = display_banner
547 self.compute_banner()
547 self.compute_banner()
548
548
549 def show_banner(self, banner=None):
549 def show_banner(self, banner=None):
550 if banner is None:
550 if banner is None:
551 banner = self.banner
551 banner = self.banner
552 self.write(banner)
552 self.write(banner)
553
553
554 def compute_banner(self):
554 def compute_banner(self):
555 self.banner = self.banner1 + '\n'
555 self.banner = self.banner1 + '\n'
556 if self.profile:
556 if self.profile:
557 self.banner += '\nIPython profile: %s\n' % self.profile
557 self.banner += '\nIPython profile: %s\n' % self.profile
558 if self.banner2:
558 if self.banner2:
559 self.banner += '\n' + self.banner2 + '\n'
559 self.banner += '\n' + self.banner2 + '\n'
560
560
561 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
562 # Things related to injections into the sys module
562 # Things related to injections into the sys module
563 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
564
564
565 def save_sys_module_state(self):
565 def save_sys_module_state(self):
566 """Save the state of hooks in the sys module.
566 """Save the state of hooks in the sys module.
567
567
568 This has to be called after self.user_ns is created.
568 This has to be called after self.user_ns is created.
569 """
569 """
570 self._orig_sys_module_state = {}
570 self._orig_sys_module_state = {}
571 self._orig_sys_module_state['stdin'] = sys.stdin
571 self._orig_sys_module_state['stdin'] = sys.stdin
572 self._orig_sys_module_state['stdout'] = sys.stdout
572 self._orig_sys_module_state['stdout'] = sys.stdout
573 self._orig_sys_module_state['stderr'] = sys.stderr
573 self._orig_sys_module_state['stderr'] = sys.stderr
574 self._orig_sys_module_state['excepthook'] = sys.excepthook
574 self._orig_sys_module_state['excepthook'] = sys.excepthook
575 try:
575 try:
576 self._orig_sys_modules_main_name = self.user_ns['__name__']
576 self._orig_sys_modules_main_name = self.user_ns['__name__']
577 except KeyError:
577 except KeyError:
578 pass
578 pass
579
579
580 def restore_sys_module_state(self):
580 def restore_sys_module_state(self):
581 """Restore the state of the sys module."""
581 """Restore the state of the sys module."""
582 try:
582 try:
583 for k, v in self._orig_sys_module_state.items():
583 for k, v in self._orig_sys_module_state.items():
584 setattr(sys, k, v)
584 setattr(sys, k, v)
585 except AttributeError:
585 except AttributeError:
586 pass
586 pass
587 try:
587 try:
588 delattr(sys, 'ipcompleter')
588 delattr(sys, 'ipcompleter')
589 except AttributeError:
589 except AttributeError:
590 pass
590 pass
591 # Reset what what done in self.init_sys_modules
591 # Reset what what done in self.init_sys_modules
592 try:
592 try:
593 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
593 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
594 except (AttributeError, KeyError):
594 except (AttributeError, KeyError):
595 pass
595 pass
596
596
597 #-------------------------------------------------------------------------
597 #-------------------------------------------------------------------------
598 # Things related to hooks
598 # Things related to hooks
599 #-------------------------------------------------------------------------
599 #-------------------------------------------------------------------------
600
600
601 def init_hooks(self):
601 def init_hooks(self):
602 # hooks holds pointers used for user-side customizations
602 # hooks holds pointers used for user-side customizations
603 self.hooks = Struct()
603 self.hooks = Struct()
604
604
605 self.strdispatchers = {}
605 self.strdispatchers = {}
606
606
607 # Set all default hooks, defined in the IPython.hooks module.
607 # Set all default hooks, defined in the IPython.hooks module.
608 hooks = IPython.core.hooks
608 hooks = IPython.core.hooks
609 for hook_name in hooks.__all__:
609 for hook_name in hooks.__all__:
610 # default hooks have priority 100, i.e. low; user hooks should have
610 # default hooks have priority 100, i.e. low; user hooks should have
611 # 0-100 priority
611 # 0-100 priority
612 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
612 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
613
613
614 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
614 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
615 """set_hook(name,hook) -> sets an internal IPython hook.
615 """set_hook(name,hook) -> sets an internal IPython hook.
616
616
617 IPython exposes some of its internal API as user-modifiable hooks. By
617 IPython exposes some of its internal API as user-modifiable hooks. By
618 adding your function to one of these hooks, you can modify IPython's
618 adding your function to one of these hooks, you can modify IPython's
619 behavior to call at runtime your own routines."""
619 behavior to call at runtime your own routines."""
620
620
621 # At some point in the future, this should validate the hook before it
621 # At some point in the future, this should validate the hook before it
622 # accepts it. Probably at least check that the hook takes the number
622 # accepts it. Probably at least check that the hook takes the number
623 # of args it's supposed to.
623 # of args it's supposed to.
624
624
625 f = new.instancemethod(hook,self,self.__class__)
625 f = new.instancemethod(hook,self,self.__class__)
626
626
627 # check if the hook is for strdispatcher first
627 # check if the hook is for strdispatcher first
628 if str_key is not None:
628 if str_key is not None:
629 sdp = self.strdispatchers.get(name, StrDispatch())
629 sdp = self.strdispatchers.get(name, StrDispatch())
630 sdp.add_s(str_key, f, priority )
630 sdp.add_s(str_key, f, priority )
631 self.strdispatchers[name] = sdp
631 self.strdispatchers[name] = sdp
632 return
632 return
633 if re_key is not None:
633 if re_key is not None:
634 sdp = self.strdispatchers.get(name, StrDispatch())
634 sdp = self.strdispatchers.get(name, StrDispatch())
635 sdp.add_re(re.compile(re_key), f, priority )
635 sdp.add_re(re.compile(re_key), f, priority )
636 self.strdispatchers[name] = sdp
636 self.strdispatchers[name] = sdp
637 return
637 return
638
638
639 dp = getattr(self.hooks, name, None)
639 dp = getattr(self.hooks, name, None)
640 if name not in IPython.core.hooks.__all__:
640 if name not in IPython.core.hooks.__all__:
641 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
641 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
642 if not dp:
642 if not dp:
643 dp = IPython.core.hooks.CommandChainDispatcher()
643 dp = IPython.core.hooks.CommandChainDispatcher()
644
644
645 try:
645 try:
646 dp.add(f,priority)
646 dp.add(f,priority)
647 except AttributeError:
647 except AttributeError:
648 # it was not commandchain, plain old func - replace
648 # it was not commandchain, plain old func - replace
649 dp = f
649 dp = f
650
650
651 setattr(self.hooks,name, dp)
651 setattr(self.hooks,name, dp)
652
652
653 #-------------------------------------------------------------------------
653 #-------------------------------------------------------------------------
654 # Things related to the "main" module
654 # Things related to the "main" module
655 #-------------------------------------------------------------------------
655 #-------------------------------------------------------------------------
656
656
657 def new_main_mod(self,ns=None):
657 def new_main_mod(self,ns=None):
658 """Return a new 'main' module object for user code execution.
658 """Return a new 'main' module object for user code execution.
659 """
659 """
660 main_mod = self._user_main_module
660 main_mod = self._user_main_module
661 init_fakemod_dict(main_mod,ns)
661 init_fakemod_dict(main_mod,ns)
662 return main_mod
662 return main_mod
663
663
664 def cache_main_mod(self,ns,fname):
664 def cache_main_mod(self,ns,fname):
665 """Cache a main module's namespace.
665 """Cache a main module's namespace.
666
666
667 When scripts are executed via %run, we must keep a reference to the
667 When scripts are executed via %run, we must keep a reference to the
668 namespace of their __main__ module (a FakeModule instance) around so
668 namespace of their __main__ module (a FakeModule instance) around so
669 that Python doesn't clear it, rendering objects defined therein
669 that Python doesn't clear it, rendering objects defined therein
670 useless.
670 useless.
671
671
672 This method keeps said reference in a private dict, keyed by the
672 This method keeps said reference in a private dict, keyed by the
673 absolute path of the module object (which corresponds to the script
673 absolute path of the module object (which corresponds to the script
674 path). This way, for multiple executions of the same script we only
674 path). This way, for multiple executions of the same script we only
675 keep one copy of the namespace (the last one), thus preventing memory
675 keep one copy of the namespace (the last one), thus preventing memory
676 leaks from old references while allowing the objects from the last
676 leaks from old references while allowing the objects from the last
677 execution to be accessible.
677 execution to be accessible.
678
678
679 Note: we can not allow the actual FakeModule instances to be deleted,
679 Note: we can not allow the actual FakeModule instances to be deleted,
680 because of how Python tears down modules (it hard-sets all their
680 because of how Python tears down modules (it hard-sets all their
681 references to None without regard for reference counts). This method
681 references to None without regard for reference counts). This method
682 must therefore make a *copy* of the given namespace, to allow the
682 must therefore make a *copy* of the given namespace, to allow the
683 original module's __dict__ to be cleared and reused.
683 original module's __dict__ to be cleared and reused.
684
684
685
685
686 Parameters
686 Parameters
687 ----------
687 ----------
688 ns : a namespace (a dict, typically)
688 ns : a namespace (a dict, typically)
689
689
690 fname : str
690 fname : str
691 Filename associated with the namespace.
691 Filename associated with the namespace.
692
692
693 Examples
693 Examples
694 --------
694 --------
695
695
696 In [10]: import IPython
696 In [10]: import IPython
697
697
698 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
698 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
699
699
700 In [12]: IPython.__file__ in _ip._main_ns_cache
700 In [12]: IPython.__file__ in _ip._main_ns_cache
701 Out[12]: True
701 Out[12]: True
702 """
702 """
703 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
703 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
704
704
705 def clear_main_mod_cache(self):
705 def clear_main_mod_cache(self):
706 """Clear the cache of main modules.
706 """Clear the cache of main modules.
707
707
708 Mainly for use by utilities like %reset.
708 Mainly for use by utilities like %reset.
709
709
710 Examples
710 Examples
711 --------
711 --------
712
712
713 In [15]: import IPython
713 In [15]: import IPython
714
714
715 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
715 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
716
716
717 In [17]: len(_ip._main_ns_cache) > 0
717 In [17]: len(_ip._main_ns_cache) > 0
718 Out[17]: True
718 Out[17]: True
719
719
720 In [18]: _ip.clear_main_mod_cache()
720 In [18]: _ip.clear_main_mod_cache()
721
721
722 In [19]: len(_ip._main_ns_cache) == 0
722 In [19]: len(_ip._main_ns_cache) == 0
723 Out[19]: True
723 Out[19]: True
724 """
724 """
725 self._main_ns_cache.clear()
725 self._main_ns_cache.clear()
726
726
727 #-------------------------------------------------------------------------
727 #-------------------------------------------------------------------------
728 # Things related to debugging
728 # Things related to debugging
729 #-------------------------------------------------------------------------
729 #-------------------------------------------------------------------------
730
730
731 def init_pdb(self):
731 def init_pdb(self):
732 # Set calling of pdb on exceptions
732 # Set calling of pdb on exceptions
733 # self.call_pdb is a property
733 # self.call_pdb is a property
734 self.call_pdb = self.pdb
734 self.call_pdb = self.pdb
735
735
736 def _get_call_pdb(self):
736 def _get_call_pdb(self):
737 return self._call_pdb
737 return self._call_pdb
738
738
739 def _set_call_pdb(self,val):
739 def _set_call_pdb(self,val):
740
740
741 if val not in (0,1,False,True):
741 if val not in (0,1,False,True):
742 raise ValueError,'new call_pdb value must be boolean'
742 raise ValueError,'new call_pdb value must be boolean'
743
743
744 # store value in instance
744 # store value in instance
745 self._call_pdb = val
745 self._call_pdb = val
746
746
747 # notify the actual exception handlers
747 # notify the actual exception handlers
748 self.InteractiveTB.call_pdb = val
748 self.InteractiveTB.call_pdb = val
749 if self.isthreaded:
749 if self.isthreaded:
750 try:
750 try:
751 self.sys_excepthook.call_pdb = val
751 self.sys_excepthook.call_pdb = val
752 except:
752 except:
753 warn('Failed to activate pdb for threaded exception handler')
753 warn('Failed to activate pdb for threaded exception handler')
754
754
755 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
755 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
756 'Control auto-activation of pdb at exceptions')
756 'Control auto-activation of pdb at exceptions')
757
757
758 def debugger(self,force=False):
758 def debugger(self,force=False):
759 """Call the pydb/pdb debugger.
759 """Call the pydb/pdb debugger.
760
760
761 Keywords:
761 Keywords:
762
762
763 - force(False): by default, this routine checks the instance call_pdb
763 - force(False): by default, this routine checks the instance call_pdb
764 flag and does not actually invoke the debugger if the flag is false.
764 flag and does not actually invoke the debugger if the flag is false.
765 The 'force' option forces the debugger to activate even if the flag
765 The 'force' option forces the debugger to activate even if the flag
766 is false.
766 is false.
767 """
767 """
768
768
769 if not (force or self.call_pdb):
769 if not (force or self.call_pdb):
770 return
770 return
771
771
772 if not hasattr(sys,'last_traceback'):
772 if not hasattr(sys,'last_traceback'):
773 error('No traceback has been produced, nothing to debug.')
773 error('No traceback has been produced, nothing to debug.')
774 return
774 return
775
775
776 # use pydb if available
776 # use pydb if available
777 if debugger.has_pydb:
777 if debugger.has_pydb:
778 from pydb import pm
778 from pydb import pm
779 else:
779 else:
780 # fallback to our internal debugger
780 # fallback to our internal debugger
781 pm = lambda : self.InteractiveTB.debugger(force=True)
781 pm = lambda : self.InteractiveTB.debugger(force=True)
782 self.history_saving_wrapper(pm)()
782 self.history_saving_wrapper(pm)()
783
783
784 #-------------------------------------------------------------------------
784 #-------------------------------------------------------------------------
785 # Things related to IPython's various namespaces
785 # Things related to IPython's various namespaces
786 #-------------------------------------------------------------------------
786 #-------------------------------------------------------------------------
787
787
788 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
788 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
789 # Create the namespace where the user will operate. user_ns is
789 # Create the namespace where the user will operate. user_ns is
790 # normally the only one used, and it is passed to the exec calls as
790 # normally the only one used, and it is passed to the exec calls as
791 # the locals argument. But we do carry a user_global_ns namespace
791 # the locals argument. But we do carry a user_global_ns namespace
792 # given as the exec 'globals' argument, This is useful in embedding
792 # given as the exec 'globals' argument, This is useful in embedding
793 # situations where the ipython shell opens in a context where the
793 # situations where the ipython shell opens in a context where the
794 # distinction between locals and globals is meaningful. For
794 # distinction between locals and globals is meaningful. For
795 # non-embedded contexts, it is just the same object as the user_ns dict.
795 # non-embedded contexts, it is just the same object as the user_ns dict.
796
796
797 # FIXME. For some strange reason, __builtins__ is showing up at user
797 # FIXME. For some strange reason, __builtins__ is showing up at user
798 # level as a dict instead of a module. This is a manual fix, but I
798 # level as a dict instead of a module. This is a manual fix, but I
799 # should really track down where the problem is coming from. Alex
799 # should really track down where the problem is coming from. Alex
800 # Schmolck reported this problem first.
800 # Schmolck reported this problem first.
801
801
802 # A useful post by Alex Martelli on this topic:
802 # A useful post by Alex Martelli on this topic:
803 # Re: inconsistent value from __builtins__
803 # Re: inconsistent value from __builtins__
804 # Von: Alex Martelli <aleaxit@yahoo.com>
804 # Von: Alex Martelli <aleaxit@yahoo.com>
805 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
805 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
806 # Gruppen: comp.lang.python
806 # Gruppen: comp.lang.python
807
807
808 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
808 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
809 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
809 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
810 # > <type 'dict'>
810 # > <type 'dict'>
811 # > >>> print type(__builtins__)
811 # > >>> print type(__builtins__)
812 # > <type 'module'>
812 # > <type 'module'>
813 # > Is this difference in return value intentional?
813 # > Is this difference in return value intentional?
814
814
815 # Well, it's documented that '__builtins__' can be either a dictionary
815 # Well, it's documented that '__builtins__' can be either a dictionary
816 # or a module, and it's been that way for a long time. Whether it's
816 # or a module, and it's been that way for a long time. Whether it's
817 # intentional (or sensible), I don't know. In any case, the idea is
817 # intentional (or sensible), I don't know. In any case, the idea is
818 # that if you need to access the built-in namespace directly, you
818 # that if you need to access the built-in namespace directly, you
819 # should start with "import __builtin__" (note, no 's') which will
819 # should start with "import __builtin__" (note, no 's') which will
820 # definitely give you a module. Yeah, it's somewhat confusing:-(.
820 # definitely give you a module. Yeah, it's somewhat confusing:-(.
821
821
822 # These routines return properly built dicts as needed by the rest of
822 # These routines return properly built dicts as needed by the rest of
823 # the code, and can also be used by extension writers to generate
823 # the code, and can also be used by extension writers to generate
824 # properly initialized namespaces.
824 # properly initialized namespaces.
825 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
825 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
826
826
827 # Assign namespaces
827 # Assign namespaces
828 # This is the namespace where all normal user variables live
828 # This is the namespace where all normal user variables live
829 self.user_ns = user_ns
829 self.user_ns = user_ns
830 self.user_global_ns = user_global_ns
830 self.user_global_ns = user_global_ns
831
831
832 # An auxiliary namespace that checks what parts of the user_ns were
832 # An auxiliary namespace that checks what parts of the user_ns were
833 # loaded at startup, so we can list later only variables defined in
833 # loaded at startup, so we can list later only variables defined in
834 # actual interactive use. Since it is always a subset of user_ns, it
834 # actual interactive use. Since it is always a subset of user_ns, it
835 # doesn't need to be separately tracked in the ns_table.
835 # doesn't need to be separately tracked in the ns_table.
836 self.user_ns_hidden = {}
836 self.user_ns_hidden = {}
837
837
838 # A namespace to keep track of internal data structures to prevent
838 # A namespace to keep track of internal data structures to prevent
839 # them from cluttering user-visible stuff. Will be updated later
839 # them from cluttering user-visible stuff. Will be updated later
840 self.internal_ns = {}
840 self.internal_ns = {}
841
841
842 # Now that FakeModule produces a real module, we've run into a nasty
842 # Now that FakeModule produces a real module, we've run into a nasty
843 # problem: after script execution (via %run), the module where the user
843 # problem: after script execution (via %run), the module where the user
844 # code ran is deleted. Now that this object is a true module (needed
844 # code ran is deleted. Now that this object is a true module (needed
845 # so docetst and other tools work correctly), the Python module
845 # so docetst and other tools work correctly), the Python module
846 # teardown mechanism runs over it, and sets to None every variable
846 # teardown mechanism runs over it, and sets to None every variable
847 # present in that module. Top-level references to objects from the
847 # present in that module. Top-level references to objects from the
848 # script survive, because the user_ns is updated with them. However,
848 # script survive, because the user_ns is updated with them. However,
849 # calling functions defined in the script that use other things from
849 # calling functions defined in the script that use other things from
850 # the script will fail, because the function's closure had references
850 # the script will fail, because the function's closure had references
851 # to the original objects, which are now all None. So we must protect
851 # to the original objects, which are now all None. So we must protect
852 # these modules from deletion by keeping a cache.
852 # these modules from deletion by keeping a cache.
853 #
853 #
854 # To avoid keeping stale modules around (we only need the one from the
854 # To avoid keeping stale modules around (we only need the one from the
855 # last run), we use a dict keyed with the full path to the script, so
855 # last run), we use a dict keyed with the full path to the script, so
856 # only the last version of the module is held in the cache. Note,
856 # only the last version of the module is held in the cache. Note,
857 # however, that we must cache the module *namespace contents* (their
857 # however, that we must cache the module *namespace contents* (their
858 # __dict__). Because if we try to cache the actual modules, old ones
858 # __dict__). Because if we try to cache the actual modules, old ones
859 # (uncached) could be destroyed while still holding references (such as
859 # (uncached) could be destroyed while still holding references (such as
860 # those held by GUI objects that tend to be long-lived)>
860 # those held by GUI objects that tend to be long-lived)>
861 #
861 #
862 # The %reset command will flush this cache. See the cache_main_mod()
862 # The %reset command will flush this cache. See the cache_main_mod()
863 # and clear_main_mod_cache() methods for details on use.
863 # and clear_main_mod_cache() methods for details on use.
864
864
865 # This is the cache used for 'main' namespaces
865 # This is the cache used for 'main' namespaces
866 self._main_ns_cache = {}
866 self._main_ns_cache = {}
867 # And this is the single instance of FakeModule whose __dict__ we keep
867 # And this is the single instance of FakeModule whose __dict__ we keep
868 # copying and clearing for reuse on each %run
868 # copying and clearing for reuse on each %run
869 self._user_main_module = FakeModule()
869 self._user_main_module = FakeModule()
870
870
871 # A table holding all the namespaces IPython deals with, so that
871 # A table holding all the namespaces IPython deals with, so that
872 # introspection facilities can search easily.
872 # introspection facilities can search easily.
873 self.ns_table = {'user':user_ns,
873 self.ns_table = {'user':user_ns,
874 'user_global':user_global_ns,
874 'user_global':user_global_ns,
875 'internal':self.internal_ns,
875 'internal':self.internal_ns,
876 'builtin':__builtin__.__dict__
876 'builtin':__builtin__.__dict__
877 }
877 }
878
878
879 # Similarly, track all namespaces where references can be held and that
879 # Similarly, track all namespaces where references can be held and that
880 # we can safely clear (so it can NOT include builtin). This one can be
880 # we can safely clear (so it can NOT include builtin). This one can be
881 # a simple list.
881 # a simple list.
882 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
882 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
883 self.internal_ns, self._main_ns_cache ]
883 self.internal_ns, self._main_ns_cache ]
884
884
885 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
885 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
886 """Return a valid local and global user interactive namespaces.
886 """Return a valid local and global user interactive namespaces.
887
887
888 This builds a dict with the minimal information needed to operate as a
888 This builds a dict with the minimal information needed to operate as a
889 valid IPython user namespace, which you can pass to the various
889 valid IPython user namespace, which you can pass to the various
890 embedding classes in ipython. The default implementation returns the
890 embedding classes in ipython. The default implementation returns the
891 same dict for both the locals and the globals to allow functions to
891 same dict for both the locals and the globals to allow functions to
892 refer to variables in the namespace. Customized implementations can
892 refer to variables in the namespace. Customized implementations can
893 return different dicts. The locals dictionary can actually be anything
893 return different dicts. The locals dictionary can actually be anything
894 following the basic mapping protocol of a dict, but the globals dict
894 following the basic mapping protocol of a dict, but the globals dict
895 must be a true dict, not even a subclass. It is recommended that any
895 must be a true dict, not even a subclass. It is recommended that any
896 custom object for the locals namespace synchronize with the globals
896 custom object for the locals namespace synchronize with the globals
897 dict somehow.
897 dict somehow.
898
898
899 Raises TypeError if the provided globals namespace is not a true dict.
899 Raises TypeError if the provided globals namespace is not a true dict.
900
900
901 Parameters
901 Parameters
902 ----------
902 ----------
903 user_ns : dict-like, optional
903 user_ns : dict-like, optional
904 The current user namespace. The items in this namespace should
904 The current user namespace. The items in this namespace should
905 be included in the output. If None, an appropriate blank
905 be included in the output. If None, an appropriate blank
906 namespace should be created.
906 namespace should be created.
907 user_global_ns : dict, optional
907 user_global_ns : dict, optional
908 The current user global namespace. The items in this namespace
908 The current user global namespace. The items in this namespace
909 should be included in the output. If None, an appropriate
909 should be included in the output. If None, an appropriate
910 blank namespace should be created.
910 blank namespace should be created.
911
911
912 Returns
912 Returns
913 -------
913 -------
914 A pair of dictionary-like object to be used as the local namespace
914 A pair of dictionary-like object to be used as the local namespace
915 of the interpreter and a dict to be used as the global namespace.
915 of the interpreter and a dict to be used as the global namespace.
916 """
916 """
917
917
918
918
919 # We must ensure that __builtin__ (without the final 's') is always
919 # We must ensure that __builtin__ (without the final 's') is always
920 # available and pointing to the __builtin__ *module*. For more details:
920 # available and pointing to the __builtin__ *module*. For more details:
921 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
921 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
922
922
923 if user_ns is None:
923 if user_ns is None:
924 # Set __name__ to __main__ to better match the behavior of the
924 # Set __name__ to __main__ to better match the behavior of the
925 # normal interpreter.
925 # normal interpreter.
926 user_ns = {'__name__' :'__main__',
926 user_ns = {'__name__' :'__main__',
927 '__builtin__' : __builtin__,
927 '__builtin__' : __builtin__,
928 '__builtins__' : __builtin__,
928 '__builtins__' : __builtin__,
929 }
929 }
930 else:
930 else:
931 user_ns.setdefault('__name__','__main__')
931 user_ns.setdefault('__name__','__main__')
932 user_ns.setdefault('__builtin__',__builtin__)
932 user_ns.setdefault('__builtin__',__builtin__)
933 user_ns.setdefault('__builtins__',__builtin__)
933 user_ns.setdefault('__builtins__',__builtin__)
934
934
935 if user_global_ns is None:
935 if user_global_ns is None:
936 user_global_ns = user_ns
936 user_global_ns = user_ns
937 if type(user_global_ns) is not dict:
937 if type(user_global_ns) is not dict:
938 raise TypeError("user_global_ns must be a true dict; got %r"
938 raise TypeError("user_global_ns must be a true dict; got %r"
939 % type(user_global_ns))
939 % type(user_global_ns))
940
940
941 return user_ns, user_global_ns
941 return user_ns, user_global_ns
942
942
943 def init_sys_modules(self):
943 def init_sys_modules(self):
944 # We need to insert into sys.modules something that looks like a
944 # We need to insert into sys.modules something that looks like a
945 # module but which accesses the IPython namespace, for shelve and
945 # module but which accesses the IPython namespace, for shelve and
946 # pickle to work interactively. Normally they rely on getting
946 # pickle to work interactively. Normally they rely on getting
947 # everything out of __main__, but for embedding purposes each IPython
947 # everything out of __main__, but for embedding purposes each IPython
948 # instance has its own private namespace, so we can't go shoving
948 # instance has its own private namespace, so we can't go shoving
949 # everything into __main__.
949 # everything into __main__.
950
950
951 # note, however, that we should only do this for non-embedded
951 # note, however, that we should only do this for non-embedded
952 # ipythons, which really mimic the __main__.__dict__ with their own
952 # ipythons, which really mimic the __main__.__dict__ with their own
953 # namespace. Embedded instances, on the other hand, should not do
953 # namespace. Embedded instances, on the other hand, should not do
954 # this because they need to manage the user local/global namespaces
954 # this because they need to manage the user local/global namespaces
955 # only, but they live within a 'normal' __main__ (meaning, they
955 # only, but they live within a 'normal' __main__ (meaning, they
956 # shouldn't overtake the execution environment of the script they're
956 # shouldn't overtake the execution environment of the script they're
957 # embedded in).
957 # embedded in).
958
958
959 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
959 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
960
960
961 try:
961 try:
962 main_name = self.user_ns['__name__']
962 main_name = self.user_ns['__name__']
963 except KeyError:
963 except KeyError:
964 raise KeyError('user_ns dictionary MUST have a "__name__" key')
964 raise KeyError('user_ns dictionary MUST have a "__name__" key')
965 else:
965 else:
966 sys.modules[main_name] = FakeModule(self.user_ns)
966 sys.modules[main_name] = FakeModule(self.user_ns)
967
967
968 def init_user_ns(self):
968 def init_user_ns(self):
969 """Initialize all user-visible namespaces to their minimum defaults.
969 """Initialize all user-visible namespaces to their minimum defaults.
970
970
971 Certain history lists are also initialized here, as they effectively
971 Certain history lists are also initialized here, as they effectively
972 act as user namespaces.
972 act as user namespaces.
973
973
974 Notes
974 Notes
975 -----
975 -----
976 All data structures here are only filled in, they are NOT reset by this
976 All data structures here are only filled in, they are NOT reset by this
977 method. If they were not empty before, data will simply be added to
977 method. If they were not empty before, data will simply be added to
978 therm.
978 therm.
979 """
979 """
980 # This function works in two parts: first we put a few things in
980 # This function works in two parts: first we put a few things in
981 # user_ns, and we sync that contents into user_ns_hidden so that these
981 # user_ns, and we sync that contents into user_ns_hidden so that these
982 # initial variables aren't shown by %who. After the sync, we add the
982 # initial variables aren't shown by %who. After the sync, we add the
983 # rest of what we *do* want the user to see with %who even on a new
983 # rest of what we *do* want the user to see with %who even on a new
984 # session (probably nothing, so theye really only see their own stuff)
984 # session (probably nothing, so theye really only see their own stuff)
985
985
986 # The user dict must *always* have a __builtin__ reference to the
986 # The user dict must *always* have a __builtin__ reference to the
987 # Python standard __builtin__ namespace, which must be imported.
987 # Python standard __builtin__ namespace, which must be imported.
988 # This is so that certain operations in prompt evaluation can be
988 # This is so that certain operations in prompt evaluation can be
989 # reliably executed with builtins. Note that we can NOT use
989 # reliably executed with builtins. Note that we can NOT use
990 # __builtins__ (note the 's'), because that can either be a dict or a
990 # __builtins__ (note the 's'), because that can either be a dict or a
991 # module, and can even mutate at runtime, depending on the context
991 # module, and can even mutate at runtime, depending on the context
992 # (Python makes no guarantees on it). In contrast, __builtin__ is
992 # (Python makes no guarantees on it). In contrast, __builtin__ is
993 # always a module object, though it must be explicitly imported.
993 # always a module object, though it must be explicitly imported.
994
994
995 # For more details:
995 # For more details:
996 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
996 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
997 ns = dict(__builtin__ = __builtin__)
997 ns = dict(__builtin__ = __builtin__)
998
998
999 # Put 'help' in the user namespace
999 # Put 'help' in the user namespace
1000 try:
1000 try:
1001 from site import _Helper
1001 from site import _Helper
1002 ns['help'] = _Helper()
1002 ns['help'] = _Helper()
1003 except ImportError:
1003 except ImportError:
1004 warn('help() not available - check site.py')
1004 warn('help() not available - check site.py')
1005
1005
1006 # make global variables for user access to the histories
1006 # make global variables for user access to the histories
1007 ns['_ih'] = self.input_hist
1007 ns['_ih'] = self.input_hist
1008 ns['_oh'] = self.output_hist
1008 ns['_oh'] = self.output_hist
1009 ns['_dh'] = self.dir_hist
1009 ns['_dh'] = self.dir_hist
1010
1010
1011 ns['_sh'] = shadowns
1011 ns['_sh'] = shadowns
1012
1012
1013 # user aliases to input and output histories. These shouldn't show up
1013 # user aliases to input and output histories. These shouldn't show up
1014 # in %who, as they can have very large reprs.
1014 # in %who, as they can have very large reprs.
1015 ns['In'] = self.input_hist
1015 ns['In'] = self.input_hist
1016 ns['Out'] = self.output_hist
1016 ns['Out'] = self.output_hist
1017
1017
1018 # Store myself as the public api!!!
1018 # Store myself as the public api!!!
1019 ns['get_ipython'] = self.get_ipython
1019 ns['get_ipython'] = self.get_ipython
1020
1020
1021 # Sync what we've added so far to user_ns_hidden so these aren't seen
1021 # Sync what we've added so far to user_ns_hidden so these aren't seen
1022 # by %who
1022 # by %who
1023 self.user_ns_hidden.update(ns)
1023 self.user_ns_hidden.update(ns)
1024
1024
1025 # Anything put into ns now would show up in %who. Think twice before
1025 # Anything put into ns now would show up in %who. Think twice before
1026 # putting anything here, as we really want %who to show the user their
1026 # putting anything here, as we really want %who to show the user their
1027 # stuff, not our variables.
1027 # stuff, not our variables.
1028
1028
1029 # Finally, update the real user's namespace
1029 # Finally, update the real user's namespace
1030 self.user_ns.update(ns)
1030 self.user_ns.update(ns)
1031
1031
1032
1032
1033 def reset(self):
1033 def reset(self):
1034 """Clear all internal namespaces.
1034 """Clear all internal namespaces.
1035
1035
1036 Note that this is much more aggressive than %reset, since it clears
1036 Note that this is much more aggressive than %reset, since it clears
1037 fully all namespaces, as well as all input/output lists.
1037 fully all namespaces, as well as all input/output lists.
1038 """
1038 """
1039 for ns in self.ns_refs_table:
1039 for ns in self.ns_refs_table:
1040 ns.clear()
1040 ns.clear()
1041
1041
1042 self.alias_manager.clear_aliases()
1042 self.alias_manager.clear_aliases()
1043
1043
1044 # Clear input and output histories
1044 # Clear input and output histories
1045 self.input_hist[:] = []
1045 self.input_hist[:] = []
1046 self.input_hist_raw[:] = []
1046 self.input_hist_raw[:] = []
1047 self.output_hist.clear()
1047 self.output_hist.clear()
1048
1048
1049 # Restore the user namespaces to minimal usability
1049 # Restore the user namespaces to minimal usability
1050 self.init_user_ns()
1050 self.init_user_ns()
1051
1051
1052 # Restore the default and user aliases
1052 # Restore the default and user aliases
1053 self.alias_manager.init_aliases()
1053 self.alias_manager.init_aliases()
1054
1054
1055 def reset_selective(self, regex=None):
1056 """Clear selective variables from internal namespaces based on a specified regular expression.
1057
1058 Parameters
1059 ----------
1060 regex : string or compiled pattern, optional
1061 A regular expression pattern that will be used in searching variable names in the users
1062 namespaces.
1063 """
1064 if regex is not None:
1065 try:
1066 m = re.compile(regex)
1067 except TypeError:
1068 raise TypeError('regex must be a string or compiled pattern')
1069 # Search for keys in each namespace that match the given regex
1070 # If a match is found, delete the key/value pair.
1071 for ns in self.ns_refs_table:
1072 for var in ns:
1073 if m.search(var):
1074 del ns[var]
1075
1055 def push(self, variables, interactive=True):
1076 def push(self, variables, interactive=True):
1056 """Inject a group of variables into the IPython user namespace.
1077 """Inject a group of variables into the IPython user namespace.
1057
1078
1058 Parameters
1079 Parameters
1059 ----------
1080 ----------
1060 variables : dict, str or list/tuple of str
1081 variables : dict, str or list/tuple of str
1061 The variables to inject into the user's namespace. If a dict,
1082 The variables to inject into the user's namespace. If a dict,
1062 a simple update is done. If a str, the string is assumed to
1083 a simple update is done. If a str, the string is assumed to
1063 have variable names separated by spaces. A list/tuple of str
1084 have variable names separated by spaces. A list/tuple of str
1064 can also be used to give the variable names. If just the variable
1085 can also be used to give the variable names. If just the variable
1065 names are give (list/tuple/str) then the variable values looked
1086 names are give (list/tuple/str) then the variable values looked
1066 up in the callers frame.
1087 up in the callers frame.
1067 interactive : bool
1088 interactive : bool
1068 If True (default), the variables will be listed with the ``who``
1089 If True (default), the variables will be listed with the ``who``
1069 magic.
1090 magic.
1070 """
1091 """
1071 vdict = None
1092 vdict = None
1072
1093
1073 # We need a dict of name/value pairs to do namespace updates.
1094 # We need a dict of name/value pairs to do namespace updates.
1074 if isinstance(variables, dict):
1095 if isinstance(variables, dict):
1075 vdict = variables
1096 vdict = variables
1076 elif isinstance(variables, (basestring, list, tuple)):
1097 elif isinstance(variables, (basestring, list, tuple)):
1077 if isinstance(variables, basestring):
1098 if isinstance(variables, basestring):
1078 vlist = variables.split()
1099 vlist = variables.split()
1079 else:
1100 else:
1080 vlist = variables
1101 vlist = variables
1081 vdict = {}
1102 vdict = {}
1082 cf = sys._getframe(1)
1103 cf = sys._getframe(1)
1083 for name in vlist:
1104 for name in vlist:
1084 try:
1105 try:
1085 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1106 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1086 except:
1107 except:
1087 print ('Could not get variable %s from %s' %
1108 print ('Could not get variable %s from %s' %
1088 (name,cf.f_code.co_name))
1109 (name,cf.f_code.co_name))
1089 else:
1110 else:
1090 raise ValueError('variables must be a dict/str/list/tuple')
1111 raise ValueError('variables must be a dict/str/list/tuple')
1091
1112
1092 # Propagate variables to user namespace
1113 # Propagate variables to user namespace
1093 self.user_ns.update(vdict)
1114 self.user_ns.update(vdict)
1094
1115
1095 # And configure interactive visibility
1116 # And configure interactive visibility
1096 config_ns = self.user_ns_hidden
1117 config_ns = self.user_ns_hidden
1097 if interactive:
1118 if interactive:
1098 for name, val in vdict.iteritems():
1119 for name, val in vdict.iteritems():
1099 config_ns.pop(name, None)
1120 config_ns.pop(name, None)
1100 else:
1121 else:
1101 for name,val in vdict.iteritems():
1122 for name,val in vdict.iteritems():
1102 config_ns[name] = val
1123 config_ns[name] = val
1103
1124
1104 #-------------------------------------------------------------------------
1125 #-------------------------------------------------------------------------
1105 # Things related to history management
1126 # Things related to history management
1106 #-------------------------------------------------------------------------
1127 #-------------------------------------------------------------------------
1107
1128
1108 def init_history(self):
1129 def init_history(self):
1109 # List of input with multi-line handling.
1130 # List of input with multi-line handling.
1110 self.input_hist = InputList()
1131 self.input_hist = InputList()
1111 # This one will hold the 'raw' input history, without any
1132 # This one will hold the 'raw' input history, without any
1112 # pre-processing. This will allow users to retrieve the input just as
1133 # pre-processing. This will allow users to retrieve the input just as
1113 # it was exactly typed in by the user, with %hist -r.
1134 # it was exactly typed in by the user, with %hist -r.
1114 self.input_hist_raw = InputList()
1135 self.input_hist_raw = InputList()
1115
1136
1116 # list of visited directories
1137 # list of visited directories
1117 try:
1138 try:
1118 self.dir_hist = [os.getcwd()]
1139 self.dir_hist = [os.getcwd()]
1119 except OSError:
1140 except OSError:
1120 self.dir_hist = []
1141 self.dir_hist = []
1121
1142
1122 # dict of output history
1143 # dict of output history
1123 self.output_hist = {}
1144 self.output_hist = {}
1124
1145
1125 # Now the history file
1146 # Now the history file
1126 if self.profile:
1147 if self.profile:
1127 histfname = 'history-%s' % self.profile
1148 histfname = 'history-%s' % self.profile
1128 else:
1149 else:
1129 histfname = 'history'
1150 histfname = 'history'
1130 self.histfile = os.path.join(self.ipython_dir, histfname)
1151 self.histfile = os.path.join(self.ipython_dir, histfname)
1131
1152
1132 # Fill the history zero entry, user counter starts at 1
1153 # Fill the history zero entry, user counter starts at 1
1133 self.input_hist.append('\n')
1154 self.input_hist.append('\n')
1134 self.input_hist_raw.append('\n')
1155 self.input_hist_raw.append('\n')
1135
1156
1136 def init_shadow_hist(self):
1157 def init_shadow_hist(self):
1137 try:
1158 try:
1138 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1159 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1139 except exceptions.UnicodeDecodeError:
1160 except exceptions.UnicodeDecodeError:
1140 print "Your ipython_dir can't be decoded to unicode!"
1161 print "Your ipython_dir can't be decoded to unicode!"
1141 print "Please set HOME environment variable to something that"
1162 print "Please set HOME environment variable to something that"
1142 print r"only has ASCII characters, e.g. c:\home"
1163 print r"only has ASCII characters, e.g. c:\home"
1143 print "Now it is", self.ipython_dir
1164 print "Now it is", self.ipython_dir
1144 sys.exit()
1165 sys.exit()
1145 self.shadowhist = ipcorehist.ShadowHist(self.db)
1166 self.shadowhist = ipcorehist.ShadowHist(self.db)
1146
1167
1147 def savehist(self):
1168 def savehist(self):
1148 """Save input history to a file (via readline library)."""
1169 """Save input history to a file (via readline library)."""
1149
1170
1150 try:
1171 try:
1151 self.readline.write_history_file(self.histfile)
1172 self.readline.write_history_file(self.histfile)
1152 except:
1173 except:
1153 print 'Unable to save IPython command history to file: ' + \
1174 print 'Unable to save IPython command history to file: ' + \
1154 `self.histfile`
1175 `self.histfile`
1155
1176
1156 def reloadhist(self):
1177 def reloadhist(self):
1157 """Reload the input history from disk file."""
1178 """Reload the input history from disk file."""
1158
1179
1159 try:
1180 try:
1160 self.readline.clear_history()
1181 self.readline.clear_history()
1161 self.readline.read_history_file(self.shell.histfile)
1182 self.readline.read_history_file(self.shell.histfile)
1162 except AttributeError:
1183 except AttributeError:
1163 pass
1184 pass
1164
1185
1165 def history_saving_wrapper(self, func):
1186 def history_saving_wrapper(self, func):
1166 """ Wrap func for readline history saving
1187 """ Wrap func for readline history saving
1167
1188
1168 Convert func into callable that saves & restores
1189 Convert func into callable that saves & restores
1169 history around the call """
1190 history around the call """
1170
1191
1171 if self.has_readline:
1192 if self.has_readline:
1172 from IPython.utils import rlineimpl as readline
1193 from IPython.utils import rlineimpl as readline
1173 else:
1194 else:
1174 return func
1195 return func
1175
1196
1176 def wrapper():
1197 def wrapper():
1177 self.savehist()
1198 self.savehist()
1178 try:
1199 try:
1179 func()
1200 func()
1180 finally:
1201 finally:
1181 readline.read_history_file(self.histfile)
1202 readline.read_history_file(self.histfile)
1182 return wrapper
1203 return wrapper
1183
1204
1184 #-------------------------------------------------------------------------
1205 #-------------------------------------------------------------------------
1185 # Things related to exception handling and tracebacks (not debugging)
1206 # Things related to exception handling and tracebacks (not debugging)
1186 #-------------------------------------------------------------------------
1207 #-------------------------------------------------------------------------
1187
1208
1188 def init_traceback_handlers(self, custom_exceptions):
1209 def init_traceback_handlers(self, custom_exceptions):
1189 # Syntax error handler.
1210 # Syntax error handler.
1190 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1211 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1191
1212
1192 # The interactive one is initialized with an offset, meaning we always
1213 # The interactive one is initialized with an offset, meaning we always
1193 # want to remove the topmost item in the traceback, which is our own
1214 # want to remove the topmost item in the traceback, which is our own
1194 # internal code. Valid modes: ['Plain','Context','Verbose']
1215 # internal code. Valid modes: ['Plain','Context','Verbose']
1195 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1216 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1196 color_scheme='NoColor',
1217 color_scheme='NoColor',
1197 tb_offset = 1)
1218 tb_offset = 1)
1198
1219
1199 # The instance will store a pointer to the system-wide exception hook,
1220 # The instance will store a pointer to the system-wide exception hook,
1200 # so that runtime code (such as magics) can access it. This is because
1221 # so that runtime code (such as magics) can access it. This is because
1201 # during the read-eval loop, it may get temporarily overwritten.
1222 # during the read-eval loop, it may get temporarily overwritten.
1202 self.sys_excepthook = sys.excepthook
1223 self.sys_excepthook = sys.excepthook
1203
1224
1204 # and add any custom exception handlers the user may have specified
1225 # and add any custom exception handlers the user may have specified
1205 self.set_custom_exc(*custom_exceptions)
1226 self.set_custom_exc(*custom_exceptions)
1206
1227
1207 # Set the exception mode
1228 # Set the exception mode
1208 self.InteractiveTB.set_mode(mode=self.xmode)
1229 self.InteractiveTB.set_mode(mode=self.xmode)
1209
1230
1210 def set_custom_exc(self,exc_tuple,handler):
1231 def set_custom_exc(self,exc_tuple,handler):
1211 """set_custom_exc(exc_tuple,handler)
1232 """set_custom_exc(exc_tuple,handler)
1212
1233
1213 Set a custom exception handler, which will be called if any of the
1234 Set a custom exception handler, which will be called if any of the
1214 exceptions in exc_tuple occur in the mainloop (specifically, in the
1235 exceptions in exc_tuple occur in the mainloop (specifically, in the
1215 runcode() method.
1236 runcode() method.
1216
1237
1217 Inputs:
1238 Inputs:
1218
1239
1219 - exc_tuple: a *tuple* of valid exceptions to call the defined
1240 - exc_tuple: a *tuple* of valid exceptions to call the defined
1220 handler for. It is very important that you use a tuple, and NOT A
1241 handler for. It is very important that you use a tuple, and NOT A
1221 LIST here, because of the way Python's except statement works. If
1242 LIST here, because of the way Python's except statement works. If
1222 you only want to trap a single exception, use a singleton tuple:
1243 you only want to trap a single exception, use a singleton tuple:
1223
1244
1224 exc_tuple == (MyCustomException,)
1245 exc_tuple == (MyCustomException,)
1225
1246
1226 - handler: this must be defined as a function with the following
1247 - handler: this must be defined as a function with the following
1227 basic interface: def my_handler(self,etype,value,tb).
1248 basic interface: def my_handler(self,etype,value,tb).
1228
1249
1229 This will be made into an instance method (via new.instancemethod)
1250 This will be made into an instance method (via new.instancemethod)
1230 of IPython itself, and it will be called if any of the exceptions
1251 of IPython itself, and it will be called if any of the exceptions
1231 listed in the exc_tuple are caught. If the handler is None, an
1252 listed in the exc_tuple are caught. If the handler is None, an
1232 internal basic one is used, which just prints basic info.
1253 internal basic one is used, which just prints basic info.
1233
1254
1234 WARNING: by putting in your own exception handler into IPython's main
1255 WARNING: by putting in your own exception handler into IPython's main
1235 execution loop, you run a very good chance of nasty crashes. This
1256 execution loop, you run a very good chance of nasty crashes. This
1236 facility should only be used if you really know what you are doing."""
1257 facility should only be used if you really know what you are doing."""
1237
1258
1238 assert type(exc_tuple)==type(()) , \
1259 assert type(exc_tuple)==type(()) , \
1239 "The custom exceptions must be given AS A TUPLE."
1260 "The custom exceptions must be given AS A TUPLE."
1240
1261
1241 def dummy_handler(self,etype,value,tb):
1262 def dummy_handler(self,etype,value,tb):
1242 print '*** Simple custom exception handler ***'
1263 print '*** Simple custom exception handler ***'
1243 print 'Exception type :',etype
1264 print 'Exception type :',etype
1244 print 'Exception value:',value
1265 print 'Exception value:',value
1245 print 'Traceback :',tb
1266 print 'Traceback :',tb
1246 print 'Source code :','\n'.join(self.buffer)
1267 print 'Source code :','\n'.join(self.buffer)
1247
1268
1248 if handler is None: handler = dummy_handler
1269 if handler is None: handler = dummy_handler
1249
1270
1250 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1271 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1251 self.custom_exceptions = exc_tuple
1272 self.custom_exceptions = exc_tuple
1252
1273
1253 def excepthook(self, etype, value, tb):
1274 def excepthook(self, etype, value, tb):
1254 """One more defense for GUI apps that call sys.excepthook.
1275 """One more defense for GUI apps that call sys.excepthook.
1255
1276
1256 GUI frameworks like wxPython trap exceptions and call
1277 GUI frameworks like wxPython trap exceptions and call
1257 sys.excepthook themselves. I guess this is a feature that
1278 sys.excepthook themselves. I guess this is a feature that
1258 enables them to keep running after exceptions that would
1279 enables them to keep running after exceptions that would
1259 otherwise kill their mainloop. This is a bother for IPython
1280 otherwise kill their mainloop. This is a bother for IPython
1260 which excepts to catch all of the program exceptions with a try:
1281 which excepts to catch all of the program exceptions with a try:
1261 except: statement.
1282 except: statement.
1262
1283
1263 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1284 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1264 any app directly invokes sys.excepthook, it will look to the user like
1285 any app directly invokes sys.excepthook, it will look to the user like
1265 IPython crashed. In order to work around this, we can disable the
1286 IPython crashed. In order to work around this, we can disable the
1266 CrashHandler and replace it with this excepthook instead, which prints a
1287 CrashHandler and replace it with this excepthook instead, which prints a
1267 regular traceback using our InteractiveTB. In this fashion, apps which
1288 regular traceback using our InteractiveTB. In this fashion, apps which
1268 call sys.excepthook will generate a regular-looking exception from
1289 call sys.excepthook will generate a regular-looking exception from
1269 IPython, and the CrashHandler will only be triggered by real IPython
1290 IPython, and the CrashHandler will only be triggered by real IPython
1270 crashes.
1291 crashes.
1271
1292
1272 This hook should be used sparingly, only in places which are not likely
1293 This hook should be used sparingly, only in places which are not likely
1273 to be true IPython errors.
1294 to be true IPython errors.
1274 """
1295 """
1275 self.showtraceback((etype,value,tb),tb_offset=0)
1296 self.showtraceback((etype,value,tb),tb_offset=0)
1276
1297
1277 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1298 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1278 exception_only=False):
1299 exception_only=False):
1279 """Display the exception that just occurred.
1300 """Display the exception that just occurred.
1280
1301
1281 If nothing is known about the exception, this is the method which
1302 If nothing is known about the exception, this is the method which
1282 should be used throughout the code for presenting user tracebacks,
1303 should be used throughout the code for presenting user tracebacks,
1283 rather than directly invoking the InteractiveTB object.
1304 rather than directly invoking the InteractiveTB object.
1284
1305
1285 A specific showsyntaxerror() also exists, but this method can take
1306 A specific showsyntaxerror() also exists, but this method can take
1286 care of calling it if needed, so unless you are explicitly catching a
1307 care of calling it if needed, so unless you are explicitly catching a
1287 SyntaxError exception, don't try to analyze the stack manually and
1308 SyntaxError exception, don't try to analyze the stack manually and
1288 simply call this method."""
1309 simply call this method."""
1289
1310
1290 try:
1311 try:
1291 if exc_tuple is None:
1312 if exc_tuple is None:
1292 etype, value, tb = sys.exc_info()
1313 etype, value, tb = sys.exc_info()
1293 else:
1314 else:
1294 etype, value, tb = exc_tuple
1315 etype, value, tb = exc_tuple
1295
1316
1296 if etype is None:
1317 if etype is None:
1297 if hasattr(sys, 'last_type'):
1318 if hasattr(sys, 'last_type'):
1298 etype, value, tb = sys.last_type, sys.last_value, \
1319 etype, value, tb = sys.last_type, sys.last_value, \
1299 sys.last_traceback
1320 sys.last_traceback
1300 else:
1321 else:
1301 self.write('No traceback available to show.\n')
1322 self.write('No traceback available to show.\n')
1302 return
1323 return
1303
1324
1304 if etype is SyntaxError:
1325 if etype is SyntaxError:
1305 # Though this won't be called by syntax errors in the input
1326 # Though this won't be called by syntax errors in the input
1306 # line, there may be SyntaxError cases whith imported code.
1327 # line, there may be SyntaxError cases whith imported code.
1307 self.showsyntaxerror(filename)
1328 self.showsyntaxerror(filename)
1308 elif etype is UsageError:
1329 elif etype is UsageError:
1309 print "UsageError:", value
1330 print "UsageError:", value
1310 else:
1331 else:
1311 # WARNING: these variables are somewhat deprecated and not
1332 # WARNING: these variables are somewhat deprecated and not
1312 # necessarily safe to use in a threaded environment, but tools
1333 # necessarily safe to use in a threaded environment, but tools
1313 # like pdb depend on their existence, so let's set them. If we
1334 # like pdb depend on their existence, so let's set them. If we
1314 # find problems in the field, we'll need to revisit their use.
1335 # find problems in the field, we'll need to revisit their use.
1315 sys.last_type = etype
1336 sys.last_type = etype
1316 sys.last_value = value
1337 sys.last_value = value
1317 sys.last_traceback = tb
1338 sys.last_traceback = tb
1318
1339
1319 if etype in self.custom_exceptions:
1340 if etype in self.custom_exceptions:
1320 self.CustomTB(etype,value,tb)
1341 self.CustomTB(etype,value,tb)
1321 else:
1342 else:
1322 if exception_only:
1343 if exception_only:
1323 m = ('An exception has occurred, use %tb to see the '
1344 m = ('An exception has occurred, use %tb to see the '
1324 'full traceback.')
1345 'full traceback.')
1325 print m
1346 print m
1326 self.InteractiveTB.show_exception_only(etype, value)
1347 self.InteractiveTB.show_exception_only(etype, value)
1327 else:
1348 else:
1328 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1349 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1329 if self.InteractiveTB.call_pdb:
1350 if self.InteractiveTB.call_pdb:
1330 # pdb mucks up readline, fix it back
1351 # pdb mucks up readline, fix it back
1331 self.set_completer()
1352 self.set_completer()
1332
1353
1333 except KeyboardInterrupt:
1354 except KeyboardInterrupt:
1334 self.write("\nKeyboardInterrupt\n")
1355 self.write("\nKeyboardInterrupt\n")
1335
1356
1336
1357
1337 def showsyntaxerror(self, filename=None):
1358 def showsyntaxerror(self, filename=None):
1338 """Display the syntax error that just occurred.
1359 """Display the syntax error that just occurred.
1339
1360
1340 This doesn't display a stack trace because there isn't one.
1361 This doesn't display a stack trace because there isn't one.
1341
1362
1342 If a filename is given, it is stuffed in the exception instead
1363 If a filename is given, it is stuffed in the exception instead
1343 of what was there before (because Python's parser always uses
1364 of what was there before (because Python's parser always uses
1344 "<string>" when reading from a string).
1365 "<string>" when reading from a string).
1345 """
1366 """
1346 etype, value, last_traceback = sys.exc_info()
1367 etype, value, last_traceback = sys.exc_info()
1347
1368
1348 # See note about these variables in showtraceback() above
1369 # See note about these variables in showtraceback() above
1349 sys.last_type = etype
1370 sys.last_type = etype
1350 sys.last_value = value
1371 sys.last_value = value
1351 sys.last_traceback = last_traceback
1372 sys.last_traceback = last_traceback
1352
1373
1353 if filename and etype is SyntaxError:
1374 if filename and etype is SyntaxError:
1354 # Work hard to stuff the correct filename in the exception
1375 # Work hard to stuff the correct filename in the exception
1355 try:
1376 try:
1356 msg, (dummy_filename, lineno, offset, line) = value
1377 msg, (dummy_filename, lineno, offset, line) = value
1357 except:
1378 except:
1358 # Not the format we expect; leave it alone
1379 # Not the format we expect; leave it alone
1359 pass
1380 pass
1360 else:
1381 else:
1361 # Stuff in the right filename
1382 # Stuff in the right filename
1362 try:
1383 try:
1363 # Assume SyntaxError is a class exception
1384 # Assume SyntaxError is a class exception
1364 value = SyntaxError(msg, (filename, lineno, offset, line))
1385 value = SyntaxError(msg, (filename, lineno, offset, line))
1365 except:
1386 except:
1366 # If that failed, assume SyntaxError is a string
1387 # If that failed, assume SyntaxError is a string
1367 value = msg, (filename, lineno, offset, line)
1388 value = msg, (filename, lineno, offset, line)
1368 self.SyntaxTB(etype,value,[])
1389 self.SyntaxTB(etype,value,[])
1369
1390
1370 def edit_syntax_error(self):
1391 def edit_syntax_error(self):
1371 """The bottom half of the syntax error handler called in the main loop.
1392 """The bottom half of the syntax error handler called in the main loop.
1372
1393
1373 Loop until syntax error is fixed or user cancels.
1394 Loop until syntax error is fixed or user cancels.
1374 """
1395 """
1375
1396
1376 while self.SyntaxTB.last_syntax_error:
1397 while self.SyntaxTB.last_syntax_error:
1377 # copy and clear last_syntax_error
1398 # copy and clear last_syntax_error
1378 err = self.SyntaxTB.clear_err_state()
1399 err = self.SyntaxTB.clear_err_state()
1379 if not self._should_recompile(err):
1400 if not self._should_recompile(err):
1380 return
1401 return
1381 try:
1402 try:
1382 # may set last_syntax_error again if a SyntaxError is raised
1403 # may set last_syntax_error again if a SyntaxError is raised
1383 self.safe_execfile(err.filename,self.user_ns)
1404 self.safe_execfile(err.filename,self.user_ns)
1384 except:
1405 except:
1385 self.showtraceback()
1406 self.showtraceback()
1386 else:
1407 else:
1387 try:
1408 try:
1388 f = file(err.filename)
1409 f = file(err.filename)
1389 try:
1410 try:
1390 # This should be inside a display_trap block and I
1411 # This should be inside a display_trap block and I
1391 # think it is.
1412 # think it is.
1392 sys.displayhook(f.read())
1413 sys.displayhook(f.read())
1393 finally:
1414 finally:
1394 f.close()
1415 f.close()
1395 except:
1416 except:
1396 self.showtraceback()
1417 self.showtraceback()
1397
1418
1398 def _should_recompile(self,e):
1419 def _should_recompile(self,e):
1399 """Utility routine for edit_syntax_error"""
1420 """Utility routine for edit_syntax_error"""
1400
1421
1401 if e.filename in ('<ipython console>','<input>','<string>',
1422 if e.filename in ('<ipython console>','<input>','<string>',
1402 '<console>','<BackgroundJob compilation>',
1423 '<console>','<BackgroundJob compilation>',
1403 None):
1424 None):
1404
1425
1405 return False
1426 return False
1406 try:
1427 try:
1407 if (self.autoedit_syntax and
1428 if (self.autoedit_syntax and
1408 not self.ask_yes_no('Return to editor to correct syntax error? '
1429 not self.ask_yes_no('Return to editor to correct syntax error? '
1409 '[Y/n] ','y')):
1430 '[Y/n] ','y')):
1410 return False
1431 return False
1411 except EOFError:
1432 except EOFError:
1412 return False
1433 return False
1413
1434
1414 def int0(x):
1435 def int0(x):
1415 try:
1436 try:
1416 return int(x)
1437 return int(x)
1417 except TypeError:
1438 except TypeError:
1418 return 0
1439 return 0
1419 # always pass integer line and offset values to editor hook
1440 # always pass integer line and offset values to editor hook
1420 try:
1441 try:
1421 self.hooks.fix_error_editor(e.filename,
1442 self.hooks.fix_error_editor(e.filename,
1422 int0(e.lineno),int0(e.offset),e.msg)
1443 int0(e.lineno),int0(e.offset),e.msg)
1423 except TryNext:
1444 except TryNext:
1424 warn('Could not open editor')
1445 warn('Could not open editor')
1425 return False
1446 return False
1426 return True
1447 return True
1427
1448
1428 #-------------------------------------------------------------------------
1449 #-------------------------------------------------------------------------
1429 # Things related to tab completion
1450 # Things related to tab completion
1430 #-------------------------------------------------------------------------
1451 #-------------------------------------------------------------------------
1431
1452
1432 def complete(self, text):
1453 def complete(self, text):
1433 """Return a sorted list of all possible completions on text.
1454 """Return a sorted list of all possible completions on text.
1434
1455
1435 Inputs:
1456 Inputs:
1436
1457
1437 - text: a string of text to be completed on.
1458 - text: a string of text to be completed on.
1438
1459
1439 This is a wrapper around the completion mechanism, similar to what
1460 This is a wrapper around the completion mechanism, similar to what
1440 readline does at the command line when the TAB key is hit. By
1461 readline does at the command line when the TAB key is hit. By
1441 exposing it as a method, it can be used by other non-readline
1462 exposing it as a method, it can be used by other non-readline
1442 environments (such as GUIs) for text completion.
1463 environments (such as GUIs) for text completion.
1443
1464
1444 Simple usage example:
1465 Simple usage example:
1445
1466
1446 In [7]: x = 'hello'
1467 In [7]: x = 'hello'
1447
1468
1448 In [8]: x
1469 In [8]: x
1449 Out[8]: 'hello'
1470 Out[8]: 'hello'
1450
1471
1451 In [9]: print x
1472 In [9]: print x
1452 hello
1473 hello
1453
1474
1454 In [10]: _ip.complete('x.l')
1475 In [10]: _ip.complete('x.l')
1455 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1476 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1456 """
1477 """
1457
1478
1458 # Inject names into __builtin__ so we can complete on the added names.
1479 # Inject names into __builtin__ so we can complete on the added names.
1459 with self.builtin_trap:
1480 with self.builtin_trap:
1460 complete = self.Completer.complete
1481 complete = self.Completer.complete
1461 state = 0
1482 state = 0
1462 # use a dict so we get unique keys, since ipyhton's multiple
1483 # use a dict so we get unique keys, since ipyhton's multiple
1463 # completers can return duplicates. When we make 2.4 a requirement,
1484 # completers can return duplicates. When we make 2.4 a requirement,
1464 # start using sets instead, which are faster.
1485 # start using sets instead, which are faster.
1465 comps = {}
1486 comps = {}
1466 while True:
1487 while True:
1467 newcomp = complete(text,state,line_buffer=text)
1488 newcomp = complete(text,state,line_buffer=text)
1468 if newcomp is None:
1489 if newcomp is None:
1469 break
1490 break
1470 comps[newcomp] = 1
1491 comps[newcomp] = 1
1471 state += 1
1492 state += 1
1472 outcomps = comps.keys()
1493 outcomps = comps.keys()
1473 outcomps.sort()
1494 outcomps.sort()
1474 #print "T:",text,"OC:",outcomps # dbg
1495 #print "T:",text,"OC:",outcomps # dbg
1475 #print "vars:",self.user_ns.keys()
1496 #print "vars:",self.user_ns.keys()
1476 return outcomps
1497 return outcomps
1477
1498
1478 def set_custom_completer(self,completer,pos=0):
1499 def set_custom_completer(self,completer,pos=0):
1479 """Adds a new custom completer function.
1500 """Adds a new custom completer function.
1480
1501
1481 The position argument (defaults to 0) is the index in the completers
1502 The position argument (defaults to 0) is the index in the completers
1482 list where you want the completer to be inserted."""
1503 list where you want the completer to be inserted."""
1483
1504
1484 newcomp = new.instancemethod(completer,self.Completer,
1505 newcomp = new.instancemethod(completer,self.Completer,
1485 self.Completer.__class__)
1506 self.Completer.__class__)
1486 self.Completer.matchers.insert(pos,newcomp)
1507 self.Completer.matchers.insert(pos,newcomp)
1487
1508
1488 def set_completer(self):
1509 def set_completer(self):
1489 """Reset readline's completer to be our own."""
1510 """Reset readline's completer to be our own."""
1490 self.readline.set_completer(self.Completer.complete)
1511 self.readline.set_completer(self.Completer.complete)
1491
1512
1492 def set_completer_frame(self, frame=None):
1513 def set_completer_frame(self, frame=None):
1493 """Set the frame of the completer."""
1514 """Set the frame of the completer."""
1494 if frame:
1515 if frame:
1495 self.Completer.namespace = frame.f_locals
1516 self.Completer.namespace = frame.f_locals
1496 self.Completer.global_namespace = frame.f_globals
1517 self.Completer.global_namespace = frame.f_globals
1497 else:
1518 else:
1498 self.Completer.namespace = self.user_ns
1519 self.Completer.namespace = self.user_ns
1499 self.Completer.global_namespace = self.user_global_ns
1520 self.Completer.global_namespace = self.user_global_ns
1500
1521
1501 #-------------------------------------------------------------------------
1522 #-------------------------------------------------------------------------
1502 # Things related to readline
1523 # Things related to readline
1503 #-------------------------------------------------------------------------
1524 #-------------------------------------------------------------------------
1504
1525
1505 def init_readline(self):
1526 def init_readline(self):
1506 """Command history completion/saving/reloading."""
1527 """Command history completion/saving/reloading."""
1507
1528
1508 if self.readline_use:
1529 if self.readline_use:
1509 import IPython.utils.rlineimpl as readline
1530 import IPython.utils.rlineimpl as readline
1510
1531
1511 self.rl_next_input = None
1532 self.rl_next_input = None
1512 self.rl_do_indent = False
1533 self.rl_do_indent = False
1513
1534
1514 if not self.readline_use or not readline.have_readline:
1535 if not self.readline_use or not readline.have_readline:
1515 self.has_readline = False
1536 self.has_readline = False
1516 self.readline = None
1537 self.readline = None
1517 # Set a number of methods that depend on readline to be no-op
1538 # Set a number of methods that depend on readline to be no-op
1518 self.savehist = no_op
1539 self.savehist = no_op
1519 self.reloadhist = no_op
1540 self.reloadhist = no_op
1520 self.set_completer = no_op
1541 self.set_completer = no_op
1521 self.set_custom_completer = no_op
1542 self.set_custom_completer = no_op
1522 self.set_completer_frame = no_op
1543 self.set_completer_frame = no_op
1523 warn('Readline services not available or not loaded.')
1544 warn('Readline services not available or not loaded.')
1524 else:
1545 else:
1525 self.has_readline = True
1546 self.has_readline = True
1526 self.readline = readline
1547 self.readline = readline
1527 sys.modules['readline'] = readline
1548 sys.modules['readline'] = readline
1528 import atexit
1549 import atexit
1529 from IPython.core.completer import IPCompleter
1550 from IPython.core.completer import IPCompleter
1530 self.Completer = IPCompleter(self,
1551 self.Completer = IPCompleter(self,
1531 self.user_ns,
1552 self.user_ns,
1532 self.user_global_ns,
1553 self.user_global_ns,
1533 self.readline_omit__names,
1554 self.readline_omit__names,
1534 self.alias_manager.alias_table)
1555 self.alias_manager.alias_table)
1535 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1556 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1536 self.strdispatchers['complete_command'] = sdisp
1557 self.strdispatchers['complete_command'] = sdisp
1537 self.Completer.custom_completers = sdisp
1558 self.Completer.custom_completers = sdisp
1538 # Platform-specific configuration
1559 # Platform-specific configuration
1539 if os.name == 'nt':
1560 if os.name == 'nt':
1540 self.readline_startup_hook = readline.set_pre_input_hook
1561 self.readline_startup_hook = readline.set_pre_input_hook
1541 else:
1562 else:
1542 self.readline_startup_hook = readline.set_startup_hook
1563 self.readline_startup_hook = readline.set_startup_hook
1543
1564
1544 # Load user's initrc file (readline config)
1565 # Load user's initrc file (readline config)
1545 # Or if libedit is used, load editrc.
1566 # Or if libedit is used, load editrc.
1546 inputrc_name = os.environ.get('INPUTRC')
1567 inputrc_name = os.environ.get('INPUTRC')
1547 if inputrc_name is None:
1568 if inputrc_name is None:
1548 home_dir = get_home_dir()
1569 home_dir = get_home_dir()
1549 if home_dir is not None:
1570 if home_dir is not None:
1550 inputrc_name = '.inputrc'
1571 inputrc_name = '.inputrc'
1551 if readline.uses_libedit:
1572 if readline.uses_libedit:
1552 inputrc_name = '.editrc'
1573 inputrc_name = '.editrc'
1553 inputrc_name = os.path.join(home_dir, inputrc_name)
1574 inputrc_name = os.path.join(home_dir, inputrc_name)
1554 if os.path.isfile(inputrc_name):
1575 if os.path.isfile(inputrc_name):
1555 try:
1576 try:
1556 readline.read_init_file(inputrc_name)
1577 readline.read_init_file(inputrc_name)
1557 except:
1578 except:
1558 warn('Problems reading readline initialization file <%s>'
1579 warn('Problems reading readline initialization file <%s>'
1559 % inputrc_name)
1580 % inputrc_name)
1560
1581
1561 # save this in sys so embedded copies can restore it properly
1582 # save this in sys so embedded copies can restore it properly
1562 sys.ipcompleter = self.Completer.complete
1583 sys.ipcompleter = self.Completer.complete
1563 self.set_completer()
1584 self.set_completer()
1564
1585
1565 # Configure readline according to user's prefs
1586 # Configure readline according to user's prefs
1566 # This is only done if GNU readline is being used. If libedit
1587 # This is only done if GNU readline is being used. If libedit
1567 # is being used (as on Leopard) the readline config is
1588 # is being used (as on Leopard) the readline config is
1568 # not run as the syntax for libedit is different.
1589 # not run as the syntax for libedit is different.
1569 if not readline.uses_libedit:
1590 if not readline.uses_libedit:
1570 for rlcommand in self.readline_parse_and_bind:
1591 for rlcommand in self.readline_parse_and_bind:
1571 #print "loading rl:",rlcommand # dbg
1592 #print "loading rl:",rlcommand # dbg
1572 readline.parse_and_bind(rlcommand)
1593 readline.parse_and_bind(rlcommand)
1573
1594
1574 # Remove some chars from the delimiters list. If we encounter
1595 # Remove some chars from the delimiters list. If we encounter
1575 # unicode chars, discard them.
1596 # unicode chars, discard them.
1576 delims = readline.get_completer_delims().encode("ascii", "ignore")
1597 delims = readline.get_completer_delims().encode("ascii", "ignore")
1577 delims = delims.translate(string._idmap,
1598 delims = delims.translate(string._idmap,
1578 self.readline_remove_delims)
1599 self.readline_remove_delims)
1579 readline.set_completer_delims(delims)
1600 readline.set_completer_delims(delims)
1580 # otherwise we end up with a monster history after a while:
1601 # otherwise we end up with a monster history after a while:
1581 readline.set_history_length(1000)
1602 readline.set_history_length(1000)
1582 try:
1603 try:
1583 #print '*** Reading readline history' # dbg
1604 #print '*** Reading readline history' # dbg
1584 readline.read_history_file(self.histfile)
1605 readline.read_history_file(self.histfile)
1585 except IOError:
1606 except IOError:
1586 pass # It doesn't exist yet.
1607 pass # It doesn't exist yet.
1587
1608
1588 atexit.register(self.atexit_operations)
1609 atexit.register(self.atexit_operations)
1589 del atexit
1610 del atexit
1590
1611
1591 # Configure auto-indent for all platforms
1612 # Configure auto-indent for all platforms
1592 self.set_autoindent(self.autoindent)
1613 self.set_autoindent(self.autoindent)
1593
1614
1594 def set_next_input(self, s):
1615 def set_next_input(self, s):
1595 """ Sets the 'default' input string for the next command line.
1616 """ Sets the 'default' input string for the next command line.
1596
1617
1597 Requires readline.
1618 Requires readline.
1598
1619
1599 Example:
1620 Example:
1600
1621
1601 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1622 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1602 [D:\ipython]|2> Hello Word_ # cursor is here
1623 [D:\ipython]|2> Hello Word_ # cursor is here
1603 """
1624 """
1604
1625
1605 self.rl_next_input = s
1626 self.rl_next_input = s
1606
1627
1607 def pre_readline(self):
1628 def pre_readline(self):
1608 """readline hook to be used at the start of each line.
1629 """readline hook to be used at the start of each line.
1609
1630
1610 Currently it handles auto-indent only."""
1631 Currently it handles auto-indent only."""
1611
1632
1612 #debugx('self.indent_current_nsp','pre_readline:')
1633 #debugx('self.indent_current_nsp','pre_readline:')
1613
1634
1614 if self.rl_do_indent:
1635 if self.rl_do_indent:
1615 self.readline.insert_text(self._indent_current_str())
1636 self.readline.insert_text(self._indent_current_str())
1616 if self.rl_next_input is not None:
1637 if self.rl_next_input is not None:
1617 self.readline.insert_text(self.rl_next_input)
1638 self.readline.insert_text(self.rl_next_input)
1618 self.rl_next_input = None
1639 self.rl_next_input = None
1619
1640
1620 def _indent_current_str(self):
1641 def _indent_current_str(self):
1621 """return the current level of indentation as a string"""
1642 """return the current level of indentation as a string"""
1622 return self.indent_current_nsp * ' '
1643 return self.indent_current_nsp * ' '
1623
1644
1624 #-------------------------------------------------------------------------
1645 #-------------------------------------------------------------------------
1625 # Things related to magics
1646 # Things related to magics
1626 #-------------------------------------------------------------------------
1647 #-------------------------------------------------------------------------
1627
1648
1628 def init_magics(self):
1649 def init_magics(self):
1629 # Set user colors (don't do it in the constructor above so that it
1650 # Set user colors (don't do it in the constructor above so that it
1630 # doesn't crash if colors option is invalid)
1651 # doesn't crash if colors option is invalid)
1631 self.magic_colors(self.colors)
1652 self.magic_colors(self.colors)
1632 # History was moved to a separate module
1653 # History was moved to a separate module
1633 from . import history
1654 from . import history
1634 history.init_ipython(self)
1655 history.init_ipython(self)
1635
1656
1636 def magic(self,arg_s):
1657 def magic(self,arg_s):
1637 """Call a magic function by name.
1658 """Call a magic function by name.
1638
1659
1639 Input: a string containing the name of the magic function to call and any
1660 Input: a string containing the name of the magic function to call and any
1640 additional arguments to be passed to the magic.
1661 additional arguments to be passed to the magic.
1641
1662
1642 magic('name -opt foo bar') is equivalent to typing at the ipython
1663 magic('name -opt foo bar') is equivalent to typing at the ipython
1643 prompt:
1664 prompt:
1644
1665
1645 In[1]: %name -opt foo bar
1666 In[1]: %name -opt foo bar
1646
1667
1647 To call a magic without arguments, simply use magic('name').
1668 To call a magic without arguments, simply use magic('name').
1648
1669
1649 This provides a proper Python function to call IPython's magics in any
1670 This provides a proper Python function to call IPython's magics in any
1650 valid Python code you can type at the interpreter, including loops and
1671 valid Python code you can type at the interpreter, including loops and
1651 compound statements.
1672 compound statements.
1652 """
1673 """
1653 args = arg_s.split(' ',1)
1674 args = arg_s.split(' ',1)
1654 magic_name = args[0]
1675 magic_name = args[0]
1655 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1676 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1656
1677
1657 try:
1678 try:
1658 magic_args = args[1]
1679 magic_args = args[1]
1659 except IndexError:
1680 except IndexError:
1660 magic_args = ''
1681 magic_args = ''
1661 fn = getattr(self,'magic_'+magic_name,None)
1682 fn = getattr(self,'magic_'+magic_name,None)
1662 if fn is None:
1683 if fn is None:
1663 error("Magic function `%s` not found." % magic_name)
1684 error("Magic function `%s` not found." % magic_name)
1664 else:
1685 else:
1665 magic_args = self.var_expand(magic_args,1)
1686 magic_args = self.var_expand(magic_args,1)
1666 with nested(self.builtin_trap,):
1687 with nested(self.builtin_trap,):
1667 result = fn(magic_args)
1688 result = fn(magic_args)
1668 return result
1689 return result
1669
1690
1670 def define_magic(self, magicname, func):
1691 def define_magic(self, magicname, func):
1671 """Expose own function as magic function for ipython
1692 """Expose own function as magic function for ipython
1672
1693
1673 def foo_impl(self,parameter_s=''):
1694 def foo_impl(self,parameter_s=''):
1674 'My very own magic!. (Use docstrings, IPython reads them).'
1695 'My very own magic!. (Use docstrings, IPython reads them).'
1675 print 'Magic function. Passed parameter is between < >:'
1696 print 'Magic function. Passed parameter is between < >:'
1676 print '<%s>' % parameter_s
1697 print '<%s>' % parameter_s
1677 print 'The self object is:',self
1698 print 'The self object is:',self
1678
1699
1679 self.define_magic('foo',foo_impl)
1700 self.define_magic('foo',foo_impl)
1680 """
1701 """
1681
1702
1682 import new
1703 import new
1683 im = new.instancemethod(func,self, self.__class__)
1704 im = new.instancemethod(func,self, self.__class__)
1684 old = getattr(self, "magic_" + magicname, None)
1705 old = getattr(self, "magic_" + magicname, None)
1685 setattr(self, "magic_" + magicname, im)
1706 setattr(self, "magic_" + magicname, im)
1686 return old
1707 return old
1687
1708
1688 #-------------------------------------------------------------------------
1709 #-------------------------------------------------------------------------
1689 # Things related to macros
1710 # Things related to macros
1690 #-------------------------------------------------------------------------
1711 #-------------------------------------------------------------------------
1691
1712
1692 def define_macro(self, name, themacro):
1713 def define_macro(self, name, themacro):
1693 """Define a new macro
1714 """Define a new macro
1694
1715
1695 Parameters
1716 Parameters
1696 ----------
1717 ----------
1697 name : str
1718 name : str
1698 The name of the macro.
1719 The name of the macro.
1699 themacro : str or Macro
1720 themacro : str or Macro
1700 The action to do upon invoking the macro. If a string, a new
1721 The action to do upon invoking the macro. If a string, a new
1701 Macro object is created by passing the string to it.
1722 Macro object is created by passing the string to it.
1702 """
1723 """
1703
1724
1704 from IPython.core import macro
1725 from IPython.core import macro
1705
1726
1706 if isinstance(themacro, basestring):
1727 if isinstance(themacro, basestring):
1707 themacro = macro.Macro(themacro)
1728 themacro = macro.Macro(themacro)
1708 if not isinstance(themacro, macro.Macro):
1729 if not isinstance(themacro, macro.Macro):
1709 raise ValueError('A macro must be a string or a Macro instance.')
1730 raise ValueError('A macro must be a string or a Macro instance.')
1710 self.user_ns[name] = themacro
1731 self.user_ns[name] = themacro
1711
1732
1712 #-------------------------------------------------------------------------
1733 #-------------------------------------------------------------------------
1713 # Things related to the running of system commands
1734 # Things related to the running of system commands
1714 #-------------------------------------------------------------------------
1735 #-------------------------------------------------------------------------
1715
1736
1716 def system(self, cmd):
1737 def system(self, cmd):
1717 """Make a system call, using IPython."""
1738 """Make a system call, using IPython."""
1718 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1739 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1719
1740
1720 #-------------------------------------------------------------------------
1741 #-------------------------------------------------------------------------
1721 # Things related to aliases
1742 # Things related to aliases
1722 #-------------------------------------------------------------------------
1743 #-------------------------------------------------------------------------
1723
1744
1724 def init_alias(self):
1745 def init_alias(self):
1725 self.alias_manager = AliasManager(self, config=self.config)
1746 self.alias_manager = AliasManager(self, config=self.config)
1726 self.ns_table['alias'] = self.alias_manager.alias_table,
1747 self.ns_table['alias'] = self.alias_manager.alias_table,
1727
1748
1728 #-------------------------------------------------------------------------
1749 #-------------------------------------------------------------------------
1729 # Things related to the running of code
1750 # Things related to the running of code
1730 #-------------------------------------------------------------------------
1751 #-------------------------------------------------------------------------
1731
1752
1732 def ex(self, cmd):
1753 def ex(self, cmd):
1733 """Execute a normal python statement in user namespace."""
1754 """Execute a normal python statement in user namespace."""
1734 with nested(self.builtin_trap,):
1755 with nested(self.builtin_trap,):
1735 exec cmd in self.user_global_ns, self.user_ns
1756 exec cmd in self.user_global_ns, self.user_ns
1736
1757
1737 def ev(self, expr):
1758 def ev(self, expr):
1738 """Evaluate python expression expr in user namespace.
1759 """Evaluate python expression expr in user namespace.
1739
1760
1740 Returns the result of evaluation
1761 Returns the result of evaluation
1741 """
1762 """
1742 with nested(self.builtin_trap,):
1763 with nested(self.builtin_trap,):
1743 return eval(expr, self.user_global_ns, self.user_ns)
1764 return eval(expr, self.user_global_ns, self.user_ns)
1744
1765
1745 def mainloop(self, display_banner=None):
1766 def mainloop(self, display_banner=None):
1746 """Start the mainloop.
1767 """Start the mainloop.
1747
1768
1748 If an optional banner argument is given, it will override the
1769 If an optional banner argument is given, it will override the
1749 internally created default banner.
1770 internally created default banner.
1750 """
1771 """
1751
1772
1752 with nested(self.builtin_trap, self.display_trap):
1773 with nested(self.builtin_trap, self.display_trap):
1753
1774
1754 # if you run stuff with -c <cmd>, raw hist is not updated
1775 # if you run stuff with -c <cmd>, raw hist is not updated
1755 # ensure that it's in sync
1776 # ensure that it's in sync
1756 if len(self.input_hist) != len (self.input_hist_raw):
1777 if len(self.input_hist) != len (self.input_hist_raw):
1757 self.input_hist_raw = InputList(self.input_hist)
1778 self.input_hist_raw = InputList(self.input_hist)
1758
1779
1759 while 1:
1780 while 1:
1760 try:
1781 try:
1761 self.interact(display_banner=display_banner)
1782 self.interact(display_banner=display_banner)
1762 #self.interact_with_readline()
1783 #self.interact_with_readline()
1763 # XXX for testing of a readline-decoupled repl loop, call
1784 # XXX for testing of a readline-decoupled repl loop, call
1764 # interact_with_readline above
1785 # interact_with_readline above
1765 break
1786 break
1766 except KeyboardInterrupt:
1787 except KeyboardInterrupt:
1767 # this should not be necessary, but KeyboardInterrupt
1788 # this should not be necessary, but KeyboardInterrupt
1768 # handling seems rather unpredictable...
1789 # handling seems rather unpredictable...
1769 self.write("\nKeyboardInterrupt in interact()\n")
1790 self.write("\nKeyboardInterrupt in interact()\n")
1770
1791
1771 def interact_prompt(self):
1792 def interact_prompt(self):
1772 """ Print the prompt (in read-eval-print loop)
1793 """ Print the prompt (in read-eval-print loop)
1773
1794
1774 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1795 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1775 used in standard IPython flow.
1796 used in standard IPython flow.
1776 """
1797 """
1777 if self.more:
1798 if self.more:
1778 try:
1799 try:
1779 prompt = self.hooks.generate_prompt(True)
1800 prompt = self.hooks.generate_prompt(True)
1780 except:
1801 except:
1781 self.showtraceback()
1802 self.showtraceback()
1782 if self.autoindent:
1803 if self.autoindent:
1783 self.rl_do_indent = True
1804 self.rl_do_indent = True
1784
1805
1785 else:
1806 else:
1786 try:
1807 try:
1787 prompt = self.hooks.generate_prompt(False)
1808 prompt = self.hooks.generate_prompt(False)
1788 except:
1809 except:
1789 self.showtraceback()
1810 self.showtraceback()
1790 self.write(prompt)
1811 self.write(prompt)
1791
1812
1792 def interact_handle_input(self,line):
1813 def interact_handle_input(self,line):
1793 """ Handle the input line (in read-eval-print loop)
1814 """ Handle the input line (in read-eval-print loop)
1794
1815
1795 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1816 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1796 used in standard IPython flow.
1817 used in standard IPython flow.
1797 """
1818 """
1798 if line.lstrip() == line:
1819 if line.lstrip() == line:
1799 self.shadowhist.add(line.strip())
1820 self.shadowhist.add(line.strip())
1800 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1821 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1801
1822
1802 if line.strip():
1823 if line.strip():
1803 if self.more:
1824 if self.more:
1804 self.input_hist_raw[-1] += '%s\n' % line
1825 self.input_hist_raw[-1] += '%s\n' % line
1805 else:
1826 else:
1806 self.input_hist_raw.append('%s\n' % line)
1827 self.input_hist_raw.append('%s\n' % line)
1807
1828
1808
1829
1809 self.more = self.push_line(lineout)
1830 self.more = self.push_line(lineout)
1810 if (self.SyntaxTB.last_syntax_error and
1831 if (self.SyntaxTB.last_syntax_error and
1811 self.autoedit_syntax):
1832 self.autoedit_syntax):
1812 self.edit_syntax_error()
1833 self.edit_syntax_error()
1813
1834
1814 def interact_with_readline(self):
1835 def interact_with_readline(self):
1815 """ Demo of using interact_handle_input, interact_prompt
1836 """ Demo of using interact_handle_input, interact_prompt
1816
1837
1817 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1838 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1818 it should work like this.
1839 it should work like this.
1819 """
1840 """
1820 self.readline_startup_hook(self.pre_readline)
1841 self.readline_startup_hook(self.pre_readline)
1821 while not self.exit_now:
1842 while not self.exit_now:
1822 self.interact_prompt()
1843 self.interact_prompt()
1823 if self.more:
1844 if self.more:
1824 self.rl_do_indent = True
1845 self.rl_do_indent = True
1825 else:
1846 else:
1826 self.rl_do_indent = False
1847 self.rl_do_indent = False
1827 line = raw_input_original().decode(self.stdin_encoding)
1848 line = raw_input_original().decode(self.stdin_encoding)
1828 self.interact_handle_input(line)
1849 self.interact_handle_input(line)
1829
1850
1830 def interact(self, display_banner=None):
1851 def interact(self, display_banner=None):
1831 """Closely emulate the interactive Python console."""
1852 """Closely emulate the interactive Python console."""
1832
1853
1833 # batch run -> do not interact
1854 # batch run -> do not interact
1834 if self.exit_now:
1855 if self.exit_now:
1835 return
1856 return
1836
1857
1837 if display_banner is None:
1858 if display_banner is None:
1838 display_banner = self.display_banner
1859 display_banner = self.display_banner
1839 if display_banner:
1860 if display_banner:
1840 self.show_banner()
1861 self.show_banner()
1841
1862
1842 more = 0
1863 more = 0
1843
1864
1844 # Mark activity in the builtins
1865 # Mark activity in the builtins
1845 __builtin__.__dict__['__IPYTHON__active'] += 1
1866 __builtin__.__dict__['__IPYTHON__active'] += 1
1846
1867
1847 if self.has_readline:
1868 if self.has_readline:
1848 self.readline_startup_hook(self.pre_readline)
1869 self.readline_startup_hook(self.pre_readline)
1849 # exit_now is set by a call to %Exit or %Quit, through the
1870 # exit_now is set by a call to %Exit or %Quit, through the
1850 # ask_exit callback.
1871 # ask_exit callback.
1851
1872
1852 while not self.exit_now:
1873 while not self.exit_now:
1853 self.hooks.pre_prompt_hook()
1874 self.hooks.pre_prompt_hook()
1854 if more:
1875 if more:
1855 try:
1876 try:
1856 prompt = self.hooks.generate_prompt(True)
1877 prompt = self.hooks.generate_prompt(True)
1857 except:
1878 except:
1858 self.showtraceback()
1879 self.showtraceback()
1859 if self.autoindent:
1880 if self.autoindent:
1860 self.rl_do_indent = True
1881 self.rl_do_indent = True
1861
1882
1862 else:
1883 else:
1863 try:
1884 try:
1864 prompt = self.hooks.generate_prompt(False)
1885 prompt = self.hooks.generate_prompt(False)
1865 except:
1886 except:
1866 self.showtraceback()
1887 self.showtraceback()
1867 try:
1888 try:
1868 line = self.raw_input(prompt, more)
1889 line = self.raw_input(prompt, more)
1869 if self.exit_now:
1890 if self.exit_now:
1870 # quick exit on sys.std[in|out] close
1891 # quick exit on sys.std[in|out] close
1871 break
1892 break
1872 if self.autoindent:
1893 if self.autoindent:
1873 self.rl_do_indent = False
1894 self.rl_do_indent = False
1874
1895
1875 except KeyboardInterrupt:
1896 except KeyboardInterrupt:
1876 #double-guard against keyboardinterrupts during kbdint handling
1897 #double-guard against keyboardinterrupts during kbdint handling
1877 try:
1898 try:
1878 self.write('\nKeyboardInterrupt\n')
1899 self.write('\nKeyboardInterrupt\n')
1879 self.resetbuffer()
1900 self.resetbuffer()
1880 # keep cache in sync with the prompt counter:
1901 # keep cache in sync with the prompt counter:
1881 self.outputcache.prompt_count -= 1
1902 self.outputcache.prompt_count -= 1
1882
1903
1883 if self.autoindent:
1904 if self.autoindent:
1884 self.indent_current_nsp = 0
1905 self.indent_current_nsp = 0
1885 more = 0
1906 more = 0
1886 except KeyboardInterrupt:
1907 except KeyboardInterrupt:
1887 pass
1908 pass
1888 except EOFError:
1909 except EOFError:
1889 if self.autoindent:
1910 if self.autoindent:
1890 self.rl_do_indent = False
1911 self.rl_do_indent = False
1891 if self.has_readline:
1912 if self.has_readline:
1892 self.readline_startup_hook(None)
1913 self.readline_startup_hook(None)
1893 self.write('\n')
1914 self.write('\n')
1894 self.exit()
1915 self.exit()
1895 except bdb.BdbQuit:
1916 except bdb.BdbQuit:
1896 warn('The Python debugger has exited with a BdbQuit exception.\n'
1917 warn('The Python debugger has exited with a BdbQuit exception.\n'
1897 'Because of how pdb handles the stack, it is impossible\n'
1918 'Because of how pdb handles the stack, it is impossible\n'
1898 'for IPython to properly format this particular exception.\n'
1919 'for IPython to properly format this particular exception.\n'
1899 'IPython will resume normal operation.')
1920 'IPython will resume normal operation.')
1900 except:
1921 except:
1901 # exceptions here are VERY RARE, but they can be triggered
1922 # exceptions here are VERY RARE, but they can be triggered
1902 # asynchronously by signal handlers, for example.
1923 # asynchronously by signal handlers, for example.
1903 self.showtraceback()
1924 self.showtraceback()
1904 else:
1925 else:
1905 more = self.push_line(line)
1926 more = self.push_line(line)
1906 if (self.SyntaxTB.last_syntax_error and
1927 if (self.SyntaxTB.last_syntax_error and
1907 self.autoedit_syntax):
1928 self.autoedit_syntax):
1908 self.edit_syntax_error()
1929 self.edit_syntax_error()
1909
1930
1910 # We are off again...
1931 # We are off again...
1911 __builtin__.__dict__['__IPYTHON__active'] -= 1
1932 __builtin__.__dict__['__IPYTHON__active'] -= 1
1912
1933
1913 # Turn off the exit flag, so the mainloop can be restarted if desired
1934 # Turn off the exit flag, so the mainloop can be restarted if desired
1914 self.exit_now = False
1935 self.exit_now = False
1915
1936
1916 def safe_execfile(self, fname, *where, **kw):
1937 def safe_execfile(self, fname, *where, **kw):
1917 """A safe version of the builtin execfile().
1938 """A safe version of the builtin execfile().
1918
1939
1919 This version will never throw an exception, but instead print
1940 This version will never throw an exception, but instead print
1920 helpful error messages to the screen. This only works on pure
1941 helpful error messages to the screen. This only works on pure
1921 Python files with the .py extension.
1942 Python files with the .py extension.
1922
1943
1923 Parameters
1944 Parameters
1924 ----------
1945 ----------
1925 fname : string
1946 fname : string
1926 The name of the file to be executed.
1947 The name of the file to be executed.
1927 where : tuple
1948 where : tuple
1928 One or two namespaces, passed to execfile() as (globals,locals).
1949 One or two namespaces, passed to execfile() as (globals,locals).
1929 If only one is given, it is passed as both.
1950 If only one is given, it is passed as both.
1930 exit_ignore : bool (False)
1951 exit_ignore : bool (False)
1931 If True, then silence SystemExit for non-zero status (it is always
1952 If True, then silence SystemExit for non-zero status (it is always
1932 silenced for zero status, as it is so common).
1953 silenced for zero status, as it is so common).
1933 """
1954 """
1934 kw.setdefault('exit_ignore', False)
1955 kw.setdefault('exit_ignore', False)
1935
1956
1936 fname = os.path.abspath(os.path.expanduser(fname))
1957 fname = os.path.abspath(os.path.expanduser(fname))
1937
1958
1938 # Make sure we have a .py file
1959 # Make sure we have a .py file
1939 if not fname.endswith('.py'):
1960 if not fname.endswith('.py'):
1940 warn('File must end with .py to be run using execfile: <%s>' % fname)
1961 warn('File must end with .py to be run using execfile: <%s>' % fname)
1941
1962
1942 # Make sure we can open the file
1963 # Make sure we can open the file
1943 try:
1964 try:
1944 with open(fname) as thefile:
1965 with open(fname) as thefile:
1945 pass
1966 pass
1946 except:
1967 except:
1947 warn('Could not open file <%s> for safe execution.' % fname)
1968 warn('Could not open file <%s> for safe execution.' % fname)
1948 return
1969 return
1949
1970
1950 # Find things also in current directory. This is needed to mimic the
1971 # Find things also in current directory. This is needed to mimic the
1951 # behavior of running a script from the system command line, where
1972 # behavior of running a script from the system command line, where
1952 # Python inserts the script's directory into sys.path
1973 # Python inserts the script's directory into sys.path
1953 dname = os.path.dirname(fname)
1974 dname = os.path.dirname(fname)
1954
1975
1955 with prepended_to_syspath(dname):
1976 with prepended_to_syspath(dname):
1956 try:
1977 try:
1957 execfile(fname,*where)
1978 execfile(fname,*where)
1958 except SystemExit, status:
1979 except SystemExit, status:
1959 # If the call was made with 0 or None exit status (sys.exit(0)
1980 # If the call was made with 0 or None exit status (sys.exit(0)
1960 # or sys.exit() ), don't bother showing a traceback, as both of
1981 # or sys.exit() ), don't bother showing a traceback, as both of
1961 # these are considered normal by the OS:
1982 # these are considered normal by the OS:
1962 # > python -c'import sys;sys.exit(0)'; echo $?
1983 # > python -c'import sys;sys.exit(0)'; echo $?
1963 # 0
1984 # 0
1964 # > python -c'import sys;sys.exit()'; echo $?
1985 # > python -c'import sys;sys.exit()'; echo $?
1965 # 0
1986 # 0
1966 # For other exit status, we show the exception unless
1987 # For other exit status, we show the exception unless
1967 # explicitly silenced, but only in short form.
1988 # explicitly silenced, but only in short form.
1968 if status.code not in (0, None) and not kw['exit_ignore']:
1989 if status.code not in (0, None) and not kw['exit_ignore']:
1969 self.showtraceback(exception_only=True)
1990 self.showtraceback(exception_only=True)
1970 except:
1991 except:
1971 self.showtraceback()
1992 self.showtraceback()
1972
1993
1973 def safe_execfile_ipy(self, fname):
1994 def safe_execfile_ipy(self, fname):
1974 """Like safe_execfile, but for .ipy files with IPython syntax.
1995 """Like safe_execfile, but for .ipy files with IPython syntax.
1975
1996
1976 Parameters
1997 Parameters
1977 ----------
1998 ----------
1978 fname : str
1999 fname : str
1979 The name of the file to execute. The filename must have a
2000 The name of the file to execute. The filename must have a
1980 .ipy extension.
2001 .ipy extension.
1981 """
2002 """
1982 fname = os.path.abspath(os.path.expanduser(fname))
2003 fname = os.path.abspath(os.path.expanduser(fname))
1983
2004
1984 # Make sure we have a .py file
2005 # Make sure we have a .py file
1985 if not fname.endswith('.ipy'):
2006 if not fname.endswith('.ipy'):
1986 warn('File must end with .py to be run using execfile: <%s>' % fname)
2007 warn('File must end with .py to be run using execfile: <%s>' % fname)
1987
2008
1988 # Make sure we can open the file
2009 # Make sure we can open the file
1989 try:
2010 try:
1990 with open(fname) as thefile:
2011 with open(fname) as thefile:
1991 pass
2012 pass
1992 except:
2013 except:
1993 warn('Could not open file <%s> for safe execution.' % fname)
2014 warn('Could not open file <%s> for safe execution.' % fname)
1994 return
2015 return
1995
2016
1996 # Find things also in current directory. This is needed to mimic the
2017 # Find things also in current directory. This is needed to mimic the
1997 # behavior of running a script from the system command line, where
2018 # behavior of running a script from the system command line, where
1998 # Python inserts the script's directory into sys.path
2019 # Python inserts the script's directory into sys.path
1999 dname = os.path.dirname(fname)
2020 dname = os.path.dirname(fname)
2000
2021
2001 with prepended_to_syspath(dname):
2022 with prepended_to_syspath(dname):
2002 try:
2023 try:
2003 with open(fname) as thefile:
2024 with open(fname) as thefile:
2004 script = thefile.read()
2025 script = thefile.read()
2005 # self.runlines currently captures all exceptions
2026 # self.runlines currently captures all exceptions
2006 # raise in user code. It would be nice if there were
2027 # raise in user code. It would be nice if there were
2007 # versions of runlines, execfile that did raise, so
2028 # versions of runlines, execfile that did raise, so
2008 # we could catch the errors.
2029 # we could catch the errors.
2009 self.runlines(script, clean=True)
2030 self.runlines(script, clean=True)
2010 except:
2031 except:
2011 self.showtraceback()
2032 self.showtraceback()
2012 warn('Unknown failure executing file: <%s>' % fname)
2033 warn('Unknown failure executing file: <%s>' % fname)
2013
2034
2014 def _is_secondary_block_start(self, s):
2035 def _is_secondary_block_start(self, s):
2015 if not s.endswith(':'):
2036 if not s.endswith(':'):
2016 return False
2037 return False
2017 if (s.startswith('elif') or
2038 if (s.startswith('elif') or
2018 s.startswith('else') or
2039 s.startswith('else') or
2019 s.startswith('except') or
2040 s.startswith('except') or
2020 s.startswith('finally')):
2041 s.startswith('finally')):
2021 return True
2042 return True
2022
2043
2023 def cleanup_ipy_script(self, script):
2044 def cleanup_ipy_script(self, script):
2024 """Make a script safe for self.runlines()
2045 """Make a script safe for self.runlines()
2025
2046
2026 Currently, IPython is lines based, with blocks being detected by
2047 Currently, IPython is lines based, with blocks being detected by
2027 empty lines. This is a problem for block based scripts that may
2048 empty lines. This is a problem for block based scripts that may
2028 not have empty lines after blocks. This script adds those empty
2049 not have empty lines after blocks. This script adds those empty
2029 lines to make scripts safe for running in the current line based
2050 lines to make scripts safe for running in the current line based
2030 IPython.
2051 IPython.
2031 """
2052 """
2032 res = []
2053 res = []
2033 lines = script.splitlines()
2054 lines = script.splitlines()
2034 level = 0
2055 level = 0
2035
2056
2036 for l in lines:
2057 for l in lines:
2037 lstripped = l.lstrip()
2058 lstripped = l.lstrip()
2038 stripped = l.strip()
2059 stripped = l.strip()
2039 if not stripped:
2060 if not stripped:
2040 continue
2061 continue
2041 newlevel = len(l) - len(lstripped)
2062 newlevel = len(l) - len(lstripped)
2042 if level > 0 and newlevel == 0 and \
2063 if level > 0 and newlevel == 0 and \
2043 not self._is_secondary_block_start(stripped):
2064 not self._is_secondary_block_start(stripped):
2044 # add empty line
2065 # add empty line
2045 res.append('')
2066 res.append('')
2046 res.append(l)
2067 res.append(l)
2047 level = newlevel
2068 level = newlevel
2048
2069
2049 return '\n'.join(res) + '\n'
2070 return '\n'.join(res) + '\n'
2050
2071
2051 def runlines(self, lines, clean=False):
2072 def runlines(self, lines, clean=False):
2052 """Run a string of one or more lines of source.
2073 """Run a string of one or more lines of source.
2053
2074
2054 This method is capable of running a string containing multiple source
2075 This method is capable of running a string containing multiple source
2055 lines, as if they had been entered at the IPython prompt. Since it
2076 lines, as if they had been entered at the IPython prompt. Since it
2056 exposes IPython's processing machinery, the given strings can contain
2077 exposes IPython's processing machinery, the given strings can contain
2057 magic calls (%magic), special shell access (!cmd), etc.
2078 magic calls (%magic), special shell access (!cmd), etc.
2058 """
2079 """
2059
2080
2060 if isinstance(lines, (list, tuple)):
2081 if isinstance(lines, (list, tuple)):
2061 lines = '\n'.join(lines)
2082 lines = '\n'.join(lines)
2062
2083
2063 if clean:
2084 if clean:
2064 lines = self.cleanup_ipy_script(lines)
2085 lines = self.cleanup_ipy_script(lines)
2065
2086
2066 # We must start with a clean buffer, in case this is run from an
2087 # We must start with a clean buffer, in case this is run from an
2067 # interactive IPython session (via a magic, for example).
2088 # interactive IPython session (via a magic, for example).
2068 self.resetbuffer()
2089 self.resetbuffer()
2069 lines = lines.splitlines()
2090 lines = lines.splitlines()
2070 more = 0
2091 more = 0
2071
2092
2072 with nested(self.builtin_trap, self.display_trap):
2093 with nested(self.builtin_trap, self.display_trap):
2073 for line in lines:
2094 for line in lines:
2074 # skip blank lines so we don't mess up the prompt counter, but do
2095 # skip blank lines so we don't mess up the prompt counter, but do
2075 # NOT skip even a blank line if we are in a code block (more is
2096 # NOT skip even a blank line if we are in a code block (more is
2076 # true)
2097 # true)
2077
2098
2078 if line or more:
2099 if line or more:
2079 # push to raw history, so hist line numbers stay in sync
2100 # push to raw history, so hist line numbers stay in sync
2080 self.input_hist_raw.append("# " + line + "\n")
2101 self.input_hist_raw.append("# " + line + "\n")
2081 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2102 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2082 more = self.push_line(prefiltered)
2103 more = self.push_line(prefiltered)
2083 # IPython's runsource returns None if there was an error
2104 # IPython's runsource returns None if there was an error
2084 # compiling the code. This allows us to stop processing right
2105 # compiling the code. This allows us to stop processing right
2085 # away, so the user gets the error message at the right place.
2106 # away, so the user gets the error message at the right place.
2086 if more is None:
2107 if more is None:
2087 break
2108 break
2088 else:
2109 else:
2089 self.input_hist_raw.append("\n")
2110 self.input_hist_raw.append("\n")
2090 # final newline in case the input didn't have it, so that the code
2111 # final newline in case the input didn't have it, so that the code
2091 # actually does get executed
2112 # actually does get executed
2092 if more:
2113 if more:
2093 self.push_line('\n')
2114 self.push_line('\n')
2094
2115
2095 def runsource(self, source, filename='<input>', symbol='single'):
2116 def runsource(self, source, filename='<input>', symbol='single'):
2096 """Compile and run some source in the interpreter.
2117 """Compile and run some source in the interpreter.
2097
2118
2098 Arguments are as for compile_command().
2119 Arguments are as for compile_command().
2099
2120
2100 One several things can happen:
2121 One several things can happen:
2101
2122
2102 1) The input is incorrect; compile_command() raised an
2123 1) The input is incorrect; compile_command() raised an
2103 exception (SyntaxError or OverflowError). A syntax traceback
2124 exception (SyntaxError or OverflowError). A syntax traceback
2104 will be printed by calling the showsyntaxerror() method.
2125 will be printed by calling the showsyntaxerror() method.
2105
2126
2106 2) The input is incomplete, and more input is required;
2127 2) The input is incomplete, and more input is required;
2107 compile_command() returned None. Nothing happens.
2128 compile_command() returned None. Nothing happens.
2108
2129
2109 3) The input is complete; compile_command() returned a code
2130 3) The input is complete; compile_command() returned a code
2110 object. The code is executed by calling self.runcode() (which
2131 object. The code is executed by calling self.runcode() (which
2111 also handles run-time exceptions, except for SystemExit).
2132 also handles run-time exceptions, except for SystemExit).
2112
2133
2113 The return value is:
2134 The return value is:
2114
2135
2115 - True in case 2
2136 - True in case 2
2116
2137
2117 - False in the other cases, unless an exception is raised, where
2138 - False in the other cases, unless an exception is raised, where
2118 None is returned instead. This can be used by external callers to
2139 None is returned instead. This can be used by external callers to
2119 know whether to continue feeding input or not.
2140 know whether to continue feeding input or not.
2120
2141
2121 The return value can be used to decide whether to use sys.ps1 or
2142 The return value can be used to decide whether to use sys.ps1 or
2122 sys.ps2 to prompt the next line."""
2143 sys.ps2 to prompt the next line."""
2123
2144
2124 # if the source code has leading blanks, add 'if 1:\n' to it
2145 # if the source code has leading blanks, add 'if 1:\n' to it
2125 # this allows execution of indented pasted code. It is tempting
2146 # this allows execution of indented pasted code. It is tempting
2126 # to add '\n' at the end of source to run commands like ' a=1'
2147 # to add '\n' at the end of source to run commands like ' a=1'
2127 # directly, but this fails for more complicated scenarios
2148 # directly, but this fails for more complicated scenarios
2128 source=source.encode(self.stdin_encoding)
2149 source=source.encode(self.stdin_encoding)
2129 if source[:1] in [' ', '\t']:
2150 if source[:1] in [' ', '\t']:
2130 source = 'if 1:\n%s' % source
2151 source = 'if 1:\n%s' % source
2131
2152
2132 try:
2153 try:
2133 code = self.compile(source,filename,symbol)
2154 code = self.compile(source,filename,symbol)
2134 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2155 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2135 # Case 1
2156 # Case 1
2136 self.showsyntaxerror(filename)
2157 self.showsyntaxerror(filename)
2137 return None
2158 return None
2138
2159
2139 if code is None:
2160 if code is None:
2140 # Case 2
2161 # Case 2
2141 return True
2162 return True
2142
2163
2143 # Case 3
2164 # Case 3
2144 # We store the code object so that threaded shells and
2165 # We store the code object so that threaded shells and
2145 # custom exception handlers can access all this info if needed.
2166 # custom exception handlers can access all this info if needed.
2146 # The source corresponding to this can be obtained from the
2167 # The source corresponding to this can be obtained from the
2147 # buffer attribute as '\n'.join(self.buffer).
2168 # buffer attribute as '\n'.join(self.buffer).
2148 self.code_to_run = code
2169 self.code_to_run = code
2149 # now actually execute the code object
2170 # now actually execute the code object
2150 if self.runcode(code) == 0:
2171 if self.runcode(code) == 0:
2151 return False
2172 return False
2152 else:
2173 else:
2153 return None
2174 return None
2154
2175
2155 def runcode(self,code_obj):
2176 def runcode(self,code_obj):
2156 """Execute a code object.
2177 """Execute a code object.
2157
2178
2158 When an exception occurs, self.showtraceback() is called to display a
2179 When an exception occurs, self.showtraceback() is called to display a
2159 traceback.
2180 traceback.
2160
2181
2161 Return value: a flag indicating whether the code to be run completed
2182 Return value: a flag indicating whether the code to be run completed
2162 successfully:
2183 successfully:
2163
2184
2164 - 0: successful execution.
2185 - 0: successful execution.
2165 - 1: an error occurred.
2186 - 1: an error occurred.
2166 """
2187 """
2167
2188
2168 # Set our own excepthook in case the user code tries to call it
2189 # Set our own excepthook in case the user code tries to call it
2169 # directly, so that the IPython crash handler doesn't get triggered
2190 # directly, so that the IPython crash handler doesn't get triggered
2170 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2191 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2171
2192
2172 # we save the original sys.excepthook in the instance, in case config
2193 # we save the original sys.excepthook in the instance, in case config
2173 # code (such as magics) needs access to it.
2194 # code (such as magics) needs access to it.
2174 self.sys_excepthook = old_excepthook
2195 self.sys_excepthook = old_excepthook
2175 outflag = 1 # happens in more places, so it's easier as default
2196 outflag = 1 # happens in more places, so it's easier as default
2176 try:
2197 try:
2177 try:
2198 try:
2178 self.hooks.pre_runcode_hook()
2199 self.hooks.pre_runcode_hook()
2179 exec code_obj in self.user_global_ns, self.user_ns
2200 exec code_obj in self.user_global_ns, self.user_ns
2180 finally:
2201 finally:
2181 # Reset our crash handler in place
2202 # Reset our crash handler in place
2182 sys.excepthook = old_excepthook
2203 sys.excepthook = old_excepthook
2183 except SystemExit:
2204 except SystemExit:
2184 self.resetbuffer()
2205 self.resetbuffer()
2185 self.showtraceback(exception_only=True)
2206 self.showtraceback(exception_only=True)
2186 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2207 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2187 except self.custom_exceptions:
2208 except self.custom_exceptions:
2188 etype,value,tb = sys.exc_info()
2209 etype,value,tb = sys.exc_info()
2189 self.CustomTB(etype,value,tb)
2210 self.CustomTB(etype,value,tb)
2190 except:
2211 except:
2191 self.showtraceback()
2212 self.showtraceback()
2192 else:
2213 else:
2193 outflag = 0
2214 outflag = 0
2194 if softspace(sys.stdout, 0):
2215 if softspace(sys.stdout, 0):
2195 print
2216 print
2196 # Flush out code object which has been run (and source)
2217 # Flush out code object which has been run (and source)
2197 self.code_to_run = None
2218 self.code_to_run = None
2198 return outflag
2219 return outflag
2199
2220
2200 def push_line(self, line):
2221 def push_line(self, line):
2201 """Push a line to the interpreter.
2222 """Push a line to the interpreter.
2202
2223
2203 The line should not have a trailing newline; it may have
2224 The line should not have a trailing newline; it may have
2204 internal newlines. The line is appended to a buffer and the
2225 internal newlines. The line is appended to a buffer and the
2205 interpreter's runsource() method is called with the
2226 interpreter's runsource() method is called with the
2206 concatenated contents of the buffer as source. If this
2227 concatenated contents of the buffer as source. If this
2207 indicates that the command was executed or invalid, the buffer
2228 indicates that the command was executed or invalid, the buffer
2208 is reset; otherwise, the command is incomplete, and the buffer
2229 is reset; otherwise, the command is incomplete, and the buffer
2209 is left as it was after the line was appended. The return
2230 is left as it was after the line was appended. The return
2210 value is 1 if more input is required, 0 if the line was dealt
2231 value is 1 if more input is required, 0 if the line was dealt
2211 with in some way (this is the same as runsource()).
2232 with in some way (this is the same as runsource()).
2212 """
2233 """
2213
2234
2214 # autoindent management should be done here, and not in the
2235 # autoindent management should be done here, and not in the
2215 # interactive loop, since that one is only seen by keyboard input. We
2236 # interactive loop, since that one is only seen by keyboard input. We
2216 # need this done correctly even for code run via runlines (which uses
2237 # need this done correctly even for code run via runlines (which uses
2217 # push).
2238 # push).
2218
2239
2219 #print 'push line: <%s>' % line # dbg
2240 #print 'push line: <%s>' % line # dbg
2220 for subline in line.splitlines():
2241 for subline in line.splitlines():
2221 self._autoindent_update(subline)
2242 self._autoindent_update(subline)
2222 self.buffer.append(line)
2243 self.buffer.append(line)
2223 more = self.runsource('\n'.join(self.buffer), self.filename)
2244 more = self.runsource('\n'.join(self.buffer), self.filename)
2224 if not more:
2245 if not more:
2225 self.resetbuffer()
2246 self.resetbuffer()
2226 return more
2247 return more
2227
2248
2228 def _autoindent_update(self,line):
2249 def _autoindent_update(self,line):
2229 """Keep track of the indent level."""
2250 """Keep track of the indent level."""
2230
2251
2231 #debugx('line')
2252 #debugx('line')
2232 #debugx('self.indent_current_nsp')
2253 #debugx('self.indent_current_nsp')
2233 if self.autoindent:
2254 if self.autoindent:
2234 if line:
2255 if line:
2235 inisp = num_ini_spaces(line)
2256 inisp = num_ini_spaces(line)
2236 if inisp < self.indent_current_nsp:
2257 if inisp < self.indent_current_nsp:
2237 self.indent_current_nsp = inisp
2258 self.indent_current_nsp = inisp
2238
2259
2239 if line[-1] == ':':
2260 if line[-1] == ':':
2240 self.indent_current_nsp += 4
2261 self.indent_current_nsp += 4
2241 elif dedent_re.match(line):
2262 elif dedent_re.match(line):
2242 self.indent_current_nsp -= 4
2263 self.indent_current_nsp -= 4
2243 else:
2264 else:
2244 self.indent_current_nsp = 0
2265 self.indent_current_nsp = 0
2245
2266
2246 def resetbuffer(self):
2267 def resetbuffer(self):
2247 """Reset the input buffer."""
2268 """Reset the input buffer."""
2248 self.buffer[:] = []
2269 self.buffer[:] = []
2249
2270
2250 def raw_input(self,prompt='',continue_prompt=False):
2271 def raw_input(self,prompt='',continue_prompt=False):
2251 """Write a prompt and read a line.
2272 """Write a prompt and read a line.
2252
2273
2253 The returned line does not include the trailing newline.
2274 The returned line does not include the trailing newline.
2254 When the user enters the EOF key sequence, EOFError is raised.
2275 When the user enters the EOF key sequence, EOFError is raised.
2255
2276
2256 Optional inputs:
2277 Optional inputs:
2257
2278
2258 - prompt(''): a string to be printed to prompt the user.
2279 - prompt(''): a string to be printed to prompt the user.
2259
2280
2260 - continue_prompt(False): whether this line is the first one or a
2281 - continue_prompt(False): whether this line is the first one or a
2261 continuation in a sequence of inputs.
2282 continuation in a sequence of inputs.
2262 """
2283 """
2263 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2284 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2264
2285
2265 # Code run by the user may have modified the readline completer state.
2286 # Code run by the user may have modified the readline completer state.
2266 # We must ensure that our completer is back in place.
2287 # We must ensure that our completer is back in place.
2267
2288
2268 if self.has_readline:
2289 if self.has_readline:
2269 self.set_completer()
2290 self.set_completer()
2270
2291
2271 try:
2292 try:
2272 line = raw_input_original(prompt).decode(self.stdin_encoding)
2293 line = raw_input_original(prompt).decode(self.stdin_encoding)
2273 except ValueError:
2294 except ValueError:
2274 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2295 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2275 " or sys.stdout.close()!\nExiting IPython!")
2296 " or sys.stdout.close()!\nExiting IPython!")
2276 self.ask_exit()
2297 self.ask_exit()
2277 return ""
2298 return ""
2278
2299
2279 # Try to be reasonably smart about not re-indenting pasted input more
2300 # Try to be reasonably smart about not re-indenting pasted input more
2280 # than necessary. We do this by trimming out the auto-indent initial
2301 # than necessary. We do this by trimming out the auto-indent initial
2281 # spaces, if the user's actual input started itself with whitespace.
2302 # spaces, if the user's actual input started itself with whitespace.
2282 #debugx('self.buffer[-1]')
2303 #debugx('self.buffer[-1]')
2283
2304
2284 if self.autoindent:
2305 if self.autoindent:
2285 if num_ini_spaces(line) > self.indent_current_nsp:
2306 if num_ini_spaces(line) > self.indent_current_nsp:
2286 line = line[self.indent_current_nsp:]
2307 line = line[self.indent_current_nsp:]
2287 self.indent_current_nsp = 0
2308 self.indent_current_nsp = 0
2288
2309
2289 # store the unfiltered input before the user has any chance to modify
2310 # store the unfiltered input before the user has any chance to modify
2290 # it.
2311 # it.
2291 if line.strip():
2312 if line.strip():
2292 if continue_prompt:
2313 if continue_prompt:
2293 self.input_hist_raw[-1] += '%s\n' % line
2314 self.input_hist_raw[-1] += '%s\n' % line
2294 if self.has_readline and self.readline_use:
2315 if self.has_readline and self.readline_use:
2295 try:
2316 try:
2296 histlen = self.readline.get_current_history_length()
2317 histlen = self.readline.get_current_history_length()
2297 if histlen > 1:
2318 if histlen > 1:
2298 newhist = self.input_hist_raw[-1].rstrip()
2319 newhist = self.input_hist_raw[-1].rstrip()
2299 self.readline.remove_history_item(histlen-1)
2320 self.readline.remove_history_item(histlen-1)
2300 self.readline.replace_history_item(histlen-2,
2321 self.readline.replace_history_item(histlen-2,
2301 newhist.encode(self.stdin_encoding))
2322 newhist.encode(self.stdin_encoding))
2302 except AttributeError:
2323 except AttributeError:
2303 pass # re{move,place}_history_item are new in 2.4.
2324 pass # re{move,place}_history_item are new in 2.4.
2304 else:
2325 else:
2305 self.input_hist_raw.append('%s\n' % line)
2326 self.input_hist_raw.append('%s\n' % line)
2306 # only entries starting at first column go to shadow history
2327 # only entries starting at first column go to shadow history
2307 if line.lstrip() == line:
2328 if line.lstrip() == line:
2308 self.shadowhist.add(line.strip())
2329 self.shadowhist.add(line.strip())
2309 elif not continue_prompt:
2330 elif not continue_prompt:
2310 self.input_hist_raw.append('\n')
2331 self.input_hist_raw.append('\n')
2311 try:
2332 try:
2312 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2333 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2313 except:
2334 except:
2314 # blanket except, in case a user-defined prefilter crashes, so it
2335 # blanket except, in case a user-defined prefilter crashes, so it
2315 # can't take all of ipython with it.
2336 # can't take all of ipython with it.
2316 self.showtraceback()
2337 self.showtraceback()
2317 return ''
2338 return ''
2318 else:
2339 else:
2319 return lineout
2340 return lineout
2320
2341
2321 #-------------------------------------------------------------------------
2342 #-------------------------------------------------------------------------
2322 # Working with components
2343 # Working with components
2323 #-------------------------------------------------------------------------
2344 #-------------------------------------------------------------------------
2324
2345
2325 def get_component(self, name=None, klass=None):
2346 def get_component(self, name=None, klass=None):
2326 """Fetch a component by name and klass in my tree."""
2347 """Fetch a component by name and klass in my tree."""
2327 c = Component.get_instances(root=self, name=name, klass=klass)
2348 c = Component.get_instances(root=self, name=name, klass=klass)
2328 if len(c) == 0:
2349 if len(c) == 0:
2329 return None
2350 return None
2330 if len(c) == 1:
2351 if len(c) == 1:
2331 return c[0]
2352 return c[0]
2332 else:
2353 else:
2333 return c
2354 return c
2334
2355
2335 #-------------------------------------------------------------------------
2356 #-------------------------------------------------------------------------
2336 # IPython extensions
2357 # IPython extensions
2337 #-------------------------------------------------------------------------
2358 #-------------------------------------------------------------------------
2338
2359
2339 def load_extension(self, module_str):
2360 def load_extension(self, module_str):
2340 """Load an IPython extension by its module name.
2361 """Load an IPython extension by its module name.
2341
2362
2342 An IPython extension is an importable Python module that has
2363 An IPython extension is an importable Python module that has
2343 a function with the signature::
2364 a function with the signature::
2344
2365
2345 def load_ipython_extension(ipython):
2366 def load_ipython_extension(ipython):
2346 # Do things with ipython
2367 # Do things with ipython
2347
2368
2348 This function is called after your extension is imported and the
2369 This function is called after your extension is imported and the
2349 currently active :class:`InteractiveShell` instance is passed as
2370 currently active :class:`InteractiveShell` instance is passed as
2350 the only argument. You can do anything you want with IPython at
2371 the only argument. You can do anything you want with IPython at
2351 that point, including defining new magic and aliases, adding new
2372 that point, including defining new magic and aliases, adding new
2352 components, etc.
2373 components, etc.
2353
2374
2354 The :func:`load_ipython_extension` will be called again is you
2375 The :func:`load_ipython_extension` will be called again is you
2355 load or reload the extension again. It is up to the extension
2376 load or reload the extension again. It is up to the extension
2356 author to add code to manage that.
2377 author to add code to manage that.
2357
2378
2358 You can put your extension modules anywhere you want, as long as
2379 You can put your extension modules anywhere you want, as long as
2359 they can be imported by Python's standard import mechanism. However,
2380 they can be imported by Python's standard import mechanism. However,
2360 to make it easy to write extensions, you can also put your extensions
2381 to make it easy to write extensions, you can also put your extensions
2361 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2382 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2362 is added to ``sys.path`` automatically.
2383 is added to ``sys.path`` automatically.
2363
2384
2364 If :func:`load_ipython_extension` returns anything, this function
2385 If :func:`load_ipython_extension` returns anything, this function
2365 will return that object.
2386 will return that object.
2366 """
2387 """
2367 from IPython.utils.syspathcontext import prepended_to_syspath
2388 from IPython.utils.syspathcontext import prepended_to_syspath
2368
2389
2369 if module_str not in sys.modules:
2390 if module_str not in sys.modules:
2370 with prepended_to_syspath(self.ipython_extension_dir):
2391 with prepended_to_syspath(self.ipython_extension_dir):
2371 __import__(module_str)
2392 __import__(module_str)
2372 mod = sys.modules[module_str]
2393 mod = sys.modules[module_str]
2373 return self._call_load_ipython_extension(mod)
2394 return self._call_load_ipython_extension(mod)
2374
2395
2375 def unload_extension(self, module_str):
2396 def unload_extension(self, module_str):
2376 """Unload an IPython extension by its module name.
2397 """Unload an IPython extension by its module name.
2377
2398
2378 This function looks up the extension's name in ``sys.modules`` and
2399 This function looks up the extension's name in ``sys.modules`` and
2379 simply calls ``mod.unload_ipython_extension(self)``.
2400 simply calls ``mod.unload_ipython_extension(self)``.
2380 """
2401 """
2381 if module_str in sys.modules:
2402 if module_str in sys.modules:
2382 mod = sys.modules[module_str]
2403 mod = sys.modules[module_str]
2383 self._call_unload_ipython_extension(mod)
2404 self._call_unload_ipython_extension(mod)
2384
2405
2385 def reload_extension(self, module_str):
2406 def reload_extension(self, module_str):
2386 """Reload an IPython extension by calling reload.
2407 """Reload an IPython extension by calling reload.
2387
2408
2388 If the module has not been loaded before,
2409 If the module has not been loaded before,
2389 :meth:`InteractiveShell.load_extension` is called. Otherwise
2410 :meth:`InteractiveShell.load_extension` is called. Otherwise
2390 :func:`reload` is called and then the :func:`load_ipython_extension`
2411 :func:`reload` is called and then the :func:`load_ipython_extension`
2391 function of the module, if it exists is called.
2412 function of the module, if it exists is called.
2392 """
2413 """
2393 from IPython.utils.syspathcontext import prepended_to_syspath
2414 from IPython.utils.syspathcontext import prepended_to_syspath
2394
2415
2395 with prepended_to_syspath(self.ipython_extension_dir):
2416 with prepended_to_syspath(self.ipython_extension_dir):
2396 if module_str in sys.modules:
2417 if module_str in sys.modules:
2397 mod = sys.modules[module_str]
2418 mod = sys.modules[module_str]
2398 reload(mod)
2419 reload(mod)
2399 self._call_load_ipython_extension(mod)
2420 self._call_load_ipython_extension(mod)
2400 else:
2421 else:
2401 self.load_extension(module_str)
2422 self.load_extension(module_str)
2402
2423
2403 def _call_load_ipython_extension(self, mod):
2424 def _call_load_ipython_extension(self, mod):
2404 if hasattr(mod, 'load_ipython_extension'):
2425 if hasattr(mod, 'load_ipython_extension'):
2405 return mod.load_ipython_extension(self)
2426 return mod.load_ipython_extension(self)
2406
2427
2407 def _call_unload_ipython_extension(self, mod):
2428 def _call_unload_ipython_extension(self, mod):
2408 if hasattr(mod, 'unload_ipython_extension'):
2429 if hasattr(mod, 'unload_ipython_extension'):
2409 return mod.unload_ipython_extension(self)
2430 return mod.unload_ipython_extension(self)
2410
2431
2411 #-------------------------------------------------------------------------
2432 #-------------------------------------------------------------------------
2412 # Things related to the prefilter
2433 # Things related to the prefilter
2413 #-------------------------------------------------------------------------
2434 #-------------------------------------------------------------------------
2414
2435
2415 def init_prefilter(self):
2436 def init_prefilter(self):
2416 self.prefilter_manager = PrefilterManager(self, config=self.config)
2437 self.prefilter_manager = PrefilterManager(self, config=self.config)
2417 # Ultimately this will be refactored in the new interpreter code, but
2438 # Ultimately this will be refactored in the new interpreter code, but
2418 # for now, we should expose the main prefilter method (there's legacy
2439 # for now, we should expose the main prefilter method (there's legacy
2419 # code out there that may rely on this).
2440 # code out there that may rely on this).
2420 self.prefilter = self.prefilter_manager.prefilter_lines
2441 self.prefilter = self.prefilter_manager.prefilter_lines
2421
2442
2422 #-------------------------------------------------------------------------
2443 #-------------------------------------------------------------------------
2423 # Utilities
2444 # Utilities
2424 #-------------------------------------------------------------------------
2445 #-------------------------------------------------------------------------
2425
2446
2426 def getoutput(self, cmd):
2447 def getoutput(self, cmd):
2427 return getoutput(self.var_expand(cmd,depth=2),
2448 return getoutput(self.var_expand(cmd,depth=2),
2428 header=self.system_header,
2449 header=self.system_header,
2429 verbose=self.system_verbose)
2450 verbose=self.system_verbose)
2430
2451
2431 def getoutputerror(self, cmd):
2452 def getoutputerror(self, cmd):
2432 return getoutputerror(self.var_expand(cmd,depth=2),
2453 return getoutputerror(self.var_expand(cmd,depth=2),
2433 header=self.system_header,
2454 header=self.system_header,
2434 verbose=self.system_verbose)
2455 verbose=self.system_verbose)
2435
2456
2436 def var_expand(self,cmd,depth=0):
2457 def var_expand(self,cmd,depth=0):
2437 """Expand python variables in a string.
2458 """Expand python variables in a string.
2438
2459
2439 The depth argument indicates how many frames above the caller should
2460 The depth argument indicates how many frames above the caller should
2440 be walked to look for the local namespace where to expand variables.
2461 be walked to look for the local namespace where to expand variables.
2441
2462
2442 The global namespace for expansion is always the user's interactive
2463 The global namespace for expansion is always the user's interactive
2443 namespace.
2464 namespace.
2444 """
2465 """
2445
2466
2446 return str(ItplNS(cmd,
2467 return str(ItplNS(cmd,
2447 self.user_ns, # globals
2468 self.user_ns, # globals
2448 # Skip our own frame in searching for locals:
2469 # Skip our own frame in searching for locals:
2449 sys._getframe(depth+1).f_locals # locals
2470 sys._getframe(depth+1).f_locals # locals
2450 ))
2471 ))
2451
2472
2452 def mktempfile(self,data=None):
2473 def mktempfile(self,data=None):
2453 """Make a new tempfile and return its filename.
2474 """Make a new tempfile and return its filename.
2454
2475
2455 This makes a call to tempfile.mktemp, but it registers the created
2476 This makes a call to tempfile.mktemp, but it registers the created
2456 filename internally so ipython cleans it up at exit time.
2477 filename internally so ipython cleans it up at exit time.
2457
2478
2458 Optional inputs:
2479 Optional inputs:
2459
2480
2460 - data(None): if data is given, it gets written out to the temp file
2481 - data(None): if data is given, it gets written out to the temp file
2461 immediately, and the file is closed again."""
2482 immediately, and the file is closed again."""
2462
2483
2463 filename = tempfile.mktemp('.py','ipython_edit_')
2484 filename = tempfile.mktemp('.py','ipython_edit_')
2464 self.tempfiles.append(filename)
2485 self.tempfiles.append(filename)
2465
2486
2466 if data:
2487 if data:
2467 tmp_file = open(filename,'w')
2488 tmp_file = open(filename,'w')
2468 tmp_file.write(data)
2489 tmp_file.write(data)
2469 tmp_file.close()
2490 tmp_file.close()
2470 return filename
2491 return filename
2471
2492
2472 def write(self,data):
2493 def write(self,data):
2473 """Write a string to the default output"""
2494 """Write a string to the default output"""
2474 Term.cout.write(data)
2495 Term.cout.write(data)
2475
2496
2476 def write_err(self,data):
2497 def write_err(self,data):
2477 """Write a string to the default error output"""
2498 """Write a string to the default error output"""
2478 Term.cerr.write(data)
2499 Term.cerr.write(data)
2479
2500
2480 def ask_yes_no(self,prompt,default=True):
2501 def ask_yes_no(self,prompt,default=True):
2481 if self.quiet:
2502 if self.quiet:
2482 return True
2503 return True
2483 return ask_yes_no(prompt,default)
2504 return ask_yes_no(prompt,default)
2484
2505
2485 #-------------------------------------------------------------------------
2506 #-------------------------------------------------------------------------
2486 # Things related to GUI support and pylab
2507 # Things related to GUI support and pylab
2487 #-------------------------------------------------------------------------
2508 #-------------------------------------------------------------------------
2488
2509
2489 def enable_pylab(self, gui=None):
2510 def enable_pylab(self, gui=None):
2490 """Activate pylab support at runtime.
2511 """Activate pylab support at runtime.
2491
2512
2492 This turns on support for matplotlib, preloads into the interactive
2513 This turns on support for matplotlib, preloads into the interactive
2493 namespace all of numpy and pylab, and configures IPython to correcdtly
2514 namespace all of numpy and pylab, and configures IPython to correcdtly
2494 interact with the GUI event loop. The GUI backend to be used can be
2515 interact with the GUI event loop. The GUI backend to be used can be
2495 optionally selected with the optional :param:`gui` argument.
2516 optionally selected with the optional :param:`gui` argument.
2496
2517
2497 Parameters
2518 Parameters
2498 ----------
2519 ----------
2499 gui : optional, string
2520 gui : optional, string
2500
2521
2501 If given, dictates the choice of matplotlib GUI backend to use
2522 If given, dictates the choice of matplotlib GUI backend to use
2502 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2523 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2503 'gtk'), otherwise we use the default chosen by matplotlib (as
2524 'gtk'), otherwise we use the default chosen by matplotlib (as
2504 dictated by the matplotlib build-time options plus the user's
2525 dictated by the matplotlib build-time options plus the user's
2505 matplotlibrc configuration file).
2526 matplotlibrc configuration file).
2506 """
2527 """
2507 # We want to prevent the loading of pylab to pollute the user's
2528 # We want to prevent the loading of pylab to pollute the user's
2508 # namespace as shown by the %who* magics, so we execute the activation
2529 # namespace as shown by the %who* magics, so we execute the activation
2509 # code in an empty namespace, and we update *both* user_ns and
2530 # code in an empty namespace, and we update *both* user_ns and
2510 # user_ns_hidden with this information.
2531 # user_ns_hidden with this information.
2511 ns = {}
2532 ns = {}
2512 gui = pylab_activate(ns, gui)
2533 gui = pylab_activate(ns, gui)
2513 self.user_ns.update(ns)
2534 self.user_ns.update(ns)
2514 self.user_ns_hidden.update(ns)
2535 self.user_ns_hidden.update(ns)
2515 # Now we must activate the gui pylab wants to use, and fix %run to take
2536 # Now we must activate the gui pylab wants to use, and fix %run to take
2516 # plot updates into account
2537 # plot updates into account
2517 enable_gui(gui)
2538 enable_gui(gui)
2518 self.magic_run = self._pylab_magic_run
2539 self.magic_run = self._pylab_magic_run
2519
2540
2520 #-------------------------------------------------------------------------
2541 #-------------------------------------------------------------------------
2521 # Things related to IPython exiting
2542 # Things related to IPython exiting
2522 #-------------------------------------------------------------------------
2543 #-------------------------------------------------------------------------
2523
2544
2524 def ask_exit(self):
2545 def ask_exit(self):
2525 """ Ask the shell to exit. Can be overiden and used as a callback. """
2546 """ Ask the shell to exit. Can be overiden and used as a callback. """
2526 self.exit_now = True
2547 self.exit_now = True
2527
2548
2528 def exit(self):
2549 def exit(self):
2529 """Handle interactive exit.
2550 """Handle interactive exit.
2530
2551
2531 This method calls the ask_exit callback."""
2552 This method calls the ask_exit callback."""
2532 if self.confirm_exit:
2553 if self.confirm_exit:
2533 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2554 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2534 self.ask_exit()
2555 self.ask_exit()
2535 else:
2556 else:
2536 self.ask_exit()
2557 self.ask_exit()
2537
2558
2538 def atexit_operations(self):
2559 def atexit_operations(self):
2539 """This will be executed at the time of exit.
2560 """This will be executed at the time of exit.
2540
2561
2541 Saving of persistent data should be performed here.
2562 Saving of persistent data should be performed here.
2542 """
2563 """
2543 self.savehist()
2564 self.savehist()
2544
2565
2545 # Cleanup all tempfiles left around
2566 # Cleanup all tempfiles left around
2546 for tfile in self.tempfiles:
2567 for tfile in self.tempfiles:
2547 try:
2568 try:
2548 os.unlink(tfile)
2569 os.unlink(tfile)
2549 except OSError:
2570 except OSError:
2550 pass
2571 pass
2551
2572
2552 # Clear all user namespaces to release all references cleanly.
2573 # Clear all user namespaces to release all references cleanly.
2553 self.reset()
2574 self.reset()
2554
2575
2555 # Run user hooks
2576 # Run user hooks
2556 self.hooks.shutdown_hook()
2577 self.hooks.shutdown_hook()
2557
2578
2558 def cleanup(self):
2579 def cleanup(self):
2559 self.restore_sys_module_state()
2580 self.restore_sys_module_state()
2560
2581
2561
2582
@@ -1,3633 +1,3698 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils.io import Term, file_read, nlprint
62 from IPython.utils.path import get_py_filename
62 from IPython.utils.path import get_py_filename
63 from IPython.utils.process import arg_split, abbrev_cwd
63 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.terminal import set_term_title
64 from IPython.utils.terminal import set_term_title
65 from IPython.utils.text import LSString, SList, StringTypes
65 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.timing import clock, clock2
66 from IPython.utils.timing import clock, clock2
67 from IPython.utils.warn import warn, error
67 from IPython.utils.warn import warn, error
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 import IPython.utils.generics
69 import IPython.utils.generics
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Utility functions
72 # Utility functions
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 def on_off(tag):
75 def on_off(tag):
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 return ['OFF','ON'][tag]
77 return ['OFF','ON'][tag]
78
78
79 class Bunch: pass
79 class Bunch: pass
80
80
81 def compress_dhist(dh):
81 def compress_dhist(dh):
82 head, tail = dh[:-10], dh[-10:]
82 head, tail = dh[:-10], dh[-10:]
83
83
84 newhead = []
84 newhead = []
85 done = set()
85 done = set()
86 for h in head:
86 for h in head:
87 if h in done:
87 if h in done:
88 continue
88 continue
89 newhead.append(h)
89 newhead.append(h)
90 done.add(h)
90 done.add(h)
91
91
92 return newhead + tail
92 return newhead + tail
93
93
94
94
95 #***************************************************************************
95 #***************************************************************************
96 # Main class implementing Magic functionality
96 # Main class implementing Magic functionality
97
97
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # on construction of the main InteractiveShell object. Something odd is going
99 # on construction of the main InteractiveShell object. Something odd is going
100 # on with super() calls, Component and the MRO... For now leave it as-is, but
100 # on with super() calls, Component and the MRO... For now leave it as-is, but
101 # eventually this needs to be clarified.
101 # eventually this needs to be clarified.
102 # BG: This is because InteractiveShell inherits from this, but is itself a
102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # Component. This messes up the MRO in some way. The fix is that we need to
103 # Component. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a component that InteractiveShell does not subclass.
104 # make Magic a component that InteractiveShell does not subclass.
105
105
106 class Magic:
106 class Magic:
107 """Magic functions for InteractiveShell.
107 """Magic functions for InteractiveShell.
108
108
109 Shell functions which can be reached as %function_name. All magic
109 Shell functions which can be reached as %function_name. All magic
110 functions should accept a string, which they can parse for their own
110 functions should accept a string, which they can parse for their own
111 needs. This can make some functions easier to type, eg `%cd ../`
111 needs. This can make some functions easier to type, eg `%cd ../`
112 vs. `%cd("../")`
112 vs. `%cd("../")`
113
113
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 at the command line, but it is is needed in the definition. """
115 at the command line, but it is is needed in the definition. """
116
116
117 # class globals
117 # class globals
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 'Automagic is ON, % prefix NOT needed for magic functions.']
119 'Automagic is ON, % prefix NOT needed for magic functions.']
120
120
121 #......................................................................
121 #......................................................................
122 # some utility functions
122 # some utility functions
123
123
124 def __init__(self,shell):
124 def __init__(self,shell):
125
125
126 self.options_table = {}
126 self.options_table = {}
127 if profile is None:
127 if profile is None:
128 self.magic_prun = self.profile_missing_notice
128 self.magic_prun = self.profile_missing_notice
129 self.shell = shell
129 self.shell = shell
130
130
131 # namespace for holding state we may need
131 # namespace for holding state we may need
132 self._magic_state = Bunch()
132 self._magic_state = Bunch()
133
133
134 def profile_missing_notice(self, *args, **kwargs):
134 def profile_missing_notice(self, *args, **kwargs):
135 error("""\
135 error("""\
136 The profile module could not be found. It has been removed from the standard
136 The profile module could not be found. It has been removed from the standard
137 python packages because of its non-free license. To use profiling, install the
137 python packages because of its non-free license. To use profiling, install the
138 python-profiler package from non-free.""")
138 python-profiler package from non-free.""")
139
139
140 def default_option(self,fn,optstr):
140 def default_option(self,fn,optstr):
141 """Make an entry in the options_table for fn, with value optstr"""
141 """Make an entry in the options_table for fn, with value optstr"""
142
142
143 if fn not in self.lsmagic():
143 if fn not in self.lsmagic():
144 error("%s is not a magic function" % fn)
144 error("%s is not a magic function" % fn)
145 self.options_table[fn] = optstr
145 self.options_table[fn] = optstr
146
146
147 def lsmagic(self):
147 def lsmagic(self):
148 """Return a list of currently available magic functions.
148 """Return a list of currently available magic functions.
149
149
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 ['magic_ls','magic_cd',...]"""
151 ['magic_ls','magic_cd',...]"""
152
152
153 # FIXME. This needs a cleanup, in the way the magics list is built.
153 # FIXME. This needs a cleanup, in the way the magics list is built.
154
154
155 # magics in class definition
155 # magics in class definition
156 class_magic = lambda fn: fn.startswith('magic_') and \
156 class_magic = lambda fn: fn.startswith('magic_') and \
157 callable(Magic.__dict__[fn])
157 callable(Magic.__dict__[fn])
158 # in instance namespace (run-time user additions)
158 # in instance namespace (run-time user additions)
159 inst_magic = lambda fn: fn.startswith('magic_') and \
159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 callable(self.__dict__[fn])
160 callable(self.__dict__[fn])
161 # and bound magics by user (so they can access self):
161 # and bound magics by user (so they can access self):
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 callable(self.__class__.__dict__[fn])
163 callable(self.__class__.__dict__[fn])
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 out = []
167 out = []
168 for fn in set(magics):
168 for fn in set(magics):
169 out.append(fn.replace('magic_','',1))
169 out.append(fn.replace('magic_','',1))
170 out.sort()
170 out.sort()
171 return out
171 return out
172
172
173 def extract_input_slices(self,slices,raw=False):
173 def extract_input_slices(self,slices,raw=False):
174 """Return as a string a set of input history slices.
174 """Return as a string a set of input history slices.
175
175
176 Inputs:
176 Inputs:
177
177
178 - slices: the set of slices is given as a list of strings (like
178 - slices: the set of slices is given as a list of strings (like
179 ['1','4:8','9'], since this function is for use by magic functions
179 ['1','4:8','9'], since this function is for use by magic functions
180 which get their arguments as strings.
180 which get their arguments as strings.
181
181
182 Optional inputs:
182 Optional inputs:
183
183
184 - raw(False): by default, the processed input is used. If this is
184 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
185 true, the raw input history is used instead.
186
186
187 Note that slices can be called with two notations:
187 Note that slices can be called with two notations:
188
188
189 N:M -> standard python form, means including items N...(M-1).
189 N:M -> standard python form, means including items N...(M-1).
190
190
191 N-M -> include items N..M (closed endpoint)."""
191 N-M -> include items N..M (closed endpoint)."""
192
192
193 if raw:
193 if raw:
194 hist = self.shell.input_hist_raw
194 hist = self.shell.input_hist_raw
195 else:
195 else:
196 hist = self.shell.input_hist
196 hist = self.shell.input_hist
197
197
198 cmds = []
198 cmds = []
199 for chunk in slices:
199 for chunk in slices:
200 if ':' in chunk:
200 if ':' in chunk:
201 ini,fin = map(int,chunk.split(':'))
201 ini,fin = map(int,chunk.split(':'))
202 elif '-' in chunk:
202 elif '-' in chunk:
203 ini,fin = map(int,chunk.split('-'))
203 ini,fin = map(int,chunk.split('-'))
204 fin += 1
204 fin += 1
205 else:
205 else:
206 ini = int(chunk)
206 ini = int(chunk)
207 fin = ini+1
207 fin = ini+1
208 cmds.append(hist[ini:fin])
208 cmds.append(hist[ini:fin])
209 return cmds
209 return cmds
210
210
211 def _ofind(self, oname, namespaces=None):
211 def _ofind(self, oname, namespaces=None):
212 """Find an object in the available namespaces.
212 """Find an object in the available namespaces.
213
213
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215
215
216 Has special code to detect magic functions.
216 Has special code to detect magic functions.
217 """
217 """
218 oname = oname.strip()
218 oname = oname.strip()
219 alias_ns = None
219 alias_ns = None
220 if namespaces is None:
220 if namespaces is None:
221 # Namespaces to search in:
221 # Namespaces to search in:
222 # Put them in a list. The order is important so that we
222 # Put them in a list. The order is important so that we
223 # find things in the same order that Python finds them.
223 # find things in the same order that Python finds them.
224 namespaces = [ ('Interactive', self.shell.user_ns),
224 namespaces = [ ('Interactive', self.shell.user_ns),
225 ('IPython internal', self.shell.internal_ns),
225 ('IPython internal', self.shell.internal_ns),
226 ('Python builtin', __builtin__.__dict__),
226 ('Python builtin', __builtin__.__dict__),
227 ('Alias', self.shell.alias_manager.alias_table),
227 ('Alias', self.shell.alias_manager.alias_table),
228 ]
228 ]
229 alias_ns = self.shell.alias_manager.alias_table
229 alias_ns = self.shell.alias_manager.alias_table
230
230
231 # initialize results to 'null'
231 # initialize results to 'null'
232 found = False; obj = None; ospace = None; ds = None;
232 found = False; obj = None; ospace = None; ds = None;
233 ismagic = False; isalias = False; parent = None
233 ismagic = False; isalias = False; parent = None
234
234
235 # We need to special-case 'print', which as of python2.6 registers as a
235 # We need to special-case 'print', which as of python2.6 registers as a
236 # function but should only be treated as one if print_function was
236 # function but should only be treated as one if print_function was
237 # loaded with a future import. In this case, just bail.
237 # loaded with a future import. In this case, just bail.
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 return {'found':found, 'obj':obj, 'namespace':ospace,
240 return {'found':found, 'obj':obj, 'namespace':ospace,
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242
242
243 # Look for the given name by splitting it in parts. If the head is
243 # Look for the given name by splitting it in parts. If the head is
244 # found, then we look for all the remaining parts as members, and only
244 # found, then we look for all the remaining parts as members, and only
245 # declare success if we can find them all.
245 # declare success if we can find them all.
246 oname_parts = oname.split('.')
246 oname_parts = oname.split('.')
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 for nsname,ns in namespaces:
248 for nsname,ns in namespaces:
249 try:
249 try:
250 obj = ns[oname_head]
250 obj = ns[oname_head]
251 except KeyError:
251 except KeyError:
252 continue
252 continue
253 else:
253 else:
254 #print 'oname_rest:', oname_rest # dbg
254 #print 'oname_rest:', oname_rest # dbg
255 for part in oname_rest:
255 for part in oname_rest:
256 try:
256 try:
257 parent = obj
257 parent = obj
258 obj = getattr(obj,part)
258 obj = getattr(obj,part)
259 except:
259 except:
260 # Blanket except b/c some badly implemented objects
260 # Blanket except b/c some badly implemented objects
261 # allow __getattr__ to raise exceptions other than
261 # allow __getattr__ to raise exceptions other than
262 # AttributeError, which then crashes IPython.
262 # AttributeError, which then crashes IPython.
263 break
263 break
264 else:
264 else:
265 # If we finish the for loop (no break), we got all members
265 # If we finish the for loop (no break), we got all members
266 found = True
266 found = True
267 ospace = nsname
267 ospace = nsname
268 if ns == alias_ns:
268 if ns == alias_ns:
269 isalias = True
269 isalias = True
270 break # namespace loop
270 break # namespace loop
271
271
272 # Try to see if it's magic
272 # Try to see if it's magic
273 if not found:
273 if not found:
274 if oname.startswith(ESC_MAGIC):
274 if oname.startswith(ESC_MAGIC):
275 oname = oname[1:]
275 oname = oname[1:]
276 obj = getattr(self,'magic_'+oname,None)
276 obj = getattr(self,'magic_'+oname,None)
277 if obj is not None:
277 if obj is not None:
278 found = True
278 found = True
279 ospace = 'IPython internal'
279 ospace = 'IPython internal'
280 ismagic = True
280 ismagic = True
281
281
282 # Last try: special-case some literals like '', [], {}, etc:
282 # Last try: special-case some literals like '', [], {}, etc:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
284 obj = eval(oname_head)
284 obj = eval(oname_head)
285 found = True
285 found = True
286 ospace = 'Interactive'
286 ospace = 'Interactive'
287
287
288 return {'found':found, 'obj':obj, 'namespace':ospace,
288 return {'found':found, 'obj':obj, 'namespace':ospace,
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290
290
291 def arg_err(self,func):
291 def arg_err(self,func):
292 """Print docstring if incorrect arguments were passed"""
292 """Print docstring if incorrect arguments were passed"""
293 print 'Error in arguments:'
293 print 'Error in arguments:'
294 print oinspect.getdoc(func)
294 print oinspect.getdoc(func)
295
295
296 def format_latex(self,strng):
296 def format_latex(self,strng):
297 """Format a string for latex inclusion."""
297 """Format a string for latex inclusion."""
298
298
299 # Characters that need to be escaped for latex:
299 # Characters that need to be escaped for latex:
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 # Magic command names as headers:
301 # Magic command names as headers:
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 re.MULTILINE)
303 re.MULTILINE)
304 # Magic commands
304 # Magic commands
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 re.MULTILINE)
306 re.MULTILINE)
307 # Paragraph continue
307 # Paragraph continue
308 par_re = re.compile(r'\\$',re.MULTILINE)
308 par_re = re.compile(r'\\$',re.MULTILINE)
309
309
310 # The "\n" symbol
310 # The "\n" symbol
311 newline_re = re.compile(r'\\n')
311 newline_re = re.compile(r'\\n')
312
312
313 # Now build the string for output:
313 # Now build the string for output:
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng)
316 strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = par_re.sub(r'\\\\',strng)
318 strng = par_re.sub(r'\\\\',strng)
319 strng = escape_re.sub(r'\\\1',strng)
319 strng = escape_re.sub(r'\\\1',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 return strng
321 return strng
322
322
323 def format_screen(self,strng):
323 def format_screen(self,strng):
324 """Format a string for screen printing.
324 """Format a string for screen printing.
325
325
326 This removes some latex-type format codes."""
326 This removes some latex-type format codes."""
327 # Paragraph continue
327 # Paragraph continue
328 par_re = re.compile(r'\\$',re.MULTILINE)
328 par_re = re.compile(r'\\$',re.MULTILINE)
329 strng = par_re.sub('',strng)
329 strng = par_re.sub('',strng)
330 return strng
330 return strng
331
331
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 """Parse options passed to an argument string.
333 """Parse options passed to an argument string.
334
334
335 The interface is similar to that of getopt(), but it returns back a
335 The interface is similar to that of getopt(), but it returns back a
336 Struct with the options as keys and the stripped argument string still
336 Struct with the options as keys and the stripped argument string still
337 as a string.
337 as a string.
338
338
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 This allows us to easily expand variables, glob files, quote
340 This allows us to easily expand variables, glob files, quote
341 arguments, etc.
341 arguments, etc.
342
342
343 Options:
343 Options:
344 -mode: default 'string'. If given as 'list', the argument string is
344 -mode: default 'string'. If given as 'list', the argument string is
345 returned as a list (split on whitespace) instead of a string.
345 returned as a list (split on whitespace) instead of a string.
346
346
347 -list_all: put all option values in lists. Normally only options
347 -list_all: put all option values in lists. Normally only options
348 appearing more than once are put in a list.
348 appearing more than once are put in a list.
349
349
350 -posix (True): whether to split the input line in POSIX mode or not,
350 -posix (True): whether to split the input line in POSIX mode or not,
351 as per the conventions outlined in the shlex module from the
351 as per the conventions outlined in the shlex module from the
352 standard library."""
352 standard library."""
353
353
354 # inject default options at the beginning of the input line
354 # inject default options at the beginning of the input line
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357
357
358 mode = kw.get('mode','string')
358 mode = kw.get('mode','string')
359 if mode not in ['string','list']:
359 if mode not in ['string','list']:
360 raise ValueError,'incorrect mode given: %s' % mode
360 raise ValueError,'incorrect mode given: %s' % mode
361 # Get options
361 # Get options
362 list_all = kw.get('list_all',0)
362 list_all = kw.get('list_all',0)
363 posix = kw.get('posix', os.name == 'posix')
363 posix = kw.get('posix', os.name == 'posix')
364
364
365 # Check if we have more than one argument to warrant extra processing:
365 # Check if we have more than one argument to warrant extra processing:
366 odict = {} # Dictionary with options
366 odict = {} # Dictionary with options
367 args = arg_str.split()
367 args = arg_str.split()
368 if len(args) >= 1:
368 if len(args) >= 1:
369 # If the list of inputs only has 0 or 1 thing in it, there's no
369 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # need to look for options
370 # need to look for options
371 argv = arg_split(arg_str,posix)
371 argv = arg_split(arg_str,posix)
372 # Do regular option processing
372 # Do regular option processing
373 try:
373 try:
374 opts,args = getopt(argv,opt_str,*long_opts)
374 opts,args = getopt(argv,opt_str,*long_opts)
375 except GetoptError,e:
375 except GetoptError,e:
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 " ".join(long_opts)))
377 " ".join(long_opts)))
378 for o,a in opts:
378 for o,a in opts:
379 if o.startswith('--'):
379 if o.startswith('--'):
380 o = o[2:]
380 o = o[2:]
381 else:
381 else:
382 o = o[1:]
382 o = o[1:]
383 try:
383 try:
384 odict[o].append(a)
384 odict[o].append(a)
385 except AttributeError:
385 except AttributeError:
386 odict[o] = [odict[o],a]
386 odict[o] = [odict[o],a]
387 except KeyError:
387 except KeyError:
388 if list_all:
388 if list_all:
389 odict[o] = [a]
389 odict[o] = [a]
390 else:
390 else:
391 odict[o] = a
391 odict[o] = a
392
392
393 # Prepare opts,args for return
393 # Prepare opts,args for return
394 opts = Struct(odict)
394 opts = Struct(odict)
395 if mode == 'string':
395 if mode == 'string':
396 args = ' '.join(args)
396 args = ' '.join(args)
397
397
398 return opts,args
398 return opts,args
399
399
400 #......................................................................
400 #......................................................................
401 # And now the actual magic functions
401 # And now the actual magic functions
402
402
403 # Functions for IPython shell work (vars,funcs, config, etc)
403 # Functions for IPython shell work (vars,funcs, config, etc)
404 def magic_lsmagic(self, parameter_s = ''):
404 def magic_lsmagic(self, parameter_s = ''):
405 """List currently available magic functions."""
405 """List currently available magic functions."""
406 mesc = ESC_MAGIC
406 mesc = ESC_MAGIC
407 print 'Available magic functions:\n'+mesc+\
407 print 'Available magic functions:\n'+mesc+\
408 (' '+mesc).join(self.lsmagic())
408 (' '+mesc).join(self.lsmagic())
409 print '\n' + Magic.auto_status[self.shell.automagic]
409 print '\n' + Magic.auto_status[self.shell.automagic]
410 return None
410 return None
411
411
412 def magic_magic(self, parameter_s = ''):
412 def magic_magic(self, parameter_s = ''):
413 """Print information about the magic function system.
413 """Print information about the magic function system.
414
414
415 Supported formats: -latex, -brief, -rest
415 Supported formats: -latex, -brief, -rest
416 """
416 """
417
417
418 mode = ''
418 mode = ''
419 try:
419 try:
420 if parameter_s.split()[0] == '-latex':
420 if parameter_s.split()[0] == '-latex':
421 mode = 'latex'
421 mode = 'latex'
422 if parameter_s.split()[0] == '-brief':
422 if parameter_s.split()[0] == '-brief':
423 mode = 'brief'
423 mode = 'brief'
424 if parameter_s.split()[0] == '-rest':
424 if parameter_s.split()[0] == '-rest':
425 mode = 'rest'
425 mode = 'rest'
426 rest_docs = []
426 rest_docs = []
427 except:
427 except:
428 pass
428 pass
429
429
430 magic_docs = []
430 magic_docs = []
431 for fname in self.lsmagic():
431 for fname in self.lsmagic():
432 mname = 'magic_' + fname
432 mname = 'magic_' + fname
433 for space in (Magic,self,self.__class__):
433 for space in (Magic,self,self.__class__):
434 try:
434 try:
435 fn = space.__dict__[mname]
435 fn = space.__dict__[mname]
436 except KeyError:
436 except KeyError:
437 pass
437 pass
438 else:
438 else:
439 break
439 break
440 if mode == 'brief':
440 if mode == 'brief':
441 # only first line
441 # only first line
442 if fn.__doc__:
442 if fn.__doc__:
443 fndoc = fn.__doc__.split('\n',1)[0]
443 fndoc = fn.__doc__.split('\n',1)[0]
444 else:
444 else:
445 fndoc = 'No documentation'
445 fndoc = 'No documentation'
446 else:
446 else:
447 if fn.__doc__:
447 if fn.__doc__:
448 fndoc = fn.__doc__.rstrip()
448 fndoc = fn.__doc__.rstrip()
449 else:
449 else:
450 fndoc = 'No documentation'
450 fndoc = 'No documentation'
451
451
452
452
453 if mode == 'rest':
453 if mode == 'rest':
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 fname,fndoc))
455 fname,fndoc))
456
456
457 else:
457 else:
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 fname,fndoc))
459 fname,fndoc))
460
460
461 magic_docs = ''.join(magic_docs)
461 magic_docs = ''.join(magic_docs)
462
462
463 if mode == 'rest':
463 if mode == 'rest':
464 return "".join(rest_docs)
464 return "".join(rest_docs)
465
465
466 if mode == 'latex':
466 if mode == 'latex':
467 print self.format_latex(magic_docs)
467 print self.format_latex(magic_docs)
468 return
468 return
469 else:
469 else:
470 magic_docs = self.format_screen(magic_docs)
470 magic_docs = self.format_screen(magic_docs)
471 if mode == 'brief':
471 if mode == 'brief':
472 return magic_docs
472 return magic_docs
473
473
474 outmsg = """
474 outmsg = """
475 IPython's 'magic' functions
475 IPython's 'magic' functions
476 ===========================
476 ===========================
477
477
478 The magic function system provides a series of functions which allow you to
478 The magic function system provides a series of functions which allow you to
479 control the behavior of IPython itself, plus a lot of system-type
479 control the behavior of IPython itself, plus a lot of system-type
480 features. All these functions are prefixed with a % character, but parameters
480 features. All these functions are prefixed with a % character, but parameters
481 are given without parentheses or quotes.
481 are given without parentheses or quotes.
482
482
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 %automagic function), you don't need to type in the % explicitly. By default,
484 %automagic function), you don't need to type in the % explicitly. By default,
485 IPython ships with automagic on, so you should only rarely need the % escape.
485 IPython ships with automagic on, so you should only rarely need the % escape.
486
486
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 to 'mydir', if it exists.
488 to 'mydir', if it exists.
489
489
490 You can define your own magic functions to extend the system. See the supplied
490 You can define your own magic functions to extend the system. See the supplied
491 ipythonrc and example-magic.py files for details (in your ipython
491 ipythonrc and example-magic.py files for details (in your ipython
492 configuration directory, typically $HOME/.ipython/).
492 configuration directory, typically $HOME/.ipython/).
493
493
494 You can also define your own aliased names for magic functions. In your
494 You can also define your own aliased names for magic functions. In your
495 ipythonrc file, placing a line like:
495 ipythonrc file, placing a line like:
496
496
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498
498
499 will define %pf as a new name for %profile.
499 will define %pf as a new name for %profile.
500
500
501 You can also call magics in code using the magic() function, which IPython
501 You can also call magics in code using the magic() function, which IPython
502 automatically adds to the builtin namespace. Type 'magic?' for details.
502 automatically adds to the builtin namespace. Type 'magic?' for details.
503
503
504 For a list of the available magic functions, use %lsmagic. For a description
504 For a list of the available magic functions, use %lsmagic. For a description
505 of any of them, type %magic_name?, e.g. '%cd?'.
505 of any of them, type %magic_name?, e.g. '%cd?'.
506
506
507 Currently the magic system has the following functions:\n"""
507 Currently the magic system has the following functions:\n"""
508
508
509 mesc = ESC_MAGIC
509 mesc = ESC_MAGIC
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 "\n\n%s%s\n\n%s" % (outmsg,
511 "\n\n%s%s\n\n%s" % (outmsg,
512 magic_docs,mesc,mesc,
512 magic_docs,mesc,mesc,
513 (' '+mesc).join(self.lsmagic()),
513 (' '+mesc).join(self.lsmagic()),
514 Magic.auto_status[self.shell.automagic] ) )
514 Magic.auto_status[self.shell.automagic] ) )
515
515
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
517
517
518
518
519 def magic_autoindent(self, parameter_s = ''):
519 def magic_autoindent(self, parameter_s = ''):
520 """Toggle autoindent on/off (if available)."""
520 """Toggle autoindent on/off (if available)."""
521
521
522 self.shell.set_autoindent()
522 self.shell.set_autoindent()
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524
524
525
525
526 def magic_automagic(self, parameter_s = ''):
526 def magic_automagic(self, parameter_s = ''):
527 """Make magic functions callable without having to type the initial %.
527 """Make magic functions callable without having to type the initial %.
528
528
529 Without argumentsl toggles on/off (when off, you must call it as
529 Without argumentsl toggles on/off (when off, you must call it as
530 %automagic, of course). With arguments it sets the value, and you can
530 %automagic, of course). With arguments it sets the value, and you can
531 use any of (case insensitive):
531 use any of (case insensitive):
532
532
533 - on,1,True: to activate
533 - on,1,True: to activate
534
534
535 - off,0,False: to deactivate.
535 - off,0,False: to deactivate.
536
536
537 Note that magic functions have lowest priority, so if there's a
537 Note that magic functions have lowest priority, so if there's a
538 variable whose name collides with that of a magic fn, automagic won't
538 variable whose name collides with that of a magic fn, automagic won't
539 work for that function (you get the variable instead). However, if you
539 work for that function (you get the variable instead). However, if you
540 delete the variable (del var), the previously shadowed magic function
540 delete the variable (del var), the previously shadowed magic function
541 becomes visible to automagic again."""
541 becomes visible to automagic again."""
542
542
543 arg = parameter_s.lower()
543 arg = parameter_s.lower()
544 if parameter_s in ('on','1','true'):
544 if parameter_s in ('on','1','true'):
545 self.shell.automagic = True
545 self.shell.automagic = True
546 elif parameter_s in ('off','0','false'):
546 elif parameter_s in ('off','0','false'):
547 self.shell.automagic = False
547 self.shell.automagic = False
548 else:
548 else:
549 self.shell.automagic = not self.shell.automagic
549 self.shell.automagic = not self.shell.automagic
550 print '\n' + Magic.auto_status[self.shell.automagic]
550 print '\n' + Magic.auto_status[self.shell.automagic]
551
551
552 @testdec.skip_doctest
552 @testdec.skip_doctest
553 def magic_autocall(self, parameter_s = ''):
553 def magic_autocall(self, parameter_s = ''):
554 """Make functions callable without having to type parentheses.
554 """Make functions callable without having to type parentheses.
555
555
556 Usage:
556 Usage:
557
557
558 %autocall [mode]
558 %autocall [mode]
559
559
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 value is toggled on and off (remembering the previous state).
561 value is toggled on and off (remembering the previous state).
562
562
563 In more detail, these values mean:
563 In more detail, these values mean:
564
564
565 0 -> fully disabled
565 0 -> fully disabled
566
566
567 1 -> active, but do not apply if there are no arguments on the line.
567 1 -> active, but do not apply if there are no arguments on the line.
568
568
569 In this mode, you get:
569 In this mode, you get:
570
570
571 In [1]: callable
571 In [1]: callable
572 Out[1]: <built-in function callable>
572 Out[1]: <built-in function callable>
573
573
574 In [2]: callable 'hello'
574 In [2]: callable 'hello'
575 ------> callable('hello')
575 ------> callable('hello')
576 Out[2]: False
576 Out[2]: False
577
577
578 2 -> Active always. Even if no arguments are present, the callable
578 2 -> Active always. Even if no arguments are present, the callable
579 object is called:
579 object is called:
580
580
581 In [2]: float
581 In [2]: float
582 ------> float()
582 ------> float()
583 Out[2]: 0.0
583 Out[2]: 0.0
584
584
585 Note that even with autocall off, you can still use '/' at the start of
585 Note that even with autocall off, you can still use '/' at the start of
586 a line to treat the first argument on the command line as a function
586 a line to treat the first argument on the command line as a function
587 and add parentheses to it:
587 and add parentheses to it:
588
588
589 In [8]: /str 43
589 In [8]: /str 43
590 ------> str(43)
590 ------> str(43)
591 Out[8]: '43'
591 Out[8]: '43'
592
592
593 # all-random (note for auto-testing)
593 # all-random (note for auto-testing)
594 """
594 """
595
595
596 if parameter_s:
596 if parameter_s:
597 arg = int(parameter_s)
597 arg = int(parameter_s)
598 else:
598 else:
599 arg = 'toggle'
599 arg = 'toggle'
600
600
601 if not arg in (0,1,2,'toggle'):
601 if not arg in (0,1,2,'toggle'):
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 return
603 return
604
604
605 if arg in (0,1,2):
605 if arg in (0,1,2):
606 self.shell.autocall = arg
606 self.shell.autocall = arg
607 else: # toggle
607 else: # toggle
608 if self.shell.autocall:
608 if self.shell.autocall:
609 self._magic_state.autocall_save = self.shell.autocall
609 self._magic_state.autocall_save = self.shell.autocall
610 self.shell.autocall = 0
610 self.shell.autocall = 0
611 else:
611 else:
612 try:
612 try:
613 self.shell.autocall = self._magic_state.autocall_save
613 self.shell.autocall = self._magic_state.autocall_save
614 except AttributeError:
614 except AttributeError:
615 self.shell.autocall = self._magic_state.autocall_save = 1
615 self.shell.autocall = self._magic_state.autocall_save = 1
616
616
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618
618
619 def magic_system_verbose(self, parameter_s = ''):
619 def magic_system_verbose(self, parameter_s = ''):
620 """Set verbose printing of system calls.
620 """Set verbose printing of system calls.
621
621
622 If called without an argument, act as a toggle"""
622 If called without an argument, act as a toggle"""
623
623
624 if parameter_s:
624 if parameter_s:
625 val = bool(eval(parameter_s))
625 val = bool(eval(parameter_s))
626 else:
626 else:
627 val = None
627 val = None
628
628
629 if self.shell.system_verbose:
629 if self.shell.system_verbose:
630 self.shell.system_verbose = False
630 self.shell.system_verbose = False
631 else:
631 else:
632 self.shell.system_verbose = True
632 self.shell.system_verbose = True
633 print "System verbose printing is:",\
633 print "System verbose printing is:",\
634 ['OFF','ON'][self.shell.system_verbose]
634 ['OFF','ON'][self.shell.system_verbose]
635
635
636
636
637 def magic_page(self, parameter_s=''):
637 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
638 """Pretty print the object and display it through a pager.
639
639
640 %page [options] OBJECT
640 %page [options] OBJECT
641
641
642 If no object is given, use _ (last output).
642 If no object is given, use _ (last output).
643
643
644 Options:
644 Options:
645
645
646 -r: page str(object), don't pretty-print it."""
646 -r: page str(object), don't pretty-print it."""
647
647
648 # After a function contributed by Olivier Aubert, slightly modified.
648 # After a function contributed by Olivier Aubert, slightly modified.
649
649
650 # Process options/args
650 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
651 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
652 raw = 'r' in opts
653
653
654 oname = args and args or '_'
654 oname = args and args or '_'
655 info = self._ofind(oname)
655 info = self._ofind(oname)
656 if info['found']:
656 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
657 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
658 page(txt)
659 else:
659 else:
660 print 'Object `%s` not found' % oname
660 print 'Object `%s` not found' % oname
661
661
662 def magic_profile(self, parameter_s=''):
662 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPython profile."""
663 """Print your currently active IPython profile."""
664 if self.shell.profile:
664 if self.shell.profile:
665 printpl('Current IPython profile: $self.shell.profile.')
665 printpl('Current IPython profile: $self.shell.profile.')
666 else:
666 else:
667 print 'No profile active.'
667 print 'No profile active.'
668
668
669 def magic_pinfo(self, parameter_s='', namespaces=None):
669 def magic_pinfo(self, parameter_s='', namespaces=None):
670 """Provide detailed information about an object.
670 """Provide detailed information about an object.
671
671
672 '%pinfo object' is just a synonym for object? or ?object."""
672 '%pinfo object' is just a synonym for object? or ?object."""
673
673
674 #print 'pinfo par: <%s>' % parameter_s # dbg
674 #print 'pinfo par: <%s>' % parameter_s # dbg
675
675
676
676
677 # detail_level: 0 -> obj? , 1 -> obj??
677 # detail_level: 0 -> obj? , 1 -> obj??
678 detail_level = 0
678 detail_level = 0
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # happen if the user types 'pinfo foo?' at the cmd line.
680 # happen if the user types 'pinfo foo?' at the cmd line.
681 pinfo,qmark1,oname,qmark2 = \
681 pinfo,qmark1,oname,qmark2 = \
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 if pinfo or qmark1 or qmark2:
683 if pinfo or qmark1 or qmark2:
684 detail_level = 1
684 detail_level = 1
685 if "*" in oname:
685 if "*" in oname:
686 self.magic_psearch(oname)
686 self.magic_psearch(oname)
687 else:
687 else:
688 self._inspect('pinfo', oname, detail_level=detail_level,
688 self._inspect('pinfo', oname, detail_level=detail_level,
689 namespaces=namespaces)
689 namespaces=namespaces)
690
690
691 def magic_pdef(self, parameter_s='', namespaces=None):
691 def magic_pdef(self, parameter_s='', namespaces=None):
692 """Print the definition header for any callable object.
692 """Print the definition header for any callable object.
693
693
694 If the object is a class, print the constructor information."""
694 If the object is a class, print the constructor information."""
695 self._inspect('pdef',parameter_s, namespaces)
695 self._inspect('pdef',parameter_s, namespaces)
696
696
697 def magic_pdoc(self, parameter_s='', namespaces=None):
697 def magic_pdoc(self, parameter_s='', namespaces=None):
698 """Print the docstring for an object.
698 """Print the docstring for an object.
699
699
700 If the given object is a class, it will print both the class and the
700 If the given object is a class, it will print both the class and the
701 constructor docstrings."""
701 constructor docstrings."""
702 self._inspect('pdoc',parameter_s, namespaces)
702 self._inspect('pdoc',parameter_s, namespaces)
703
703
704 def magic_psource(self, parameter_s='', namespaces=None):
704 def magic_psource(self, parameter_s='', namespaces=None):
705 """Print (or run through pager) the source code for an object."""
705 """Print (or run through pager) the source code for an object."""
706 self._inspect('psource',parameter_s, namespaces)
706 self._inspect('psource',parameter_s, namespaces)
707
707
708 def magic_pfile(self, parameter_s=''):
708 def magic_pfile(self, parameter_s=''):
709 """Print (or run through pager) the file where an object is defined.
709 """Print (or run through pager) the file where an object is defined.
710
710
711 The file opens at the line where the object definition begins. IPython
711 The file opens at the line where the object definition begins. IPython
712 will honor the environment variable PAGER if set, and otherwise will
712 will honor the environment variable PAGER if set, and otherwise will
713 do its best to print the file in a convenient form.
713 do its best to print the file in a convenient form.
714
714
715 If the given argument is not an object currently defined, IPython will
715 If the given argument is not an object currently defined, IPython will
716 try to interpret it as a filename (automatically adding a .py extension
716 try to interpret it as a filename (automatically adding a .py extension
717 if needed). You can thus use %pfile as a syntax highlighting code
717 if needed). You can thus use %pfile as a syntax highlighting code
718 viewer."""
718 viewer."""
719
719
720 # first interpret argument as an object name
720 # first interpret argument as an object name
721 out = self._inspect('pfile',parameter_s)
721 out = self._inspect('pfile',parameter_s)
722 # if not, try the input as a filename
722 # if not, try the input as a filename
723 if out == 'not found':
723 if out == 'not found':
724 try:
724 try:
725 filename = get_py_filename(parameter_s)
725 filename = get_py_filename(parameter_s)
726 except IOError,msg:
726 except IOError,msg:
727 print msg
727 print msg
728 return
728 return
729 page(self.shell.inspector.format(file(filename).read()))
729 page(self.shell.inspector.format(file(filename).read()))
730
730
731 def _inspect(self,meth,oname,namespaces=None,**kw):
731 def _inspect(self,meth,oname,namespaces=None,**kw):
732 """Generic interface to the inspector system.
732 """Generic interface to the inspector system.
733
733
734 This function is meant to be called by pdef, pdoc & friends."""
734 This function is meant to be called by pdef, pdoc & friends."""
735
735
736 #oname = oname.strip()
736 #oname = oname.strip()
737 #print '1- oname: <%r>' % oname # dbg
737 #print '1- oname: <%r>' % oname # dbg
738 try:
738 try:
739 oname = oname.strip().encode('ascii')
739 oname = oname.strip().encode('ascii')
740 #print '2- oname: <%r>' % oname # dbg
740 #print '2- oname: <%r>' % oname # dbg
741 except UnicodeEncodeError:
741 except UnicodeEncodeError:
742 print 'Python identifiers can only contain ascii characters.'
742 print 'Python identifiers can only contain ascii characters.'
743 return 'not found'
743 return 'not found'
744
744
745 info = Struct(self._ofind(oname, namespaces))
745 info = Struct(self._ofind(oname, namespaces))
746
746
747 if info.found:
747 if info.found:
748 try:
748 try:
749 IPython.utils.generics.inspect_object(info.obj)
749 IPython.utils.generics.inspect_object(info.obj)
750 return
750 return
751 except TryNext:
751 except TryNext:
752 pass
752 pass
753 # Get the docstring of the class property if it exists.
753 # Get the docstring of the class property if it exists.
754 path = oname.split('.')
754 path = oname.split('.')
755 root = '.'.join(path[:-1])
755 root = '.'.join(path[:-1])
756 if info.parent is not None:
756 if info.parent is not None:
757 try:
757 try:
758 target = getattr(info.parent, '__class__')
758 target = getattr(info.parent, '__class__')
759 # The object belongs to a class instance.
759 # The object belongs to a class instance.
760 try:
760 try:
761 target = getattr(target, path[-1])
761 target = getattr(target, path[-1])
762 # The class defines the object.
762 # The class defines the object.
763 if isinstance(target, property):
763 if isinstance(target, property):
764 oname = root + '.__class__.' + path[-1]
764 oname = root + '.__class__.' + path[-1]
765 info = Struct(self._ofind(oname))
765 info = Struct(self._ofind(oname))
766 except AttributeError: pass
766 except AttributeError: pass
767 except AttributeError: pass
767 except AttributeError: pass
768
768
769 pmethod = getattr(self.shell.inspector,meth)
769 pmethod = getattr(self.shell.inspector,meth)
770 formatter = info.ismagic and self.format_screen or None
770 formatter = info.ismagic and self.format_screen or None
771 if meth == 'pdoc':
771 if meth == 'pdoc':
772 pmethod(info.obj,oname,formatter)
772 pmethod(info.obj,oname,formatter)
773 elif meth == 'pinfo':
773 elif meth == 'pinfo':
774 pmethod(info.obj,oname,formatter,info,**kw)
774 pmethod(info.obj,oname,formatter,info,**kw)
775 else:
775 else:
776 pmethod(info.obj,oname)
776 pmethod(info.obj,oname)
777 else:
777 else:
778 print 'Object `%s` not found.' % oname
778 print 'Object `%s` not found.' % oname
779 return 'not found' # so callers can take other action
779 return 'not found' # so callers can take other action
780
780
781 def magic_psearch(self, parameter_s=''):
781 def magic_psearch(self, parameter_s=''):
782 """Search for object in namespaces by wildcard.
782 """Search for object in namespaces by wildcard.
783
783
784 %psearch [options] PATTERN [OBJECT TYPE]
784 %psearch [options] PATTERN [OBJECT TYPE]
785
785
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 rest of the command line must be unchanged (options come first), so
788 rest of the command line must be unchanged (options come first), so
789 for example the following forms are equivalent
789 for example the following forms are equivalent
790
790
791 %psearch -i a* function
791 %psearch -i a* function
792 -i a* function?
792 -i a* function?
793 ?-i a* function
793 ?-i a* function
794
794
795 Arguments:
795 Arguments:
796
796
797 PATTERN
797 PATTERN
798
798
799 where PATTERN is a string containing * as a wildcard similar to its
799 where PATTERN is a string containing * as a wildcard similar to its
800 use in a shell. The pattern is matched in all namespaces on the
800 use in a shell. The pattern is matched in all namespaces on the
801 search path. By default objects starting with a single _ are not
801 search path. By default objects starting with a single _ are not
802 matched, many IPython generated objects have a single
802 matched, many IPython generated objects have a single
803 underscore. The default is case insensitive matching. Matching is
803 underscore. The default is case insensitive matching. Matching is
804 also done on the attributes of objects and not only on the objects
804 also done on the attributes of objects and not only on the objects
805 in a module.
805 in a module.
806
806
807 [OBJECT TYPE]
807 [OBJECT TYPE]
808
808
809 Is the name of a python type from the types module. The name is
809 Is the name of a python type from the types module. The name is
810 given in lowercase without the ending type, ex. StringType is
810 given in lowercase without the ending type, ex. StringType is
811 written string. By adding a type here only objects matching the
811 written string. By adding a type here only objects matching the
812 given type are matched. Using all here makes the pattern match all
812 given type are matched. Using all here makes the pattern match all
813 types (this is the default).
813 types (this is the default).
814
814
815 Options:
815 Options:
816
816
817 -a: makes the pattern match even objects whose names start with a
817 -a: makes the pattern match even objects whose names start with a
818 single underscore. These names are normally ommitted from the
818 single underscore. These names are normally ommitted from the
819 search.
819 search.
820
820
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 these options is given, the default is read from your ipythonrc
822 these options is given, the default is read from your ipythonrc
823 file. The option name which sets this value is
823 file. The option name which sets this value is
824 'wildcards_case_sensitive'. If this option is not specified in your
824 'wildcards_case_sensitive'. If this option is not specified in your
825 ipythonrc file, IPython's internal default is to do a case sensitive
825 ipythonrc file, IPython's internal default is to do a case sensitive
826 search.
826 search.
827
827
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 specifiy can be searched in any of the following namespaces:
829 specifiy can be searched in any of the following namespaces:
830 'builtin', 'user', 'user_global','internal', 'alias', where
830 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin' and 'user' are the search defaults. Note that you should
831 'builtin' and 'user' are the search defaults. Note that you should
832 not use quotes when specifying namespaces.
832 not use quotes when specifying namespaces.
833
833
834 'Builtin' contains the python module builtin, 'user' contains all
834 'Builtin' contains the python module builtin, 'user' contains all
835 user data, 'alias' only contain the shell aliases and no python
835 user data, 'alias' only contain the shell aliases and no python
836 objects, 'internal' contains objects used by IPython. The
836 objects, 'internal' contains objects used by IPython. The
837 'user_global' namespace is only used by embedded IPython instances,
837 'user_global' namespace is only used by embedded IPython instances,
838 and it contains module-level globals. You can add namespaces to the
838 and it contains module-level globals. You can add namespaces to the
839 search with -s or exclude them with -e (these options can be given
839 search with -s or exclude them with -e (these options can be given
840 more than once).
840 more than once).
841
841
842 Examples:
842 Examples:
843
843
844 %psearch a* -> objects beginning with an a
844 %psearch a* -> objects beginning with an a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch a* function -> all functions beginning with an a
846 %psearch a* function -> all functions beginning with an a
847 %psearch re.e* -> objects beginning with an e in module re
847 %psearch re.e* -> objects beginning with an e in module re
848 %psearch r*.e* -> objects that start with e in modules starting in r
848 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.* string -> all strings in modules beginning with r
849 %psearch r*.* string -> all strings in modules beginning with r
850
850
851 Case sensitve search:
851 Case sensitve search:
852
852
853 %psearch -c a* list all object beginning with lower case a
853 %psearch -c a* list all object beginning with lower case a
854
854
855 Show objects beginning with a single _:
855 Show objects beginning with a single _:
856
856
857 %psearch -a _* list objects beginning with a single underscore"""
857 %psearch -a _* list objects beginning with a single underscore"""
858 try:
858 try:
859 parameter_s = parameter_s.encode('ascii')
859 parameter_s = parameter_s.encode('ascii')
860 except UnicodeEncodeError:
860 except UnicodeEncodeError:
861 print 'Python identifiers can only contain ascii characters.'
861 print 'Python identifiers can only contain ascii characters.'
862 return
862 return
863
863
864 # default namespaces to be searched
864 # default namespaces to be searched
865 def_search = ['user','builtin']
865 def_search = ['user','builtin']
866
866
867 # Process options/args
867 # Process options/args
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opt = opts.get
869 opt = opts.get
870 shell = self.shell
870 shell = self.shell
871 psearch = shell.inspector.psearch
871 psearch = shell.inspector.psearch
872
872
873 # select case options
873 # select case options
874 if opts.has_key('i'):
874 if opts.has_key('i'):
875 ignore_case = True
875 ignore_case = True
876 elif opts.has_key('c'):
876 elif opts.has_key('c'):
877 ignore_case = False
877 ignore_case = False
878 else:
878 else:
879 ignore_case = not shell.wildcards_case_sensitive
879 ignore_case = not shell.wildcards_case_sensitive
880
880
881 # Build list of namespaces to search from user options
881 # Build list of namespaces to search from user options
882 def_search.extend(opt('s',[]))
882 def_search.extend(opt('s',[]))
883 ns_exclude = ns_exclude=opt('e',[])
883 ns_exclude = ns_exclude=opt('e',[])
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885
885
886 # Call the actual search
886 # Call the actual search
887 try:
887 try:
888 psearch(args,shell.ns_table,ns_search,
888 psearch(args,shell.ns_table,ns_search,
889 show_all=opt('a'),ignore_case=ignore_case)
889 show_all=opt('a'),ignore_case=ignore_case)
890 except:
890 except:
891 shell.showtraceback()
891 shell.showtraceback()
892
892
893 def magic_who_ls(self, parameter_s=''):
893 def magic_who_ls(self, parameter_s=''):
894 """Return a sorted list of all interactive variables.
894 """Return a sorted list of all interactive variables.
895
895
896 If arguments are given, only variables of types matching these
896 If arguments are given, only variables of types matching these
897 arguments are returned."""
897 arguments are returned."""
898
898
899 user_ns = self.shell.user_ns
899 user_ns = self.shell.user_ns
900 internal_ns = self.shell.internal_ns
900 internal_ns = self.shell.internal_ns
901 user_ns_hidden = self.shell.user_ns_hidden
901 user_ns_hidden = self.shell.user_ns_hidden
902 out = [ i for i in user_ns
902 out = [ i for i in user_ns
903 if not i.startswith('_') \
903 if not i.startswith('_') \
904 and not (i in internal_ns or i in user_ns_hidden) ]
904 and not (i in internal_ns or i in user_ns_hidden) ]
905
905
906 typelist = parameter_s.split()
906 typelist = parameter_s.split()
907 if typelist:
907 if typelist:
908 typeset = set(typelist)
908 typeset = set(typelist)
909 out = [i for i in out if type(i).__name__ in typeset]
909 out = [i for i in out if type(i).__name__ in typeset]
910
910
911 out.sort()
911 out.sort()
912 return out
912 return out
913
913
914 def magic_who(self, parameter_s=''):
914 def magic_who(self, parameter_s=''):
915 """Print all interactive variables, with some minimal formatting.
915 """Print all interactive variables, with some minimal formatting.
916
916
917 If any arguments are given, only variables whose type matches one of
917 If any arguments are given, only variables whose type matches one of
918 these are printed. For example:
918 these are printed. For example:
919
919
920 %who function str
920 %who function str
921
921
922 will only list functions and strings, excluding all other types of
922 will only list functions and strings, excluding all other types of
923 variables. To find the proper type names, simply use type(var) at a
923 variables. To find the proper type names, simply use type(var) at a
924 command line to see how python prints type names. For example:
924 command line to see how python prints type names. For example:
925
925
926 In [1]: type('hello')\\
926 In [1]: type('hello')\\
927 Out[1]: <type 'str'>
927 Out[1]: <type 'str'>
928
928
929 indicates that the type name for strings is 'str'.
929 indicates that the type name for strings is 'str'.
930
930
931 %who always excludes executed names loaded through your configuration
931 %who always excludes executed names loaded through your configuration
932 file and things which are internal to IPython.
932 file and things which are internal to IPython.
933
933
934 This is deliberate, as typically you may load many modules and the
934 This is deliberate, as typically you may load many modules and the
935 purpose of %who is to show you only what you've manually defined."""
935 purpose of %who is to show you only what you've manually defined."""
936
936
937 varlist = self.magic_who_ls(parameter_s)
937 varlist = self.magic_who_ls(parameter_s)
938 if not varlist:
938 if not varlist:
939 if parameter_s:
939 if parameter_s:
940 print 'No variables match your requested type.'
940 print 'No variables match your requested type.'
941 else:
941 else:
942 print 'Interactive namespace is empty.'
942 print 'Interactive namespace is empty.'
943 return
943 return
944
944
945 # if we have variables, move on...
945 # if we have variables, move on...
946 count = 0
946 count = 0
947 for i in varlist:
947 for i in varlist:
948 print i+'\t',
948 print i+'\t',
949 count += 1
949 count += 1
950 if count > 8:
950 if count > 8:
951 count = 0
951 count = 0
952 print
952 print
953 print
953 print
954
954
955 def magic_whos(self, parameter_s=''):
955 def magic_whos(self, parameter_s=''):
956 """Like %who, but gives some extra information about each variable.
956 """Like %who, but gives some extra information about each variable.
957
957
958 The same type filtering of %who can be applied here.
958 The same type filtering of %who can be applied here.
959
959
960 For all variables, the type is printed. Additionally it prints:
960 For all variables, the type is printed. Additionally it prints:
961
961
962 - For {},[],(): their length.
962 - For {},[],(): their length.
963
963
964 - For numpy and Numeric arrays, a summary with shape, number of
964 - For numpy and Numeric arrays, a summary with shape, number of
965 elements, typecode and size in memory.
965 elements, typecode and size in memory.
966
966
967 - Everything else: a string representation, snipping their middle if
967 - Everything else: a string representation, snipping their middle if
968 too long."""
968 too long."""
969
969
970 varnames = self.magic_who_ls(parameter_s)
970 varnames = self.magic_who_ls(parameter_s)
971 if not varnames:
971 if not varnames:
972 if parameter_s:
972 if parameter_s:
973 print 'No variables match your requested type.'
973 print 'No variables match your requested type.'
974 else:
974 else:
975 print 'Interactive namespace is empty.'
975 print 'Interactive namespace is empty.'
976 return
976 return
977
977
978 # if we have variables, move on...
978 # if we have variables, move on...
979
979
980 # for these types, show len() instead of data:
980 # for these types, show len() instead of data:
981 seq_types = [types.DictType,types.ListType,types.TupleType]
981 seq_types = [types.DictType,types.ListType,types.TupleType]
982
982
983 # for numpy/Numeric arrays, display summary info
983 # for numpy/Numeric arrays, display summary info
984 try:
984 try:
985 import numpy
985 import numpy
986 except ImportError:
986 except ImportError:
987 ndarray_type = None
987 ndarray_type = None
988 else:
988 else:
989 ndarray_type = numpy.ndarray.__name__
989 ndarray_type = numpy.ndarray.__name__
990 try:
990 try:
991 import Numeric
991 import Numeric
992 except ImportError:
992 except ImportError:
993 array_type = None
993 array_type = None
994 else:
994 else:
995 array_type = Numeric.ArrayType.__name__
995 array_type = Numeric.ArrayType.__name__
996
996
997 # Find all variable names and types so we can figure out column sizes
997 # Find all variable names and types so we can figure out column sizes
998 def get_vars(i):
998 def get_vars(i):
999 return self.shell.user_ns[i]
999 return self.shell.user_ns[i]
1000
1000
1001 # some types are well known and can be shorter
1001 # some types are well known and can be shorter
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 def type_name(v):
1003 def type_name(v):
1004 tn = type(v).__name__
1004 tn = type(v).__name__
1005 return abbrevs.get(tn,tn)
1005 return abbrevs.get(tn,tn)
1006
1006
1007 varlist = map(get_vars,varnames)
1007 varlist = map(get_vars,varnames)
1008
1008
1009 typelist = []
1009 typelist = []
1010 for vv in varlist:
1010 for vv in varlist:
1011 tt = type_name(vv)
1011 tt = type_name(vv)
1012
1012
1013 if tt=='instance':
1013 if tt=='instance':
1014 typelist.append( abbrevs.get(str(vv.__class__),
1014 typelist.append( abbrevs.get(str(vv.__class__),
1015 str(vv.__class__)))
1015 str(vv.__class__)))
1016 else:
1016 else:
1017 typelist.append(tt)
1017 typelist.append(tt)
1018
1018
1019 # column labels and # of spaces as separator
1019 # column labels and # of spaces as separator
1020 varlabel = 'Variable'
1020 varlabel = 'Variable'
1021 typelabel = 'Type'
1021 typelabel = 'Type'
1022 datalabel = 'Data/Info'
1022 datalabel = 'Data/Info'
1023 colsep = 3
1023 colsep = 3
1024 # variable format strings
1024 # variable format strings
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 # find the size of the columns to format the output nicely
1028 # find the size of the columns to format the output nicely
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 # table header
1031 # table header
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 # and the table itself
1034 # and the table itself
1035 kb = 1024
1035 kb = 1024
1036 Mb = 1048576 # kb**2
1036 Mb = 1048576 # kb**2
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 print itpl(vformat),
1038 print itpl(vformat),
1039 if vtype in seq_types:
1039 if vtype in seq_types:
1040 print len(var)
1040 print len(var)
1041 elif vtype in [array_type,ndarray_type]:
1041 elif vtype in [array_type,ndarray_type]:
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 if vtype==ndarray_type:
1043 if vtype==ndarray_type:
1044 # numpy
1044 # numpy
1045 vsize = var.size
1045 vsize = var.size
1046 vbytes = vsize*var.itemsize
1046 vbytes = vsize*var.itemsize
1047 vdtype = var.dtype
1047 vdtype = var.dtype
1048 else:
1048 else:
1049 # Numeric
1049 # Numeric
1050 vsize = Numeric.size(var)
1050 vsize = Numeric.size(var)
1051 vbytes = vsize*var.itemsize()
1051 vbytes = vsize*var.itemsize()
1052 vdtype = var.typecode()
1052 vdtype = var.typecode()
1053
1053
1054 if vbytes < 100000:
1054 if vbytes < 100000:
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1056 else:
1056 else:
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1058 if vbytes < Mb:
1058 if vbytes < Mb:
1059 print '(%s kb)' % (vbytes/kb,)
1059 print '(%s kb)' % (vbytes/kb,)
1060 else:
1060 else:
1061 print '(%s Mb)' % (vbytes/Mb,)
1061 print '(%s Mb)' % (vbytes/Mb,)
1062 else:
1062 else:
1063 try:
1063 try:
1064 vstr = str(var)
1064 vstr = str(var)
1065 except UnicodeEncodeError:
1065 except UnicodeEncodeError:
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 'backslashreplace')
1067 'backslashreplace')
1068 vstr = vstr.replace('\n','\\n')
1068 vstr = vstr.replace('\n','\\n')
1069 if len(vstr) < 50:
1069 if len(vstr) < 50:
1070 print vstr
1070 print vstr
1071 else:
1071 else:
1072 printpl(vfmt_short)
1072 printpl(vfmt_short)
1073
1073
1074 def magic_reset(self, parameter_s=''):
1074 def magic_reset(self, parameter_s=''):
1075 """Resets the namespace by removing all names defined by the user.
1075 """Resets the namespace by removing all names defined by the user.
1076
1076
1077 Input/Output history are left around in case you need them.
1077 Input/Output history are left around in case you need them.
1078
1078
1079 Parameters
1079 Parameters
1080 ----------
1080 ----------
1081 -y : force reset without asking for confirmation.
1081 -y : force reset without asking for confirmation.
1082
1082
1083 Examples
1083 Examples
1084 --------
1084 --------
1085 In [6]: a = 1
1085 In [6]: a = 1
1086
1086
1087 In [7]: a
1087 In [7]: a
1088 Out[7]: 1
1088 Out[7]: 1
1089
1089
1090 In [8]: 'a' in _ip.user_ns
1090 In [8]: 'a' in _ip.user_ns
1091 Out[8]: True
1091 Out[8]: True
1092
1092
1093 In [9]: %reset -f
1093 In [9]: %reset -f
1094
1094
1095 In [10]: 'a' in _ip.user_ns
1095 In [10]: 'a' in _ip.user_ns
1096 Out[10]: False
1096 Out[10]: False
1097 """
1097 """
1098
1098
1099 if parameter_s == '-f':
1099 if parameter_s == '-f':
1100 ans = True
1100 ans = True
1101 else:
1101 else:
1102 ans = self.shell.ask_yes_no(
1102 ans = self.shell.ask_yes_no(
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 if not ans:
1104 if not ans:
1105 print 'Nothing done.'
1105 print 'Nothing done.'
1106 return
1106 return
1107 user_ns = self.shell.user_ns
1107 user_ns = self.shell.user_ns
1108 for i in self.magic_who_ls():
1108 for i in self.magic_who_ls():
1109 del(user_ns[i])
1109 del(user_ns[i])
1110
1110
1111 # Also flush the private list of module references kept for script
1111 # Also flush the private list of module references kept for script
1112 # execution protection
1112 # execution protection
1113 self.shell.clear_main_mod_cache()
1113 self.shell.clear_main_mod_cache()
1114
1114
1115 def magic_reset_selective(self, parameter_s=''):
1116 """Resets the namespace by removing names defined by the user.
1117
1118 Input/Output history are left around in case you need them.
1119
1120 %reset_selective [-f] regex
1121
1122 No action is taken if regex is not included
1123
1124 Options
1125 -f : force reset without asking for confirmation.
1126
1127 Examples
1128 --------
1129
1130 In [1]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1131
1132 In [2]: who_ls
1133 Out[2]: ['a', 'b', 'b1', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1134
1135 In [3]: %reset_selective -f b[2-3]m
1136
1137 In [4]: who_ls
1138 Out[4]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c']
1139
1140 In [5]: %reset_selective -f d
1141
1142 In [6]: who_ls
1143 Out[6]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c']
1144
1145 In [7]: %reset_selective -f c
1146
1147 In [8]: who_ls
1148 Out[8]:['a', 'b', 'b1', 'b1m', 'b2s']
1149
1150 In [9]: %reset_selective -f b
1151
1152 In [10]: who_ls
1153 Out[10]: ['a']
1154
1155 """
1156
1157 opts, regex = self.parse_options(parameter_s,'f')
1158
1159 if opts.has_key('f'):
1160 ans = True
1161 else:
1162 ans = self.shell.ask_yes_no(
1163 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1164 if not ans:
1165 print 'Nothing done.'
1166 return
1167 user_ns = self.shell.user_ns
1168 if not regex:
1169 print 'No regex pattern specified. Nothing done.'
1170 return
1171 else:
1172 try:
1173 m = re.compile(regex)
1174 except TypeError:
1175 raise TypeError('regex must be a string or compiled pattern')
1176 for i in self.magic_who_ls():
1177 if m.search(i):
1178 del(user_ns[i])
1179
1115 def magic_logstart(self,parameter_s=''):
1180 def magic_logstart(self,parameter_s=''):
1116 """Start logging anywhere in a session.
1181 """Start logging anywhere in a session.
1117
1182
1118 %logstart [-o|-r|-t] [log_name [log_mode]]
1183 %logstart [-o|-r|-t] [log_name [log_mode]]
1119
1184
1120 If no name is given, it defaults to a file named 'ipython_log.py' in your
1185 If no name is given, it defaults to a file named 'ipython_log.py' in your
1121 current directory, in 'rotate' mode (see below).
1186 current directory, in 'rotate' mode (see below).
1122
1187
1123 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1188 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1124 history up to that point and then continues logging.
1189 history up to that point and then continues logging.
1125
1190
1126 %logstart takes a second optional parameter: logging mode. This can be one
1191 %logstart takes a second optional parameter: logging mode. This can be one
1127 of (note that the modes are given unquoted):\\
1192 of (note that the modes are given unquoted):\\
1128 append: well, that says it.\\
1193 append: well, that says it.\\
1129 backup: rename (if exists) to name~ and start name.\\
1194 backup: rename (if exists) to name~ and start name.\\
1130 global: single logfile in your home dir, appended to.\\
1195 global: single logfile in your home dir, appended to.\\
1131 over : overwrite existing log.\\
1196 over : overwrite existing log.\\
1132 rotate: create rotating logs name.1~, name.2~, etc.
1197 rotate: create rotating logs name.1~, name.2~, etc.
1133
1198
1134 Options:
1199 Options:
1135
1200
1136 -o: log also IPython's output. In this mode, all commands which
1201 -o: log also IPython's output. In this mode, all commands which
1137 generate an Out[NN] prompt are recorded to the logfile, right after
1202 generate an Out[NN] prompt are recorded to the logfile, right after
1138 their corresponding input line. The output lines are always
1203 their corresponding input line. The output lines are always
1139 prepended with a '#[Out]# ' marker, so that the log remains valid
1204 prepended with a '#[Out]# ' marker, so that the log remains valid
1140 Python code.
1205 Python code.
1141
1206
1142 Since this marker is always the same, filtering only the output from
1207 Since this marker is always the same, filtering only the output from
1143 a log is very easy, using for example a simple awk call:
1208 a log is very easy, using for example a simple awk call:
1144
1209
1145 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1210 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1146
1211
1147 -r: log 'raw' input. Normally, IPython's logs contain the processed
1212 -r: log 'raw' input. Normally, IPython's logs contain the processed
1148 input, so that user lines are logged in their final form, converted
1213 input, so that user lines are logged in their final form, converted
1149 into valid Python. For example, %Exit is logged as
1214 into valid Python. For example, %Exit is logged as
1150 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1215 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1151 exactly as typed, with no transformations applied.
1216 exactly as typed, with no transformations applied.
1152
1217
1153 -t: put timestamps before each input line logged (these are put in
1218 -t: put timestamps before each input line logged (these are put in
1154 comments)."""
1219 comments)."""
1155
1220
1156 opts,par = self.parse_options(parameter_s,'ort')
1221 opts,par = self.parse_options(parameter_s,'ort')
1157 log_output = 'o' in opts
1222 log_output = 'o' in opts
1158 log_raw_input = 'r' in opts
1223 log_raw_input = 'r' in opts
1159 timestamp = 't' in opts
1224 timestamp = 't' in opts
1160
1225
1161 logger = self.shell.logger
1226 logger = self.shell.logger
1162
1227
1163 # if no args are given, the defaults set in the logger constructor by
1228 # if no args are given, the defaults set in the logger constructor by
1164 # ipytohn remain valid
1229 # ipytohn remain valid
1165 if par:
1230 if par:
1166 try:
1231 try:
1167 logfname,logmode = par.split()
1232 logfname,logmode = par.split()
1168 except:
1233 except:
1169 logfname = par
1234 logfname = par
1170 logmode = 'backup'
1235 logmode = 'backup'
1171 else:
1236 else:
1172 logfname = logger.logfname
1237 logfname = logger.logfname
1173 logmode = logger.logmode
1238 logmode = logger.logmode
1174 # put logfname into rc struct as if it had been called on the command
1239 # put logfname into rc struct as if it had been called on the command
1175 # line, so it ends up saved in the log header Save it in case we need
1240 # line, so it ends up saved in the log header Save it in case we need
1176 # to restore it...
1241 # to restore it...
1177 old_logfile = self.shell.logfile
1242 old_logfile = self.shell.logfile
1178 if logfname:
1243 if logfname:
1179 logfname = os.path.expanduser(logfname)
1244 logfname = os.path.expanduser(logfname)
1180 self.shell.logfile = logfname
1245 self.shell.logfile = logfname
1181
1246
1182 loghead = '# IPython log file\n\n'
1247 loghead = '# IPython log file\n\n'
1183 try:
1248 try:
1184 started = logger.logstart(logfname,loghead,logmode,
1249 started = logger.logstart(logfname,loghead,logmode,
1185 log_output,timestamp,log_raw_input)
1250 log_output,timestamp,log_raw_input)
1186 except:
1251 except:
1187 self.shell.logfile = old_logfile
1252 self.shell.logfile = old_logfile
1188 warn("Couldn't start log: %s" % sys.exc_info()[1])
1253 warn("Couldn't start log: %s" % sys.exc_info()[1])
1189 else:
1254 else:
1190 # log input history up to this point, optionally interleaving
1255 # log input history up to this point, optionally interleaving
1191 # output if requested
1256 # output if requested
1192
1257
1193 if timestamp:
1258 if timestamp:
1194 # disable timestamping for the previous history, since we've
1259 # disable timestamping for the previous history, since we've
1195 # lost those already (no time machine here).
1260 # lost those already (no time machine here).
1196 logger.timestamp = False
1261 logger.timestamp = False
1197
1262
1198 if log_raw_input:
1263 if log_raw_input:
1199 input_hist = self.shell.input_hist_raw
1264 input_hist = self.shell.input_hist_raw
1200 else:
1265 else:
1201 input_hist = self.shell.input_hist
1266 input_hist = self.shell.input_hist
1202
1267
1203 if log_output:
1268 if log_output:
1204 log_write = logger.log_write
1269 log_write = logger.log_write
1205 output_hist = self.shell.output_hist
1270 output_hist = self.shell.output_hist
1206 for n in range(1,len(input_hist)-1):
1271 for n in range(1,len(input_hist)-1):
1207 log_write(input_hist[n].rstrip())
1272 log_write(input_hist[n].rstrip())
1208 if n in output_hist:
1273 if n in output_hist:
1209 log_write(repr(output_hist[n]),'output')
1274 log_write(repr(output_hist[n]),'output')
1210 else:
1275 else:
1211 logger.log_write(input_hist[1:])
1276 logger.log_write(input_hist[1:])
1212 if timestamp:
1277 if timestamp:
1213 # re-enable timestamping
1278 # re-enable timestamping
1214 logger.timestamp = True
1279 logger.timestamp = True
1215
1280
1216 print ('Activating auto-logging. '
1281 print ('Activating auto-logging. '
1217 'Current session state plus future input saved.')
1282 'Current session state plus future input saved.')
1218 logger.logstate()
1283 logger.logstate()
1219
1284
1220 def magic_logstop(self,parameter_s=''):
1285 def magic_logstop(self,parameter_s=''):
1221 """Fully stop logging and close log file.
1286 """Fully stop logging and close log file.
1222
1287
1223 In order to start logging again, a new %logstart call needs to be made,
1288 In order to start logging again, a new %logstart call needs to be made,
1224 possibly (though not necessarily) with a new filename, mode and other
1289 possibly (though not necessarily) with a new filename, mode and other
1225 options."""
1290 options."""
1226 self.logger.logstop()
1291 self.logger.logstop()
1227
1292
1228 def magic_logoff(self,parameter_s=''):
1293 def magic_logoff(self,parameter_s=''):
1229 """Temporarily stop logging.
1294 """Temporarily stop logging.
1230
1295
1231 You must have previously started logging."""
1296 You must have previously started logging."""
1232 self.shell.logger.switch_log(0)
1297 self.shell.logger.switch_log(0)
1233
1298
1234 def magic_logon(self,parameter_s=''):
1299 def magic_logon(self,parameter_s=''):
1235 """Restart logging.
1300 """Restart logging.
1236
1301
1237 This function is for restarting logging which you've temporarily
1302 This function is for restarting logging which you've temporarily
1238 stopped with %logoff. For starting logging for the first time, you
1303 stopped with %logoff. For starting logging for the first time, you
1239 must use the %logstart function, which allows you to specify an
1304 must use the %logstart function, which allows you to specify an
1240 optional log filename."""
1305 optional log filename."""
1241
1306
1242 self.shell.logger.switch_log(1)
1307 self.shell.logger.switch_log(1)
1243
1308
1244 def magic_logstate(self,parameter_s=''):
1309 def magic_logstate(self,parameter_s=''):
1245 """Print the status of the logging system."""
1310 """Print the status of the logging system."""
1246
1311
1247 self.shell.logger.logstate()
1312 self.shell.logger.logstate()
1248
1313
1249 def magic_pdb(self, parameter_s=''):
1314 def magic_pdb(self, parameter_s=''):
1250 """Control the automatic calling of the pdb interactive debugger.
1315 """Control the automatic calling of the pdb interactive debugger.
1251
1316
1252 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1317 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1253 argument it works as a toggle.
1318 argument it works as a toggle.
1254
1319
1255 When an exception is triggered, IPython can optionally call the
1320 When an exception is triggered, IPython can optionally call the
1256 interactive pdb debugger after the traceback printout. %pdb toggles
1321 interactive pdb debugger after the traceback printout. %pdb toggles
1257 this feature on and off.
1322 this feature on and off.
1258
1323
1259 The initial state of this feature is set in your ipythonrc
1324 The initial state of this feature is set in your ipythonrc
1260 configuration file (the variable is called 'pdb').
1325 configuration file (the variable is called 'pdb').
1261
1326
1262 If you want to just activate the debugger AFTER an exception has fired,
1327 If you want to just activate the debugger AFTER an exception has fired,
1263 without having to type '%pdb on' and rerunning your code, you can use
1328 without having to type '%pdb on' and rerunning your code, you can use
1264 the %debug magic."""
1329 the %debug magic."""
1265
1330
1266 par = parameter_s.strip().lower()
1331 par = parameter_s.strip().lower()
1267
1332
1268 if par:
1333 if par:
1269 try:
1334 try:
1270 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1335 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1271 except KeyError:
1336 except KeyError:
1272 print ('Incorrect argument. Use on/1, off/0, '
1337 print ('Incorrect argument. Use on/1, off/0, '
1273 'or nothing for a toggle.')
1338 'or nothing for a toggle.')
1274 return
1339 return
1275 else:
1340 else:
1276 # toggle
1341 # toggle
1277 new_pdb = not self.shell.call_pdb
1342 new_pdb = not self.shell.call_pdb
1278
1343
1279 # set on the shell
1344 # set on the shell
1280 self.shell.call_pdb = new_pdb
1345 self.shell.call_pdb = new_pdb
1281 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1346 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1282
1347
1283 def magic_debug(self, parameter_s=''):
1348 def magic_debug(self, parameter_s=''):
1284 """Activate the interactive debugger in post-mortem mode.
1349 """Activate the interactive debugger in post-mortem mode.
1285
1350
1286 If an exception has just occurred, this lets you inspect its stack
1351 If an exception has just occurred, this lets you inspect its stack
1287 frames interactively. Note that this will always work only on the last
1352 frames interactively. Note that this will always work only on the last
1288 traceback that occurred, so you must call this quickly after an
1353 traceback that occurred, so you must call this quickly after an
1289 exception that you wish to inspect has fired, because if another one
1354 exception that you wish to inspect has fired, because if another one
1290 occurs, it clobbers the previous one.
1355 occurs, it clobbers the previous one.
1291
1356
1292 If you want IPython to automatically do this on every exception, see
1357 If you want IPython to automatically do this on every exception, see
1293 the %pdb magic for more details.
1358 the %pdb magic for more details.
1294 """
1359 """
1295 self.shell.debugger(force=True)
1360 self.shell.debugger(force=True)
1296
1361
1297 @testdec.skip_doctest
1362 @testdec.skip_doctest
1298 def magic_prun(self, parameter_s ='',user_mode=1,
1363 def magic_prun(self, parameter_s ='',user_mode=1,
1299 opts=None,arg_lst=None,prog_ns=None):
1364 opts=None,arg_lst=None,prog_ns=None):
1300
1365
1301 """Run a statement through the python code profiler.
1366 """Run a statement through the python code profiler.
1302
1367
1303 Usage:
1368 Usage:
1304 %prun [options] statement
1369 %prun [options] statement
1305
1370
1306 The given statement (which doesn't require quote marks) is run via the
1371 The given statement (which doesn't require quote marks) is run via the
1307 python profiler in a manner similar to the profile.run() function.
1372 python profiler in a manner similar to the profile.run() function.
1308 Namespaces are internally managed to work correctly; profile.run
1373 Namespaces are internally managed to work correctly; profile.run
1309 cannot be used in IPython because it makes certain assumptions about
1374 cannot be used in IPython because it makes certain assumptions about
1310 namespaces which do not hold under IPython.
1375 namespaces which do not hold under IPython.
1311
1376
1312 Options:
1377 Options:
1313
1378
1314 -l <limit>: you can place restrictions on what or how much of the
1379 -l <limit>: you can place restrictions on what or how much of the
1315 profile gets printed. The limit value can be:
1380 profile gets printed. The limit value can be:
1316
1381
1317 * A string: only information for function names containing this string
1382 * A string: only information for function names containing this string
1318 is printed.
1383 is printed.
1319
1384
1320 * An integer: only these many lines are printed.
1385 * An integer: only these many lines are printed.
1321
1386
1322 * A float (between 0 and 1): this fraction of the report is printed
1387 * A float (between 0 and 1): this fraction of the report is printed
1323 (for example, use a limit of 0.4 to see the topmost 40% only).
1388 (for example, use a limit of 0.4 to see the topmost 40% only).
1324
1389
1325 You can combine several limits with repeated use of the option. For
1390 You can combine several limits with repeated use of the option. For
1326 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1391 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1327 information about class constructors.
1392 information about class constructors.
1328
1393
1329 -r: return the pstats.Stats object generated by the profiling. This
1394 -r: return the pstats.Stats object generated by the profiling. This
1330 object has all the information about the profile in it, and you can
1395 object has all the information about the profile in it, and you can
1331 later use it for further analysis or in other functions.
1396 later use it for further analysis or in other functions.
1332
1397
1333 -s <key>: sort profile by given key. You can provide more than one key
1398 -s <key>: sort profile by given key. You can provide more than one key
1334 by using the option several times: '-s key1 -s key2 -s key3...'. The
1399 by using the option several times: '-s key1 -s key2 -s key3...'. The
1335 default sorting key is 'time'.
1400 default sorting key is 'time'.
1336
1401
1337 The following is copied verbatim from the profile documentation
1402 The following is copied verbatim from the profile documentation
1338 referenced below:
1403 referenced below:
1339
1404
1340 When more than one key is provided, additional keys are used as
1405 When more than one key is provided, additional keys are used as
1341 secondary criteria when the there is equality in all keys selected
1406 secondary criteria when the there is equality in all keys selected
1342 before them.
1407 before them.
1343
1408
1344 Abbreviations can be used for any key names, as long as the
1409 Abbreviations can be used for any key names, as long as the
1345 abbreviation is unambiguous. The following are the keys currently
1410 abbreviation is unambiguous. The following are the keys currently
1346 defined:
1411 defined:
1347
1412
1348 Valid Arg Meaning
1413 Valid Arg Meaning
1349 "calls" call count
1414 "calls" call count
1350 "cumulative" cumulative time
1415 "cumulative" cumulative time
1351 "file" file name
1416 "file" file name
1352 "module" file name
1417 "module" file name
1353 "pcalls" primitive call count
1418 "pcalls" primitive call count
1354 "line" line number
1419 "line" line number
1355 "name" function name
1420 "name" function name
1356 "nfl" name/file/line
1421 "nfl" name/file/line
1357 "stdname" standard name
1422 "stdname" standard name
1358 "time" internal time
1423 "time" internal time
1359
1424
1360 Note that all sorts on statistics are in descending order (placing
1425 Note that all sorts on statistics are in descending order (placing
1361 most time consuming items first), where as name, file, and line number
1426 most time consuming items first), where as name, file, and line number
1362 searches are in ascending order (i.e., alphabetical). The subtle
1427 searches are in ascending order (i.e., alphabetical). The subtle
1363 distinction between "nfl" and "stdname" is that the standard name is a
1428 distinction between "nfl" and "stdname" is that the standard name is a
1364 sort of the name as printed, which means that the embedded line
1429 sort of the name as printed, which means that the embedded line
1365 numbers get compared in an odd way. For example, lines 3, 20, and 40
1430 numbers get compared in an odd way. For example, lines 3, 20, and 40
1366 would (if the file names were the same) appear in the string order
1431 would (if the file names were the same) appear in the string order
1367 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1432 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1368 line numbers. In fact, sort_stats("nfl") is the same as
1433 line numbers. In fact, sort_stats("nfl") is the same as
1369 sort_stats("name", "file", "line").
1434 sort_stats("name", "file", "line").
1370
1435
1371 -T <filename>: save profile results as shown on screen to a text
1436 -T <filename>: save profile results as shown on screen to a text
1372 file. The profile is still shown on screen.
1437 file. The profile is still shown on screen.
1373
1438
1374 -D <filename>: save (via dump_stats) profile statistics to given
1439 -D <filename>: save (via dump_stats) profile statistics to given
1375 filename. This data is in a format understod by the pstats module, and
1440 filename. This data is in a format understod by the pstats module, and
1376 is generated by a call to the dump_stats() method of profile
1441 is generated by a call to the dump_stats() method of profile
1377 objects. The profile is still shown on screen.
1442 objects. The profile is still shown on screen.
1378
1443
1379 If you want to run complete programs under the profiler's control, use
1444 If you want to run complete programs under the profiler's control, use
1380 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1445 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1381 contains profiler specific options as described here.
1446 contains profiler specific options as described here.
1382
1447
1383 You can read the complete documentation for the profile module with::
1448 You can read the complete documentation for the profile module with::
1384
1449
1385 In [1]: import profile; profile.help()
1450 In [1]: import profile; profile.help()
1386 """
1451 """
1387
1452
1388 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1453 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1389 # protect user quote marks
1454 # protect user quote marks
1390 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1455 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1391
1456
1392 if user_mode: # regular user call
1457 if user_mode: # regular user call
1393 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1458 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1394 list_all=1)
1459 list_all=1)
1395 namespace = self.shell.user_ns
1460 namespace = self.shell.user_ns
1396 else: # called to run a program by %run -p
1461 else: # called to run a program by %run -p
1397 try:
1462 try:
1398 filename = get_py_filename(arg_lst[0])
1463 filename = get_py_filename(arg_lst[0])
1399 except IOError,msg:
1464 except IOError,msg:
1400 error(msg)
1465 error(msg)
1401 return
1466 return
1402
1467
1403 arg_str = 'execfile(filename,prog_ns)'
1468 arg_str = 'execfile(filename,prog_ns)'
1404 namespace = locals()
1469 namespace = locals()
1405
1470
1406 opts.merge(opts_def)
1471 opts.merge(opts_def)
1407
1472
1408 prof = profile.Profile()
1473 prof = profile.Profile()
1409 try:
1474 try:
1410 prof = prof.runctx(arg_str,namespace,namespace)
1475 prof = prof.runctx(arg_str,namespace,namespace)
1411 sys_exit = ''
1476 sys_exit = ''
1412 except SystemExit:
1477 except SystemExit:
1413 sys_exit = """*** SystemExit exception caught in code being profiled."""
1478 sys_exit = """*** SystemExit exception caught in code being profiled."""
1414
1479
1415 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1480 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1416
1481
1417 lims = opts.l
1482 lims = opts.l
1418 if lims:
1483 if lims:
1419 lims = [] # rebuild lims with ints/floats/strings
1484 lims = [] # rebuild lims with ints/floats/strings
1420 for lim in opts.l:
1485 for lim in opts.l:
1421 try:
1486 try:
1422 lims.append(int(lim))
1487 lims.append(int(lim))
1423 except ValueError:
1488 except ValueError:
1424 try:
1489 try:
1425 lims.append(float(lim))
1490 lims.append(float(lim))
1426 except ValueError:
1491 except ValueError:
1427 lims.append(lim)
1492 lims.append(lim)
1428
1493
1429 # Trap output.
1494 # Trap output.
1430 stdout_trap = StringIO()
1495 stdout_trap = StringIO()
1431
1496
1432 if hasattr(stats,'stream'):
1497 if hasattr(stats,'stream'):
1433 # In newer versions of python, the stats object has a 'stream'
1498 # In newer versions of python, the stats object has a 'stream'
1434 # attribute to write into.
1499 # attribute to write into.
1435 stats.stream = stdout_trap
1500 stats.stream = stdout_trap
1436 stats.print_stats(*lims)
1501 stats.print_stats(*lims)
1437 else:
1502 else:
1438 # For older versions, we manually redirect stdout during printing
1503 # For older versions, we manually redirect stdout during printing
1439 sys_stdout = sys.stdout
1504 sys_stdout = sys.stdout
1440 try:
1505 try:
1441 sys.stdout = stdout_trap
1506 sys.stdout = stdout_trap
1442 stats.print_stats(*lims)
1507 stats.print_stats(*lims)
1443 finally:
1508 finally:
1444 sys.stdout = sys_stdout
1509 sys.stdout = sys_stdout
1445
1510
1446 output = stdout_trap.getvalue()
1511 output = stdout_trap.getvalue()
1447 output = output.rstrip()
1512 output = output.rstrip()
1448
1513
1449 page(output,screen_lines=self.shell.usable_screen_length)
1514 page(output,screen_lines=self.shell.usable_screen_length)
1450 print sys_exit,
1515 print sys_exit,
1451
1516
1452 dump_file = opts.D[0]
1517 dump_file = opts.D[0]
1453 text_file = opts.T[0]
1518 text_file = opts.T[0]
1454 if dump_file:
1519 if dump_file:
1455 prof.dump_stats(dump_file)
1520 prof.dump_stats(dump_file)
1456 print '\n*** Profile stats marshalled to file',\
1521 print '\n*** Profile stats marshalled to file',\
1457 `dump_file`+'.',sys_exit
1522 `dump_file`+'.',sys_exit
1458 if text_file:
1523 if text_file:
1459 pfile = file(text_file,'w')
1524 pfile = file(text_file,'w')
1460 pfile.write(output)
1525 pfile.write(output)
1461 pfile.close()
1526 pfile.close()
1462 print '\n*** Profile printout saved to text file',\
1527 print '\n*** Profile printout saved to text file',\
1463 `text_file`+'.',sys_exit
1528 `text_file`+'.',sys_exit
1464
1529
1465 if opts.has_key('r'):
1530 if opts.has_key('r'):
1466 return stats
1531 return stats
1467 else:
1532 else:
1468 return None
1533 return None
1469
1534
1470 @testdec.skip_doctest
1535 @testdec.skip_doctest
1471 def magic_run(self, parameter_s ='',runner=None,
1536 def magic_run(self, parameter_s ='',runner=None,
1472 file_finder=get_py_filename):
1537 file_finder=get_py_filename):
1473 """Run the named file inside IPython as a program.
1538 """Run the named file inside IPython as a program.
1474
1539
1475 Usage:\\
1540 Usage:\\
1476 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1541 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1477
1542
1478 Parameters after the filename are passed as command-line arguments to
1543 Parameters after the filename are passed as command-line arguments to
1479 the program (put in sys.argv). Then, control returns to IPython's
1544 the program (put in sys.argv). Then, control returns to IPython's
1480 prompt.
1545 prompt.
1481
1546
1482 This is similar to running at a system prompt:\\
1547 This is similar to running at a system prompt:\\
1483 $ python file args\\
1548 $ python file args\\
1484 but with the advantage of giving you IPython's tracebacks, and of
1549 but with the advantage of giving you IPython's tracebacks, and of
1485 loading all variables into your interactive namespace for further use
1550 loading all variables into your interactive namespace for further use
1486 (unless -p is used, see below).
1551 (unless -p is used, see below).
1487
1552
1488 The file is executed in a namespace initially consisting only of
1553 The file is executed in a namespace initially consisting only of
1489 __name__=='__main__' and sys.argv constructed as indicated. It thus
1554 __name__=='__main__' and sys.argv constructed as indicated. It thus
1490 sees its environment as if it were being run as a stand-alone program
1555 sees its environment as if it were being run as a stand-alone program
1491 (except for sharing global objects such as previously imported
1556 (except for sharing global objects such as previously imported
1492 modules). But after execution, the IPython interactive namespace gets
1557 modules). But after execution, the IPython interactive namespace gets
1493 updated with all variables defined in the program (except for __name__
1558 updated with all variables defined in the program (except for __name__
1494 and sys.argv). This allows for very convenient loading of code for
1559 and sys.argv). This allows for very convenient loading of code for
1495 interactive work, while giving each program a 'clean sheet' to run in.
1560 interactive work, while giving each program a 'clean sheet' to run in.
1496
1561
1497 Options:
1562 Options:
1498
1563
1499 -n: __name__ is NOT set to '__main__', but to the running file's name
1564 -n: __name__ is NOT set to '__main__', but to the running file's name
1500 without extension (as python does under import). This allows running
1565 without extension (as python does under import). This allows running
1501 scripts and reloading the definitions in them without calling code
1566 scripts and reloading the definitions in them without calling code
1502 protected by an ' if __name__ == "__main__" ' clause.
1567 protected by an ' if __name__ == "__main__" ' clause.
1503
1568
1504 -i: run the file in IPython's namespace instead of an empty one. This
1569 -i: run the file in IPython's namespace instead of an empty one. This
1505 is useful if you are experimenting with code written in a text editor
1570 is useful if you are experimenting with code written in a text editor
1506 which depends on variables defined interactively.
1571 which depends on variables defined interactively.
1507
1572
1508 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1573 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1509 being run. This is particularly useful if IPython is being used to
1574 being run. This is particularly useful if IPython is being used to
1510 run unittests, which always exit with a sys.exit() call. In such
1575 run unittests, which always exit with a sys.exit() call. In such
1511 cases you are interested in the output of the test results, not in
1576 cases you are interested in the output of the test results, not in
1512 seeing a traceback of the unittest module.
1577 seeing a traceback of the unittest module.
1513
1578
1514 -t: print timing information at the end of the run. IPython will give
1579 -t: print timing information at the end of the run. IPython will give
1515 you an estimated CPU time consumption for your script, which under
1580 you an estimated CPU time consumption for your script, which under
1516 Unix uses the resource module to avoid the wraparound problems of
1581 Unix uses the resource module to avoid the wraparound problems of
1517 time.clock(). Under Unix, an estimate of time spent on system tasks
1582 time.clock(). Under Unix, an estimate of time spent on system tasks
1518 is also given (for Windows platforms this is reported as 0.0).
1583 is also given (for Windows platforms this is reported as 0.0).
1519
1584
1520 If -t is given, an additional -N<N> option can be given, where <N>
1585 If -t is given, an additional -N<N> option can be given, where <N>
1521 must be an integer indicating how many times you want the script to
1586 must be an integer indicating how many times you want the script to
1522 run. The final timing report will include total and per run results.
1587 run. The final timing report will include total and per run results.
1523
1588
1524 For example (testing the script uniq_stable.py):
1589 For example (testing the script uniq_stable.py):
1525
1590
1526 In [1]: run -t uniq_stable
1591 In [1]: run -t uniq_stable
1527
1592
1528 IPython CPU timings (estimated):\\
1593 IPython CPU timings (estimated):\\
1529 User : 0.19597 s.\\
1594 User : 0.19597 s.\\
1530 System: 0.0 s.\\
1595 System: 0.0 s.\\
1531
1596
1532 In [2]: run -t -N5 uniq_stable
1597 In [2]: run -t -N5 uniq_stable
1533
1598
1534 IPython CPU timings (estimated):\\
1599 IPython CPU timings (estimated):\\
1535 Total runs performed: 5\\
1600 Total runs performed: 5\\
1536 Times : Total Per run\\
1601 Times : Total Per run\\
1537 User : 0.910862 s, 0.1821724 s.\\
1602 User : 0.910862 s, 0.1821724 s.\\
1538 System: 0.0 s, 0.0 s.
1603 System: 0.0 s, 0.0 s.
1539
1604
1540 -d: run your program under the control of pdb, the Python debugger.
1605 -d: run your program under the control of pdb, the Python debugger.
1541 This allows you to execute your program step by step, watch variables,
1606 This allows you to execute your program step by step, watch variables,
1542 etc. Internally, what IPython does is similar to calling:
1607 etc. Internally, what IPython does is similar to calling:
1543
1608
1544 pdb.run('execfile("YOURFILENAME")')
1609 pdb.run('execfile("YOURFILENAME")')
1545
1610
1546 with a breakpoint set on line 1 of your file. You can change the line
1611 with a breakpoint set on line 1 of your file. You can change the line
1547 number for this automatic breakpoint to be <N> by using the -bN option
1612 number for this automatic breakpoint to be <N> by using the -bN option
1548 (where N must be an integer). For example:
1613 (where N must be an integer). For example:
1549
1614
1550 %run -d -b40 myscript
1615 %run -d -b40 myscript
1551
1616
1552 will set the first breakpoint at line 40 in myscript.py. Note that
1617 will set the first breakpoint at line 40 in myscript.py. Note that
1553 the first breakpoint must be set on a line which actually does
1618 the first breakpoint must be set on a line which actually does
1554 something (not a comment or docstring) for it to stop execution.
1619 something (not a comment or docstring) for it to stop execution.
1555
1620
1556 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1621 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1557 first enter 'c' (without qoutes) to start execution up to the first
1622 first enter 'c' (without qoutes) to start execution up to the first
1558 breakpoint.
1623 breakpoint.
1559
1624
1560 Entering 'help' gives information about the use of the debugger. You
1625 Entering 'help' gives information about the use of the debugger. You
1561 can easily see pdb's full documentation with "import pdb;pdb.help()"
1626 can easily see pdb's full documentation with "import pdb;pdb.help()"
1562 at a prompt.
1627 at a prompt.
1563
1628
1564 -p: run program under the control of the Python profiler module (which
1629 -p: run program under the control of the Python profiler module (which
1565 prints a detailed report of execution times, function calls, etc).
1630 prints a detailed report of execution times, function calls, etc).
1566
1631
1567 You can pass other options after -p which affect the behavior of the
1632 You can pass other options after -p which affect the behavior of the
1568 profiler itself. See the docs for %prun for details.
1633 profiler itself. See the docs for %prun for details.
1569
1634
1570 In this mode, the program's variables do NOT propagate back to the
1635 In this mode, the program's variables do NOT propagate back to the
1571 IPython interactive namespace (because they remain in the namespace
1636 IPython interactive namespace (because they remain in the namespace
1572 where the profiler executes them).
1637 where the profiler executes them).
1573
1638
1574 Internally this triggers a call to %prun, see its documentation for
1639 Internally this triggers a call to %prun, see its documentation for
1575 details on the options available specifically for profiling.
1640 details on the options available specifically for profiling.
1576
1641
1577 There is one special usage for which the text above doesn't apply:
1642 There is one special usage for which the text above doesn't apply:
1578 if the filename ends with .ipy, the file is run as ipython script,
1643 if the filename ends with .ipy, the file is run as ipython script,
1579 just as if the commands were written on IPython prompt.
1644 just as if the commands were written on IPython prompt.
1580 """
1645 """
1581
1646
1582 # get arguments and set sys.argv for program to be run.
1647 # get arguments and set sys.argv for program to be run.
1583 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1648 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1584 mode='list',list_all=1)
1649 mode='list',list_all=1)
1585
1650
1586 try:
1651 try:
1587 filename = file_finder(arg_lst[0])
1652 filename = file_finder(arg_lst[0])
1588 except IndexError:
1653 except IndexError:
1589 warn('you must provide at least a filename.')
1654 warn('you must provide at least a filename.')
1590 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1655 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1591 return
1656 return
1592 except IOError,msg:
1657 except IOError,msg:
1593 error(msg)
1658 error(msg)
1594 return
1659 return
1595
1660
1596 if filename.lower().endswith('.ipy'):
1661 if filename.lower().endswith('.ipy'):
1597 self.shell.safe_execfile_ipy(filename)
1662 self.shell.safe_execfile_ipy(filename)
1598 return
1663 return
1599
1664
1600 # Control the response to exit() calls made by the script being run
1665 # Control the response to exit() calls made by the script being run
1601 exit_ignore = opts.has_key('e')
1666 exit_ignore = opts.has_key('e')
1602
1667
1603 # Make sure that the running script gets a proper sys.argv as if it
1668 # Make sure that the running script gets a proper sys.argv as if it
1604 # were run from a system shell.
1669 # were run from a system shell.
1605 save_argv = sys.argv # save it for later restoring
1670 save_argv = sys.argv # save it for later restoring
1606 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1671 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1607
1672
1608 if opts.has_key('i'):
1673 if opts.has_key('i'):
1609 # Run in user's interactive namespace
1674 # Run in user's interactive namespace
1610 prog_ns = self.shell.user_ns
1675 prog_ns = self.shell.user_ns
1611 __name__save = self.shell.user_ns['__name__']
1676 __name__save = self.shell.user_ns['__name__']
1612 prog_ns['__name__'] = '__main__'
1677 prog_ns['__name__'] = '__main__'
1613 main_mod = self.shell.new_main_mod(prog_ns)
1678 main_mod = self.shell.new_main_mod(prog_ns)
1614 else:
1679 else:
1615 # Run in a fresh, empty namespace
1680 # Run in a fresh, empty namespace
1616 if opts.has_key('n'):
1681 if opts.has_key('n'):
1617 name = os.path.splitext(os.path.basename(filename))[0]
1682 name = os.path.splitext(os.path.basename(filename))[0]
1618 else:
1683 else:
1619 name = '__main__'
1684 name = '__main__'
1620
1685
1621 main_mod = self.shell.new_main_mod()
1686 main_mod = self.shell.new_main_mod()
1622 prog_ns = main_mod.__dict__
1687 prog_ns = main_mod.__dict__
1623 prog_ns['__name__'] = name
1688 prog_ns['__name__'] = name
1624
1689
1625 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1690 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1626 # set the __file__ global in the script's namespace
1691 # set the __file__ global in the script's namespace
1627 prog_ns['__file__'] = filename
1692 prog_ns['__file__'] = filename
1628
1693
1629 # pickle fix. See iplib for an explanation. But we need to make sure
1694 # pickle fix. See iplib for an explanation. But we need to make sure
1630 # that, if we overwrite __main__, we replace it at the end
1695 # that, if we overwrite __main__, we replace it at the end
1631 main_mod_name = prog_ns['__name__']
1696 main_mod_name = prog_ns['__name__']
1632
1697
1633 if main_mod_name == '__main__':
1698 if main_mod_name == '__main__':
1634 restore_main = sys.modules['__main__']
1699 restore_main = sys.modules['__main__']
1635 else:
1700 else:
1636 restore_main = False
1701 restore_main = False
1637
1702
1638 # This needs to be undone at the end to prevent holding references to
1703 # This needs to be undone at the end to prevent holding references to
1639 # every single object ever created.
1704 # every single object ever created.
1640 sys.modules[main_mod_name] = main_mod
1705 sys.modules[main_mod_name] = main_mod
1641
1706
1642 stats = None
1707 stats = None
1643 try:
1708 try:
1644 self.shell.savehist()
1709 self.shell.savehist()
1645
1710
1646 if opts.has_key('p'):
1711 if opts.has_key('p'):
1647 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1712 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1648 else:
1713 else:
1649 if opts.has_key('d'):
1714 if opts.has_key('d'):
1650 deb = debugger.Pdb(self.shell.colors)
1715 deb = debugger.Pdb(self.shell.colors)
1651 # reset Breakpoint state, which is moronically kept
1716 # reset Breakpoint state, which is moronically kept
1652 # in a class
1717 # in a class
1653 bdb.Breakpoint.next = 1
1718 bdb.Breakpoint.next = 1
1654 bdb.Breakpoint.bplist = {}
1719 bdb.Breakpoint.bplist = {}
1655 bdb.Breakpoint.bpbynumber = [None]
1720 bdb.Breakpoint.bpbynumber = [None]
1656 # Set an initial breakpoint to stop execution
1721 # Set an initial breakpoint to stop execution
1657 maxtries = 10
1722 maxtries = 10
1658 bp = int(opts.get('b',[1])[0])
1723 bp = int(opts.get('b',[1])[0])
1659 checkline = deb.checkline(filename,bp)
1724 checkline = deb.checkline(filename,bp)
1660 if not checkline:
1725 if not checkline:
1661 for bp in range(bp+1,bp+maxtries+1):
1726 for bp in range(bp+1,bp+maxtries+1):
1662 if deb.checkline(filename,bp):
1727 if deb.checkline(filename,bp):
1663 break
1728 break
1664 else:
1729 else:
1665 msg = ("\nI failed to find a valid line to set "
1730 msg = ("\nI failed to find a valid line to set "
1666 "a breakpoint\n"
1731 "a breakpoint\n"
1667 "after trying up to line: %s.\n"
1732 "after trying up to line: %s.\n"
1668 "Please set a valid breakpoint manually "
1733 "Please set a valid breakpoint manually "
1669 "with the -b option." % bp)
1734 "with the -b option." % bp)
1670 error(msg)
1735 error(msg)
1671 return
1736 return
1672 # if we find a good linenumber, set the breakpoint
1737 # if we find a good linenumber, set the breakpoint
1673 deb.do_break('%s:%s' % (filename,bp))
1738 deb.do_break('%s:%s' % (filename,bp))
1674 # Start file run
1739 # Start file run
1675 print "NOTE: Enter 'c' at the",
1740 print "NOTE: Enter 'c' at the",
1676 print "%s prompt to start your script." % deb.prompt
1741 print "%s prompt to start your script." % deb.prompt
1677 try:
1742 try:
1678 deb.run('execfile("%s")' % filename,prog_ns)
1743 deb.run('execfile("%s")' % filename,prog_ns)
1679
1744
1680 except:
1745 except:
1681 etype, value, tb = sys.exc_info()
1746 etype, value, tb = sys.exc_info()
1682 # Skip three frames in the traceback: the %run one,
1747 # Skip three frames in the traceback: the %run one,
1683 # one inside bdb.py, and the command-line typed by the
1748 # one inside bdb.py, and the command-line typed by the
1684 # user (run by exec in pdb itself).
1749 # user (run by exec in pdb itself).
1685 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1750 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1686 else:
1751 else:
1687 if runner is None:
1752 if runner is None:
1688 runner = self.shell.safe_execfile
1753 runner = self.shell.safe_execfile
1689 if opts.has_key('t'):
1754 if opts.has_key('t'):
1690 # timed execution
1755 # timed execution
1691 try:
1756 try:
1692 nruns = int(opts['N'][0])
1757 nruns = int(opts['N'][0])
1693 if nruns < 1:
1758 if nruns < 1:
1694 error('Number of runs must be >=1')
1759 error('Number of runs must be >=1')
1695 return
1760 return
1696 except (KeyError):
1761 except (KeyError):
1697 nruns = 1
1762 nruns = 1
1698 if nruns == 1:
1763 if nruns == 1:
1699 t0 = clock2()
1764 t0 = clock2()
1700 runner(filename,prog_ns,prog_ns,
1765 runner(filename,prog_ns,prog_ns,
1701 exit_ignore=exit_ignore)
1766 exit_ignore=exit_ignore)
1702 t1 = clock2()
1767 t1 = clock2()
1703 t_usr = t1[0]-t0[0]
1768 t_usr = t1[0]-t0[0]
1704 t_sys = t1[1]-t0[1]
1769 t_sys = t1[1]-t0[1]
1705 print "\nIPython CPU timings (estimated):"
1770 print "\nIPython CPU timings (estimated):"
1706 print " User : %10s s." % t_usr
1771 print " User : %10s s." % t_usr
1707 print " System: %10s s." % t_sys
1772 print " System: %10s s." % t_sys
1708 else:
1773 else:
1709 runs = range(nruns)
1774 runs = range(nruns)
1710 t0 = clock2()
1775 t0 = clock2()
1711 for nr in runs:
1776 for nr in runs:
1712 runner(filename,prog_ns,prog_ns,
1777 runner(filename,prog_ns,prog_ns,
1713 exit_ignore=exit_ignore)
1778 exit_ignore=exit_ignore)
1714 t1 = clock2()
1779 t1 = clock2()
1715 t_usr = t1[0]-t0[0]
1780 t_usr = t1[0]-t0[0]
1716 t_sys = t1[1]-t0[1]
1781 t_sys = t1[1]-t0[1]
1717 print "\nIPython CPU timings (estimated):"
1782 print "\nIPython CPU timings (estimated):"
1718 print "Total runs performed:",nruns
1783 print "Total runs performed:",nruns
1719 print " Times : %10s %10s" % ('Total','Per run')
1784 print " Times : %10s %10s" % ('Total','Per run')
1720 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1785 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1721 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1786 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1722
1787
1723 else:
1788 else:
1724 # regular execution
1789 # regular execution
1725 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1790 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1726
1791
1727 if opts.has_key('i'):
1792 if opts.has_key('i'):
1728 self.shell.user_ns['__name__'] = __name__save
1793 self.shell.user_ns['__name__'] = __name__save
1729 else:
1794 else:
1730 # The shell MUST hold a reference to prog_ns so after %run
1795 # The shell MUST hold a reference to prog_ns so after %run
1731 # exits, the python deletion mechanism doesn't zero it out
1796 # exits, the python deletion mechanism doesn't zero it out
1732 # (leaving dangling references).
1797 # (leaving dangling references).
1733 self.shell.cache_main_mod(prog_ns,filename)
1798 self.shell.cache_main_mod(prog_ns,filename)
1734 # update IPython interactive namespace
1799 # update IPython interactive namespace
1735
1800
1736 # Some forms of read errors on the file may mean the
1801 # Some forms of read errors on the file may mean the
1737 # __name__ key was never set; using pop we don't have to
1802 # __name__ key was never set; using pop we don't have to
1738 # worry about a possible KeyError.
1803 # worry about a possible KeyError.
1739 prog_ns.pop('__name__', None)
1804 prog_ns.pop('__name__', None)
1740
1805
1741 self.shell.user_ns.update(prog_ns)
1806 self.shell.user_ns.update(prog_ns)
1742 finally:
1807 finally:
1743 # It's a bit of a mystery why, but __builtins__ can change from
1808 # It's a bit of a mystery why, but __builtins__ can change from
1744 # being a module to becoming a dict missing some key data after
1809 # being a module to becoming a dict missing some key data after
1745 # %run. As best I can see, this is NOT something IPython is doing
1810 # %run. As best I can see, this is NOT something IPython is doing
1746 # at all, and similar problems have been reported before:
1811 # at all, and similar problems have been reported before:
1747 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1812 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1748 # Since this seems to be done by the interpreter itself, the best
1813 # Since this seems to be done by the interpreter itself, the best
1749 # we can do is to at least restore __builtins__ for the user on
1814 # we can do is to at least restore __builtins__ for the user on
1750 # exit.
1815 # exit.
1751 self.shell.user_ns['__builtins__'] = __builtin__
1816 self.shell.user_ns['__builtins__'] = __builtin__
1752
1817
1753 # Ensure key global structures are restored
1818 # Ensure key global structures are restored
1754 sys.argv = save_argv
1819 sys.argv = save_argv
1755 if restore_main:
1820 if restore_main:
1756 sys.modules['__main__'] = restore_main
1821 sys.modules['__main__'] = restore_main
1757 else:
1822 else:
1758 # Remove from sys.modules the reference to main_mod we'd
1823 # Remove from sys.modules the reference to main_mod we'd
1759 # added. Otherwise it will trap references to objects
1824 # added. Otherwise it will trap references to objects
1760 # contained therein.
1825 # contained therein.
1761 del sys.modules[main_mod_name]
1826 del sys.modules[main_mod_name]
1762
1827
1763 self.shell.reloadhist()
1828 self.shell.reloadhist()
1764
1829
1765 return stats
1830 return stats
1766
1831
1767 @testdec.skip_doctest
1832 @testdec.skip_doctest
1768 def magic_timeit(self, parameter_s =''):
1833 def magic_timeit(self, parameter_s =''):
1769 """Time execution of a Python statement or expression
1834 """Time execution of a Python statement or expression
1770
1835
1771 Usage:\\
1836 Usage:\\
1772 %timeit [-n<N> -r<R> [-t|-c]] statement
1837 %timeit [-n<N> -r<R> [-t|-c]] statement
1773
1838
1774 Time execution of a Python statement or expression using the timeit
1839 Time execution of a Python statement or expression using the timeit
1775 module.
1840 module.
1776
1841
1777 Options:
1842 Options:
1778 -n<N>: execute the given statement <N> times in a loop. If this value
1843 -n<N>: execute the given statement <N> times in a loop. If this value
1779 is not given, a fitting value is chosen.
1844 is not given, a fitting value is chosen.
1780
1845
1781 -r<R>: repeat the loop iteration <R> times and take the best result.
1846 -r<R>: repeat the loop iteration <R> times and take the best result.
1782 Default: 3
1847 Default: 3
1783
1848
1784 -t: use time.time to measure the time, which is the default on Unix.
1849 -t: use time.time to measure the time, which is the default on Unix.
1785 This function measures wall time.
1850 This function measures wall time.
1786
1851
1787 -c: use time.clock to measure the time, which is the default on
1852 -c: use time.clock to measure the time, which is the default on
1788 Windows and measures wall time. On Unix, resource.getrusage is used
1853 Windows and measures wall time. On Unix, resource.getrusage is used
1789 instead and returns the CPU user time.
1854 instead and returns the CPU user time.
1790
1855
1791 -p<P>: use a precision of <P> digits to display the timing result.
1856 -p<P>: use a precision of <P> digits to display the timing result.
1792 Default: 3
1857 Default: 3
1793
1858
1794
1859
1795 Examples:
1860 Examples:
1796
1861
1797 In [1]: %timeit pass
1862 In [1]: %timeit pass
1798 10000000 loops, best of 3: 53.3 ns per loop
1863 10000000 loops, best of 3: 53.3 ns per loop
1799
1864
1800 In [2]: u = None
1865 In [2]: u = None
1801
1866
1802 In [3]: %timeit u is None
1867 In [3]: %timeit u is None
1803 10000000 loops, best of 3: 184 ns per loop
1868 10000000 loops, best of 3: 184 ns per loop
1804
1869
1805 In [4]: %timeit -r 4 u == None
1870 In [4]: %timeit -r 4 u == None
1806 1000000 loops, best of 4: 242 ns per loop
1871 1000000 loops, best of 4: 242 ns per loop
1807
1872
1808 In [5]: import time
1873 In [5]: import time
1809
1874
1810 In [6]: %timeit -n1 time.sleep(2)
1875 In [6]: %timeit -n1 time.sleep(2)
1811 1 loops, best of 3: 2 s per loop
1876 1 loops, best of 3: 2 s per loop
1812
1877
1813
1878
1814 The times reported by %timeit will be slightly higher than those
1879 The times reported by %timeit will be slightly higher than those
1815 reported by the timeit.py script when variables are accessed. This is
1880 reported by the timeit.py script when variables are accessed. This is
1816 due to the fact that %timeit executes the statement in the namespace
1881 due to the fact that %timeit executes the statement in the namespace
1817 of the shell, compared with timeit.py, which uses a single setup
1882 of the shell, compared with timeit.py, which uses a single setup
1818 statement to import function or create variables. Generally, the bias
1883 statement to import function or create variables. Generally, the bias
1819 does not matter as long as results from timeit.py are not mixed with
1884 does not matter as long as results from timeit.py are not mixed with
1820 those from %timeit."""
1885 those from %timeit."""
1821
1886
1822 import timeit
1887 import timeit
1823 import math
1888 import math
1824
1889
1825 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1890 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1826 # certain terminals. Until we figure out a robust way of
1891 # certain terminals. Until we figure out a robust way of
1827 # auto-detecting if the terminal can deal with it, use plain 'us' for
1892 # auto-detecting if the terminal can deal with it, use plain 'us' for
1828 # microseconds. I am really NOT happy about disabling the proper
1893 # microseconds. I am really NOT happy about disabling the proper
1829 # 'micro' prefix, but crashing is worse... If anyone knows what the
1894 # 'micro' prefix, but crashing is worse... If anyone knows what the
1830 # right solution for this is, I'm all ears...
1895 # right solution for this is, I'm all ears...
1831 #
1896 #
1832 # Note: using
1897 # Note: using
1833 #
1898 #
1834 # s = u'\xb5'
1899 # s = u'\xb5'
1835 # s.encode(sys.getdefaultencoding())
1900 # s.encode(sys.getdefaultencoding())
1836 #
1901 #
1837 # is not sufficient, as I've seen terminals where that fails but
1902 # is not sufficient, as I've seen terminals where that fails but
1838 # print s
1903 # print s
1839 #
1904 #
1840 # succeeds
1905 # succeeds
1841 #
1906 #
1842 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1907 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1843
1908
1844 #units = [u"s", u"ms",u'\xb5',"ns"]
1909 #units = [u"s", u"ms",u'\xb5',"ns"]
1845 units = [u"s", u"ms",u'us',"ns"]
1910 units = [u"s", u"ms",u'us',"ns"]
1846
1911
1847 scaling = [1, 1e3, 1e6, 1e9]
1912 scaling = [1, 1e3, 1e6, 1e9]
1848
1913
1849 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1914 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1850 posix=False)
1915 posix=False)
1851 if stmt == "":
1916 if stmt == "":
1852 return
1917 return
1853 timefunc = timeit.default_timer
1918 timefunc = timeit.default_timer
1854 number = int(getattr(opts, "n", 0))
1919 number = int(getattr(opts, "n", 0))
1855 repeat = int(getattr(opts, "r", timeit.default_repeat))
1920 repeat = int(getattr(opts, "r", timeit.default_repeat))
1856 precision = int(getattr(opts, "p", 3))
1921 precision = int(getattr(opts, "p", 3))
1857 if hasattr(opts, "t"):
1922 if hasattr(opts, "t"):
1858 timefunc = time.time
1923 timefunc = time.time
1859 if hasattr(opts, "c"):
1924 if hasattr(opts, "c"):
1860 timefunc = clock
1925 timefunc = clock
1861
1926
1862 timer = timeit.Timer(timer=timefunc)
1927 timer = timeit.Timer(timer=timefunc)
1863 # this code has tight coupling to the inner workings of timeit.Timer,
1928 # this code has tight coupling to the inner workings of timeit.Timer,
1864 # but is there a better way to achieve that the code stmt has access
1929 # but is there a better way to achieve that the code stmt has access
1865 # to the shell namespace?
1930 # to the shell namespace?
1866
1931
1867 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1932 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1868 'setup': "pass"}
1933 'setup': "pass"}
1869 # Track compilation time so it can be reported if too long
1934 # Track compilation time so it can be reported if too long
1870 # Minimum time above which compilation time will be reported
1935 # Minimum time above which compilation time will be reported
1871 tc_min = 0.1
1936 tc_min = 0.1
1872
1937
1873 t0 = clock()
1938 t0 = clock()
1874 code = compile(src, "<magic-timeit>", "exec")
1939 code = compile(src, "<magic-timeit>", "exec")
1875 tc = clock()-t0
1940 tc = clock()-t0
1876
1941
1877 ns = {}
1942 ns = {}
1878 exec code in self.shell.user_ns, ns
1943 exec code in self.shell.user_ns, ns
1879 timer.inner = ns["inner"]
1944 timer.inner = ns["inner"]
1880
1945
1881 if number == 0:
1946 if number == 0:
1882 # determine number so that 0.2 <= total time < 2.0
1947 # determine number so that 0.2 <= total time < 2.0
1883 number = 1
1948 number = 1
1884 for i in range(1, 10):
1949 for i in range(1, 10):
1885 if timer.timeit(number) >= 0.2:
1950 if timer.timeit(number) >= 0.2:
1886 break
1951 break
1887 number *= 10
1952 number *= 10
1888
1953
1889 best = min(timer.repeat(repeat, number)) / number
1954 best = min(timer.repeat(repeat, number)) / number
1890
1955
1891 if best > 0.0:
1956 if best > 0.0:
1892 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1957 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1893 else:
1958 else:
1894 order = 3
1959 order = 3
1895 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1960 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1896 precision,
1961 precision,
1897 best * scaling[order],
1962 best * scaling[order],
1898 units[order])
1963 units[order])
1899 if tc > tc_min:
1964 if tc > tc_min:
1900 print "Compiler time: %.2f s" % tc
1965 print "Compiler time: %.2f s" % tc
1901
1966
1902 @testdec.skip_doctest
1967 @testdec.skip_doctest
1903 def magic_time(self,parameter_s = ''):
1968 def magic_time(self,parameter_s = ''):
1904 """Time execution of a Python statement or expression.
1969 """Time execution of a Python statement or expression.
1905
1970
1906 The CPU and wall clock times are printed, and the value of the
1971 The CPU and wall clock times are printed, and the value of the
1907 expression (if any) is returned. Note that under Win32, system time
1972 expression (if any) is returned. Note that under Win32, system time
1908 is always reported as 0, since it can not be measured.
1973 is always reported as 0, since it can not be measured.
1909
1974
1910 This function provides very basic timing functionality. In Python
1975 This function provides very basic timing functionality. In Python
1911 2.3, the timeit module offers more control and sophistication, so this
1976 2.3, the timeit module offers more control and sophistication, so this
1912 could be rewritten to use it (patches welcome).
1977 could be rewritten to use it (patches welcome).
1913
1978
1914 Some examples:
1979 Some examples:
1915
1980
1916 In [1]: time 2**128
1981 In [1]: time 2**128
1917 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1982 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 Wall time: 0.00
1983 Wall time: 0.00
1919 Out[1]: 340282366920938463463374607431768211456L
1984 Out[1]: 340282366920938463463374607431768211456L
1920
1985
1921 In [2]: n = 1000000
1986 In [2]: n = 1000000
1922
1987
1923 In [3]: time sum(range(n))
1988 In [3]: time sum(range(n))
1924 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1989 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1925 Wall time: 1.37
1990 Wall time: 1.37
1926 Out[3]: 499999500000L
1991 Out[3]: 499999500000L
1927
1992
1928 In [4]: time print 'hello world'
1993 In [4]: time print 'hello world'
1929 hello world
1994 hello world
1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1995 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1931 Wall time: 0.00
1996 Wall time: 0.00
1932
1997
1933 Note that the time needed by Python to compile the given expression
1998 Note that the time needed by Python to compile the given expression
1934 will be reported if it is more than 0.1s. In this example, the
1999 will be reported if it is more than 0.1s. In this example, the
1935 actual exponentiation is done by Python at compilation time, so while
2000 actual exponentiation is done by Python at compilation time, so while
1936 the expression can take a noticeable amount of time to compute, that
2001 the expression can take a noticeable amount of time to compute, that
1937 time is purely due to the compilation:
2002 time is purely due to the compilation:
1938
2003
1939 In [5]: time 3**9999;
2004 In [5]: time 3**9999;
1940 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1941 Wall time: 0.00 s
2006 Wall time: 0.00 s
1942
2007
1943 In [6]: time 3**999999;
2008 In [6]: time 3**999999;
1944 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2009 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1945 Wall time: 0.00 s
2010 Wall time: 0.00 s
1946 Compiler : 0.78 s
2011 Compiler : 0.78 s
1947 """
2012 """
1948
2013
1949 # fail immediately if the given expression can't be compiled
2014 # fail immediately if the given expression can't be compiled
1950
2015
1951 expr = self.shell.prefilter(parameter_s,False)
2016 expr = self.shell.prefilter(parameter_s,False)
1952
2017
1953 # Minimum time above which compilation time will be reported
2018 # Minimum time above which compilation time will be reported
1954 tc_min = 0.1
2019 tc_min = 0.1
1955
2020
1956 try:
2021 try:
1957 mode = 'eval'
2022 mode = 'eval'
1958 t0 = clock()
2023 t0 = clock()
1959 code = compile(expr,'<timed eval>',mode)
2024 code = compile(expr,'<timed eval>',mode)
1960 tc = clock()-t0
2025 tc = clock()-t0
1961 except SyntaxError:
2026 except SyntaxError:
1962 mode = 'exec'
2027 mode = 'exec'
1963 t0 = clock()
2028 t0 = clock()
1964 code = compile(expr,'<timed exec>',mode)
2029 code = compile(expr,'<timed exec>',mode)
1965 tc = clock()-t0
2030 tc = clock()-t0
1966 # skew measurement as little as possible
2031 # skew measurement as little as possible
1967 glob = self.shell.user_ns
2032 glob = self.shell.user_ns
1968 clk = clock2
2033 clk = clock2
1969 wtime = time.time
2034 wtime = time.time
1970 # time execution
2035 # time execution
1971 wall_st = wtime()
2036 wall_st = wtime()
1972 if mode=='eval':
2037 if mode=='eval':
1973 st = clk()
2038 st = clk()
1974 out = eval(code,glob)
2039 out = eval(code,glob)
1975 end = clk()
2040 end = clk()
1976 else:
2041 else:
1977 st = clk()
2042 st = clk()
1978 exec code in glob
2043 exec code in glob
1979 end = clk()
2044 end = clk()
1980 out = None
2045 out = None
1981 wall_end = wtime()
2046 wall_end = wtime()
1982 # Compute actual times and report
2047 # Compute actual times and report
1983 wall_time = wall_end-wall_st
2048 wall_time = wall_end-wall_st
1984 cpu_user = end[0]-st[0]
2049 cpu_user = end[0]-st[0]
1985 cpu_sys = end[1]-st[1]
2050 cpu_sys = end[1]-st[1]
1986 cpu_tot = cpu_user+cpu_sys
2051 cpu_tot = cpu_user+cpu_sys
1987 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2052 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1988 (cpu_user,cpu_sys,cpu_tot)
2053 (cpu_user,cpu_sys,cpu_tot)
1989 print "Wall time: %.2f s" % wall_time
2054 print "Wall time: %.2f s" % wall_time
1990 if tc > tc_min:
2055 if tc > tc_min:
1991 print "Compiler : %.2f s" % tc
2056 print "Compiler : %.2f s" % tc
1992 return out
2057 return out
1993
2058
1994 @testdec.skip_doctest
2059 @testdec.skip_doctest
1995 def magic_macro(self,parameter_s = ''):
2060 def magic_macro(self,parameter_s = ''):
1996 """Define a set of input lines as a macro for future re-execution.
2061 """Define a set of input lines as a macro for future re-execution.
1997
2062
1998 Usage:\\
2063 Usage:\\
1999 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2064 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2000
2065
2001 Options:
2066 Options:
2002
2067
2003 -r: use 'raw' input. By default, the 'processed' history is used,
2068 -r: use 'raw' input. By default, the 'processed' history is used,
2004 so that magics are loaded in their transformed version to valid
2069 so that magics are loaded in their transformed version to valid
2005 Python. If this option is given, the raw input as typed as the
2070 Python. If this option is given, the raw input as typed as the
2006 command line is used instead.
2071 command line is used instead.
2007
2072
2008 This will define a global variable called `name` which is a string
2073 This will define a global variable called `name` which is a string
2009 made of joining the slices and lines you specify (n1,n2,... numbers
2074 made of joining the slices and lines you specify (n1,n2,... numbers
2010 above) from your input history into a single string. This variable
2075 above) from your input history into a single string. This variable
2011 acts like an automatic function which re-executes those lines as if
2076 acts like an automatic function which re-executes those lines as if
2012 you had typed them. You just type 'name' at the prompt and the code
2077 you had typed them. You just type 'name' at the prompt and the code
2013 executes.
2078 executes.
2014
2079
2015 The notation for indicating number ranges is: n1-n2 means 'use line
2080 The notation for indicating number ranges is: n1-n2 means 'use line
2016 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2081 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2017 using the lines numbered 5,6 and 7.
2082 using the lines numbered 5,6 and 7.
2018
2083
2019 Note: as a 'hidden' feature, you can also use traditional python slice
2084 Note: as a 'hidden' feature, you can also use traditional python slice
2020 notation, where N:M means numbers N through M-1.
2085 notation, where N:M means numbers N through M-1.
2021
2086
2022 For example, if your history contains (%hist prints it):
2087 For example, if your history contains (%hist prints it):
2023
2088
2024 44: x=1
2089 44: x=1
2025 45: y=3
2090 45: y=3
2026 46: z=x+y
2091 46: z=x+y
2027 47: print x
2092 47: print x
2028 48: a=5
2093 48: a=5
2029 49: print 'x',x,'y',y
2094 49: print 'x',x,'y',y
2030
2095
2031 you can create a macro with lines 44 through 47 (included) and line 49
2096 you can create a macro with lines 44 through 47 (included) and line 49
2032 called my_macro with:
2097 called my_macro with:
2033
2098
2034 In [55]: %macro my_macro 44-47 49
2099 In [55]: %macro my_macro 44-47 49
2035
2100
2036 Now, typing `my_macro` (without quotes) will re-execute all this code
2101 Now, typing `my_macro` (without quotes) will re-execute all this code
2037 in one pass.
2102 in one pass.
2038
2103
2039 You don't need to give the line-numbers in order, and any given line
2104 You don't need to give the line-numbers in order, and any given line
2040 number can appear multiple times. You can assemble macros with any
2105 number can appear multiple times. You can assemble macros with any
2041 lines from your input history in any order.
2106 lines from your input history in any order.
2042
2107
2043 The macro is a simple object which holds its value in an attribute,
2108 The macro is a simple object which holds its value in an attribute,
2044 but IPython's display system checks for macros and executes them as
2109 but IPython's display system checks for macros and executes them as
2045 code instead of printing them when you type their name.
2110 code instead of printing them when you type their name.
2046
2111
2047 You can view a macro's contents by explicitly printing it with:
2112 You can view a macro's contents by explicitly printing it with:
2048
2113
2049 'print macro_name'.
2114 'print macro_name'.
2050
2115
2051 For one-off cases which DON'T contain magic function calls in them you
2116 For one-off cases which DON'T contain magic function calls in them you
2052 can obtain similar results by explicitly executing slices from your
2117 can obtain similar results by explicitly executing slices from your
2053 input history with:
2118 input history with:
2054
2119
2055 In [60]: exec In[44:48]+In[49]"""
2120 In [60]: exec In[44:48]+In[49]"""
2056
2121
2057 opts,args = self.parse_options(parameter_s,'r',mode='list')
2122 opts,args = self.parse_options(parameter_s,'r',mode='list')
2058 if not args:
2123 if not args:
2059 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2124 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2060 macs.sort()
2125 macs.sort()
2061 return macs
2126 return macs
2062 if len(args) == 1:
2127 if len(args) == 1:
2063 raise UsageError(
2128 raise UsageError(
2064 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2129 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2065 name,ranges = args[0], args[1:]
2130 name,ranges = args[0], args[1:]
2066
2131
2067 #print 'rng',ranges # dbg
2132 #print 'rng',ranges # dbg
2068 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2133 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2069 macro = Macro(lines)
2134 macro = Macro(lines)
2070 self.shell.define_macro(name, macro)
2135 self.shell.define_macro(name, macro)
2071 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2136 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2072 print 'Macro contents:'
2137 print 'Macro contents:'
2073 print macro,
2138 print macro,
2074
2139
2075 def magic_save(self,parameter_s = ''):
2140 def magic_save(self,parameter_s = ''):
2076 """Save a set of lines to a given filename.
2141 """Save a set of lines to a given filename.
2077
2142
2078 Usage:\\
2143 Usage:\\
2079 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2144 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2080
2145
2081 Options:
2146 Options:
2082
2147
2083 -r: use 'raw' input. By default, the 'processed' history is used,
2148 -r: use 'raw' input. By default, the 'processed' history is used,
2084 so that magics are loaded in their transformed version to valid
2149 so that magics are loaded in their transformed version to valid
2085 Python. If this option is given, the raw input as typed as the
2150 Python. If this option is given, the raw input as typed as the
2086 command line is used instead.
2151 command line is used instead.
2087
2152
2088 This function uses the same syntax as %macro for line extraction, but
2153 This function uses the same syntax as %macro for line extraction, but
2089 instead of creating a macro it saves the resulting string to the
2154 instead of creating a macro it saves the resulting string to the
2090 filename you specify.
2155 filename you specify.
2091
2156
2092 It adds a '.py' extension to the file if you don't do so yourself, and
2157 It adds a '.py' extension to the file if you don't do so yourself, and
2093 it asks for confirmation before overwriting existing files."""
2158 it asks for confirmation before overwriting existing files."""
2094
2159
2095 opts,args = self.parse_options(parameter_s,'r',mode='list')
2160 opts,args = self.parse_options(parameter_s,'r',mode='list')
2096 fname,ranges = args[0], args[1:]
2161 fname,ranges = args[0], args[1:]
2097 if not fname.endswith('.py'):
2162 if not fname.endswith('.py'):
2098 fname += '.py'
2163 fname += '.py'
2099 if os.path.isfile(fname):
2164 if os.path.isfile(fname):
2100 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2165 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2101 if ans.lower() not in ['y','yes']:
2166 if ans.lower() not in ['y','yes']:
2102 print 'Operation cancelled.'
2167 print 'Operation cancelled.'
2103 return
2168 return
2104 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2169 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2105 f = file(fname,'w')
2170 f = file(fname,'w')
2106 f.write(cmds)
2171 f.write(cmds)
2107 f.close()
2172 f.close()
2108 print 'The following commands were written to file `%s`:' % fname
2173 print 'The following commands were written to file `%s`:' % fname
2109 print cmds
2174 print cmds
2110
2175
2111 def _edit_macro(self,mname,macro):
2176 def _edit_macro(self,mname,macro):
2112 """open an editor with the macro data in a file"""
2177 """open an editor with the macro data in a file"""
2113 filename = self.shell.mktempfile(macro.value)
2178 filename = self.shell.mktempfile(macro.value)
2114 self.shell.hooks.editor(filename)
2179 self.shell.hooks.editor(filename)
2115
2180
2116 # and make a new macro object, to replace the old one
2181 # and make a new macro object, to replace the old one
2117 mfile = open(filename)
2182 mfile = open(filename)
2118 mvalue = mfile.read()
2183 mvalue = mfile.read()
2119 mfile.close()
2184 mfile.close()
2120 self.shell.user_ns[mname] = Macro(mvalue)
2185 self.shell.user_ns[mname] = Macro(mvalue)
2121
2186
2122 def magic_ed(self,parameter_s=''):
2187 def magic_ed(self,parameter_s=''):
2123 """Alias to %edit."""
2188 """Alias to %edit."""
2124 return self.magic_edit(parameter_s)
2189 return self.magic_edit(parameter_s)
2125
2190
2126 @testdec.skip_doctest
2191 @testdec.skip_doctest
2127 def magic_edit(self,parameter_s='',last_call=['','']):
2192 def magic_edit(self,parameter_s='',last_call=['','']):
2128 """Bring up an editor and execute the resulting code.
2193 """Bring up an editor and execute the resulting code.
2129
2194
2130 Usage:
2195 Usage:
2131 %edit [options] [args]
2196 %edit [options] [args]
2132
2197
2133 %edit runs IPython's editor hook. The default version of this hook is
2198 %edit runs IPython's editor hook. The default version of this hook is
2134 set to call the __IPYTHON__.rc.editor command. This is read from your
2199 set to call the __IPYTHON__.rc.editor command. This is read from your
2135 environment variable $EDITOR. If this isn't found, it will default to
2200 environment variable $EDITOR. If this isn't found, it will default to
2136 vi under Linux/Unix and to notepad under Windows. See the end of this
2201 vi under Linux/Unix and to notepad under Windows. See the end of this
2137 docstring for how to change the editor hook.
2202 docstring for how to change the editor hook.
2138
2203
2139 You can also set the value of this editor via the command line option
2204 You can also set the value of this editor via the command line option
2140 '-editor' or in your ipythonrc file. This is useful if you wish to use
2205 '-editor' or in your ipythonrc file. This is useful if you wish to use
2141 specifically for IPython an editor different from your typical default
2206 specifically for IPython an editor different from your typical default
2142 (and for Windows users who typically don't set environment variables).
2207 (and for Windows users who typically don't set environment variables).
2143
2208
2144 This command allows you to conveniently edit multi-line code right in
2209 This command allows you to conveniently edit multi-line code right in
2145 your IPython session.
2210 your IPython session.
2146
2211
2147 If called without arguments, %edit opens up an empty editor with a
2212 If called without arguments, %edit opens up an empty editor with a
2148 temporary file and will execute the contents of this file when you
2213 temporary file and will execute the contents of this file when you
2149 close it (don't forget to save it!).
2214 close it (don't forget to save it!).
2150
2215
2151
2216
2152 Options:
2217 Options:
2153
2218
2154 -n <number>: open the editor at a specified line number. By default,
2219 -n <number>: open the editor at a specified line number. By default,
2155 the IPython editor hook uses the unix syntax 'editor +N filename', but
2220 the IPython editor hook uses the unix syntax 'editor +N filename', but
2156 you can configure this by providing your own modified hook if your
2221 you can configure this by providing your own modified hook if your
2157 favorite editor supports line-number specifications with a different
2222 favorite editor supports line-number specifications with a different
2158 syntax.
2223 syntax.
2159
2224
2160 -p: this will call the editor with the same data as the previous time
2225 -p: this will call the editor with the same data as the previous time
2161 it was used, regardless of how long ago (in your current session) it
2226 it was used, regardless of how long ago (in your current session) it
2162 was.
2227 was.
2163
2228
2164 -r: use 'raw' input. This option only applies to input taken from the
2229 -r: use 'raw' input. This option only applies to input taken from the
2165 user's history. By default, the 'processed' history is used, so that
2230 user's history. By default, the 'processed' history is used, so that
2166 magics are loaded in their transformed version to valid Python. If
2231 magics are loaded in their transformed version to valid Python. If
2167 this option is given, the raw input as typed as the command line is
2232 this option is given, the raw input as typed as the command line is
2168 used instead. When you exit the editor, it will be executed by
2233 used instead. When you exit the editor, it will be executed by
2169 IPython's own processor.
2234 IPython's own processor.
2170
2235
2171 -x: do not execute the edited code immediately upon exit. This is
2236 -x: do not execute the edited code immediately upon exit. This is
2172 mainly useful if you are editing programs which need to be called with
2237 mainly useful if you are editing programs which need to be called with
2173 command line arguments, which you can then do using %run.
2238 command line arguments, which you can then do using %run.
2174
2239
2175
2240
2176 Arguments:
2241 Arguments:
2177
2242
2178 If arguments are given, the following possibilites exist:
2243 If arguments are given, the following possibilites exist:
2179
2244
2180 - The arguments are numbers or pairs of colon-separated numbers (like
2245 - The arguments are numbers or pairs of colon-separated numbers (like
2181 1 4:8 9). These are interpreted as lines of previous input to be
2246 1 4:8 9). These are interpreted as lines of previous input to be
2182 loaded into the editor. The syntax is the same of the %macro command.
2247 loaded into the editor. The syntax is the same of the %macro command.
2183
2248
2184 - If the argument doesn't start with a number, it is evaluated as a
2249 - If the argument doesn't start with a number, it is evaluated as a
2185 variable and its contents loaded into the editor. You can thus edit
2250 variable and its contents loaded into the editor. You can thus edit
2186 any string which contains python code (including the result of
2251 any string which contains python code (including the result of
2187 previous edits).
2252 previous edits).
2188
2253
2189 - If the argument is the name of an object (other than a string),
2254 - If the argument is the name of an object (other than a string),
2190 IPython will try to locate the file where it was defined and open the
2255 IPython will try to locate the file where it was defined and open the
2191 editor at the point where it is defined. You can use `%edit function`
2256 editor at the point where it is defined. You can use `%edit function`
2192 to load an editor exactly at the point where 'function' is defined,
2257 to load an editor exactly at the point where 'function' is defined,
2193 edit it and have the file be executed automatically.
2258 edit it and have the file be executed automatically.
2194
2259
2195 If the object is a macro (see %macro for details), this opens up your
2260 If the object is a macro (see %macro for details), this opens up your
2196 specified editor with a temporary file containing the macro's data.
2261 specified editor with a temporary file containing the macro's data.
2197 Upon exit, the macro is reloaded with the contents of the file.
2262 Upon exit, the macro is reloaded with the contents of the file.
2198
2263
2199 Note: opening at an exact line is only supported under Unix, and some
2264 Note: opening at an exact line is only supported under Unix, and some
2200 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2265 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2201 '+NUMBER' parameter necessary for this feature. Good editors like
2266 '+NUMBER' parameter necessary for this feature. Good editors like
2202 (X)Emacs, vi, jed, pico and joe all do.
2267 (X)Emacs, vi, jed, pico and joe all do.
2203
2268
2204 - If the argument is not found as a variable, IPython will look for a
2269 - If the argument is not found as a variable, IPython will look for a
2205 file with that name (adding .py if necessary) and load it into the
2270 file with that name (adding .py if necessary) and load it into the
2206 editor. It will execute its contents with execfile() when you exit,
2271 editor. It will execute its contents with execfile() when you exit,
2207 loading any code in the file into your interactive namespace.
2272 loading any code in the file into your interactive namespace.
2208
2273
2209 After executing your code, %edit will return as output the code you
2274 After executing your code, %edit will return as output the code you
2210 typed in the editor (except when it was an existing file). This way
2275 typed in the editor (except when it was an existing file). This way
2211 you can reload the code in further invocations of %edit as a variable,
2276 you can reload the code in further invocations of %edit as a variable,
2212 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2277 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2213 the output.
2278 the output.
2214
2279
2215 Note that %edit is also available through the alias %ed.
2280 Note that %edit is also available through the alias %ed.
2216
2281
2217 This is an example of creating a simple function inside the editor and
2282 This is an example of creating a simple function inside the editor and
2218 then modifying it. First, start up the editor:
2283 then modifying it. First, start up the editor:
2219
2284
2220 In [1]: ed
2285 In [1]: ed
2221 Editing... done. Executing edited code...
2286 Editing... done. Executing edited code...
2222 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2287 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2223
2288
2224 We can then call the function foo():
2289 We can then call the function foo():
2225
2290
2226 In [2]: foo()
2291 In [2]: foo()
2227 foo() was defined in an editing session
2292 foo() was defined in an editing session
2228
2293
2229 Now we edit foo. IPython automatically loads the editor with the
2294 Now we edit foo. IPython automatically loads the editor with the
2230 (temporary) file where foo() was previously defined:
2295 (temporary) file where foo() was previously defined:
2231
2296
2232 In [3]: ed foo
2297 In [3]: ed foo
2233 Editing... done. Executing edited code...
2298 Editing... done. Executing edited code...
2234
2299
2235 And if we call foo() again we get the modified version:
2300 And if we call foo() again we get the modified version:
2236
2301
2237 In [4]: foo()
2302 In [4]: foo()
2238 foo() has now been changed!
2303 foo() has now been changed!
2239
2304
2240 Here is an example of how to edit a code snippet successive
2305 Here is an example of how to edit a code snippet successive
2241 times. First we call the editor:
2306 times. First we call the editor:
2242
2307
2243 In [5]: ed
2308 In [5]: ed
2244 Editing... done. Executing edited code...
2309 Editing... done. Executing edited code...
2245 hello
2310 hello
2246 Out[5]: "print 'hello'n"
2311 Out[5]: "print 'hello'n"
2247
2312
2248 Now we call it again with the previous output (stored in _):
2313 Now we call it again with the previous output (stored in _):
2249
2314
2250 In [6]: ed _
2315 In [6]: ed _
2251 Editing... done. Executing edited code...
2316 Editing... done. Executing edited code...
2252 hello world
2317 hello world
2253 Out[6]: "print 'hello world'n"
2318 Out[6]: "print 'hello world'n"
2254
2319
2255 Now we call it with the output #8 (stored in _8, also as Out[8]):
2320 Now we call it with the output #8 (stored in _8, also as Out[8]):
2256
2321
2257 In [7]: ed _8
2322 In [7]: ed _8
2258 Editing... done. Executing edited code...
2323 Editing... done. Executing edited code...
2259 hello again
2324 hello again
2260 Out[7]: "print 'hello again'n"
2325 Out[7]: "print 'hello again'n"
2261
2326
2262
2327
2263 Changing the default editor hook:
2328 Changing the default editor hook:
2264
2329
2265 If you wish to write your own editor hook, you can put it in a
2330 If you wish to write your own editor hook, you can put it in a
2266 configuration file which you load at startup time. The default hook
2331 configuration file which you load at startup time. The default hook
2267 is defined in the IPython.core.hooks module, and you can use that as a
2332 is defined in the IPython.core.hooks module, and you can use that as a
2268 starting example for further modifications. That file also has
2333 starting example for further modifications. That file also has
2269 general instructions on how to set a new hook for use once you've
2334 general instructions on how to set a new hook for use once you've
2270 defined it."""
2335 defined it."""
2271
2336
2272 # FIXME: This function has become a convoluted mess. It needs a
2337 # FIXME: This function has become a convoluted mess. It needs a
2273 # ground-up rewrite with clean, simple logic.
2338 # ground-up rewrite with clean, simple logic.
2274
2339
2275 def make_filename(arg):
2340 def make_filename(arg):
2276 "Make a filename from the given args"
2341 "Make a filename from the given args"
2277 try:
2342 try:
2278 filename = get_py_filename(arg)
2343 filename = get_py_filename(arg)
2279 except IOError:
2344 except IOError:
2280 if args.endswith('.py'):
2345 if args.endswith('.py'):
2281 filename = arg
2346 filename = arg
2282 else:
2347 else:
2283 filename = None
2348 filename = None
2284 return filename
2349 return filename
2285
2350
2286 # custom exceptions
2351 # custom exceptions
2287 class DataIsObject(Exception): pass
2352 class DataIsObject(Exception): pass
2288
2353
2289 opts,args = self.parse_options(parameter_s,'prxn:')
2354 opts,args = self.parse_options(parameter_s,'prxn:')
2290 # Set a few locals from the options for convenience:
2355 # Set a few locals from the options for convenience:
2291 opts_p = opts.has_key('p')
2356 opts_p = opts.has_key('p')
2292 opts_r = opts.has_key('r')
2357 opts_r = opts.has_key('r')
2293
2358
2294 # Default line number value
2359 # Default line number value
2295 lineno = opts.get('n',None)
2360 lineno = opts.get('n',None)
2296
2361
2297 if opts_p:
2362 if opts_p:
2298 args = '_%s' % last_call[0]
2363 args = '_%s' % last_call[0]
2299 if not self.shell.user_ns.has_key(args):
2364 if not self.shell.user_ns.has_key(args):
2300 args = last_call[1]
2365 args = last_call[1]
2301
2366
2302 # use last_call to remember the state of the previous call, but don't
2367 # use last_call to remember the state of the previous call, but don't
2303 # let it be clobbered by successive '-p' calls.
2368 # let it be clobbered by successive '-p' calls.
2304 try:
2369 try:
2305 last_call[0] = self.shell.outputcache.prompt_count
2370 last_call[0] = self.shell.outputcache.prompt_count
2306 if not opts_p:
2371 if not opts_p:
2307 last_call[1] = parameter_s
2372 last_call[1] = parameter_s
2308 except:
2373 except:
2309 pass
2374 pass
2310
2375
2311 # by default this is done with temp files, except when the given
2376 # by default this is done with temp files, except when the given
2312 # arg is a filename
2377 # arg is a filename
2313 use_temp = 1
2378 use_temp = 1
2314
2379
2315 if re.match(r'\d',args):
2380 if re.match(r'\d',args):
2316 # Mode where user specifies ranges of lines, like in %macro.
2381 # Mode where user specifies ranges of lines, like in %macro.
2317 # This means that you can't edit files whose names begin with
2382 # This means that you can't edit files whose names begin with
2318 # numbers this way. Tough.
2383 # numbers this way. Tough.
2319 ranges = args.split()
2384 ranges = args.split()
2320 data = ''.join(self.extract_input_slices(ranges,opts_r))
2385 data = ''.join(self.extract_input_slices(ranges,opts_r))
2321 elif args.endswith('.py'):
2386 elif args.endswith('.py'):
2322 filename = make_filename(args)
2387 filename = make_filename(args)
2323 data = ''
2388 data = ''
2324 use_temp = 0
2389 use_temp = 0
2325 elif args:
2390 elif args:
2326 try:
2391 try:
2327 # Load the parameter given as a variable. If not a string,
2392 # Load the parameter given as a variable. If not a string,
2328 # process it as an object instead (below)
2393 # process it as an object instead (below)
2329
2394
2330 #print '*** args',args,'type',type(args) # dbg
2395 #print '*** args',args,'type',type(args) # dbg
2331 data = eval(args,self.shell.user_ns)
2396 data = eval(args,self.shell.user_ns)
2332 if not type(data) in StringTypes:
2397 if not type(data) in StringTypes:
2333 raise DataIsObject
2398 raise DataIsObject
2334
2399
2335 except (NameError,SyntaxError):
2400 except (NameError,SyntaxError):
2336 # given argument is not a variable, try as a filename
2401 # given argument is not a variable, try as a filename
2337 filename = make_filename(args)
2402 filename = make_filename(args)
2338 if filename is None:
2403 if filename is None:
2339 warn("Argument given (%s) can't be found as a variable "
2404 warn("Argument given (%s) can't be found as a variable "
2340 "or as a filename." % args)
2405 "or as a filename." % args)
2341 return
2406 return
2342
2407
2343 data = ''
2408 data = ''
2344 use_temp = 0
2409 use_temp = 0
2345 except DataIsObject:
2410 except DataIsObject:
2346
2411
2347 # macros have a special edit function
2412 # macros have a special edit function
2348 if isinstance(data,Macro):
2413 if isinstance(data,Macro):
2349 self._edit_macro(args,data)
2414 self._edit_macro(args,data)
2350 return
2415 return
2351
2416
2352 # For objects, try to edit the file where they are defined
2417 # For objects, try to edit the file where they are defined
2353 try:
2418 try:
2354 filename = inspect.getabsfile(data)
2419 filename = inspect.getabsfile(data)
2355 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2420 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2356 # class created by %edit? Try to find source
2421 # class created by %edit? Try to find source
2357 # by looking for method definitions instead, the
2422 # by looking for method definitions instead, the
2358 # __module__ in those classes is FakeModule.
2423 # __module__ in those classes is FakeModule.
2359 attrs = [getattr(data, aname) for aname in dir(data)]
2424 attrs = [getattr(data, aname) for aname in dir(data)]
2360 for attr in attrs:
2425 for attr in attrs:
2361 if not inspect.ismethod(attr):
2426 if not inspect.ismethod(attr):
2362 continue
2427 continue
2363 filename = inspect.getabsfile(attr)
2428 filename = inspect.getabsfile(attr)
2364 if filename and 'fakemodule' not in filename.lower():
2429 if filename and 'fakemodule' not in filename.lower():
2365 # change the attribute to be the edit target instead
2430 # change the attribute to be the edit target instead
2366 data = attr
2431 data = attr
2367 break
2432 break
2368
2433
2369 datafile = 1
2434 datafile = 1
2370 except TypeError:
2435 except TypeError:
2371 filename = make_filename(args)
2436 filename = make_filename(args)
2372 datafile = 1
2437 datafile = 1
2373 warn('Could not find file where `%s` is defined.\n'
2438 warn('Could not find file where `%s` is defined.\n'
2374 'Opening a file named `%s`' % (args,filename))
2439 'Opening a file named `%s`' % (args,filename))
2375 # Now, make sure we can actually read the source (if it was in
2440 # Now, make sure we can actually read the source (if it was in
2376 # a temp file it's gone by now).
2441 # a temp file it's gone by now).
2377 if datafile:
2442 if datafile:
2378 try:
2443 try:
2379 if lineno is None:
2444 if lineno is None:
2380 lineno = inspect.getsourcelines(data)[1]
2445 lineno = inspect.getsourcelines(data)[1]
2381 except IOError:
2446 except IOError:
2382 filename = make_filename(args)
2447 filename = make_filename(args)
2383 if filename is None:
2448 if filename is None:
2384 warn('The file `%s` where `%s` was defined cannot '
2449 warn('The file `%s` where `%s` was defined cannot '
2385 'be read.' % (filename,data))
2450 'be read.' % (filename,data))
2386 return
2451 return
2387 use_temp = 0
2452 use_temp = 0
2388 else:
2453 else:
2389 data = ''
2454 data = ''
2390
2455
2391 if use_temp:
2456 if use_temp:
2392 filename = self.shell.mktempfile(data)
2457 filename = self.shell.mktempfile(data)
2393 print 'IPython will make a temporary file named:',filename
2458 print 'IPython will make a temporary file named:',filename
2394
2459
2395 # do actual editing here
2460 # do actual editing here
2396 print 'Editing...',
2461 print 'Editing...',
2397 sys.stdout.flush()
2462 sys.stdout.flush()
2398 try:
2463 try:
2399 # Quote filenames that may have spaces in them
2464 # Quote filenames that may have spaces in them
2400 if ' ' in filename:
2465 if ' ' in filename:
2401 filename = "%s" % filename
2466 filename = "%s" % filename
2402 self.shell.hooks.editor(filename,lineno)
2467 self.shell.hooks.editor(filename,lineno)
2403 except TryNext:
2468 except TryNext:
2404 warn('Could not open editor')
2469 warn('Could not open editor')
2405 return
2470 return
2406
2471
2407 # XXX TODO: should this be generalized for all string vars?
2472 # XXX TODO: should this be generalized for all string vars?
2408 # For now, this is special-cased to blocks created by cpaste
2473 # For now, this is special-cased to blocks created by cpaste
2409 if args.strip() == 'pasted_block':
2474 if args.strip() == 'pasted_block':
2410 self.shell.user_ns['pasted_block'] = file_read(filename)
2475 self.shell.user_ns['pasted_block'] = file_read(filename)
2411
2476
2412 if opts.has_key('x'): # -x prevents actual execution
2477 if opts.has_key('x'): # -x prevents actual execution
2413 print
2478 print
2414 else:
2479 else:
2415 print 'done. Executing edited code...'
2480 print 'done. Executing edited code...'
2416 if opts_r:
2481 if opts_r:
2417 self.shell.runlines(file_read(filename))
2482 self.shell.runlines(file_read(filename))
2418 else:
2483 else:
2419 self.shell.safe_execfile(filename,self.shell.user_ns,
2484 self.shell.safe_execfile(filename,self.shell.user_ns,
2420 self.shell.user_ns)
2485 self.shell.user_ns)
2421
2486
2422
2487
2423 if use_temp:
2488 if use_temp:
2424 try:
2489 try:
2425 return open(filename).read()
2490 return open(filename).read()
2426 except IOError,msg:
2491 except IOError,msg:
2427 if msg.filename == filename:
2492 if msg.filename == filename:
2428 warn('File not found. Did you forget to save?')
2493 warn('File not found. Did you forget to save?')
2429 return
2494 return
2430 else:
2495 else:
2431 self.shell.showtraceback()
2496 self.shell.showtraceback()
2432
2497
2433 def magic_xmode(self,parameter_s = ''):
2498 def magic_xmode(self,parameter_s = ''):
2434 """Switch modes for the exception handlers.
2499 """Switch modes for the exception handlers.
2435
2500
2436 Valid modes: Plain, Context and Verbose.
2501 Valid modes: Plain, Context and Verbose.
2437
2502
2438 If called without arguments, acts as a toggle."""
2503 If called without arguments, acts as a toggle."""
2439
2504
2440 def xmode_switch_err(name):
2505 def xmode_switch_err(name):
2441 warn('Error changing %s exception modes.\n%s' %
2506 warn('Error changing %s exception modes.\n%s' %
2442 (name,sys.exc_info()[1]))
2507 (name,sys.exc_info()[1]))
2443
2508
2444 shell = self.shell
2509 shell = self.shell
2445 new_mode = parameter_s.strip().capitalize()
2510 new_mode = parameter_s.strip().capitalize()
2446 try:
2511 try:
2447 shell.InteractiveTB.set_mode(mode=new_mode)
2512 shell.InteractiveTB.set_mode(mode=new_mode)
2448 print 'Exception reporting mode:',shell.InteractiveTB.mode
2513 print 'Exception reporting mode:',shell.InteractiveTB.mode
2449 except:
2514 except:
2450 xmode_switch_err('user')
2515 xmode_switch_err('user')
2451
2516
2452 # threaded shells use a special handler in sys.excepthook
2517 # threaded shells use a special handler in sys.excepthook
2453 if shell.isthreaded:
2518 if shell.isthreaded:
2454 try:
2519 try:
2455 shell.sys_excepthook.set_mode(mode=new_mode)
2520 shell.sys_excepthook.set_mode(mode=new_mode)
2456 except:
2521 except:
2457 xmode_switch_err('threaded')
2522 xmode_switch_err('threaded')
2458
2523
2459 def magic_colors(self,parameter_s = ''):
2524 def magic_colors(self,parameter_s = ''):
2460 """Switch color scheme for prompts, info system and exception handlers.
2525 """Switch color scheme for prompts, info system and exception handlers.
2461
2526
2462 Currently implemented schemes: NoColor, Linux, LightBG.
2527 Currently implemented schemes: NoColor, Linux, LightBG.
2463
2528
2464 Color scheme names are not case-sensitive."""
2529 Color scheme names are not case-sensitive."""
2465
2530
2466 def color_switch_err(name):
2531 def color_switch_err(name):
2467 warn('Error changing %s color schemes.\n%s' %
2532 warn('Error changing %s color schemes.\n%s' %
2468 (name,sys.exc_info()[1]))
2533 (name,sys.exc_info()[1]))
2469
2534
2470
2535
2471 new_scheme = parameter_s.strip()
2536 new_scheme = parameter_s.strip()
2472 if not new_scheme:
2537 if not new_scheme:
2473 raise UsageError(
2538 raise UsageError(
2474 "%colors: you must specify a color scheme. See '%colors?'")
2539 "%colors: you must specify a color scheme. See '%colors?'")
2475 return
2540 return
2476 # local shortcut
2541 # local shortcut
2477 shell = self.shell
2542 shell = self.shell
2478
2543
2479 import IPython.utils.rlineimpl as readline
2544 import IPython.utils.rlineimpl as readline
2480
2545
2481 if not readline.have_readline and sys.platform == "win32":
2546 if not readline.have_readline and sys.platform == "win32":
2482 msg = """\
2547 msg = """\
2483 Proper color support under MS Windows requires the pyreadline library.
2548 Proper color support under MS Windows requires the pyreadline library.
2484 You can find it at:
2549 You can find it at:
2485 http://ipython.scipy.org/moin/PyReadline/Intro
2550 http://ipython.scipy.org/moin/PyReadline/Intro
2486 Gary's readline needs the ctypes module, from:
2551 Gary's readline needs the ctypes module, from:
2487 http://starship.python.net/crew/theller/ctypes
2552 http://starship.python.net/crew/theller/ctypes
2488 (Note that ctypes is already part of Python versions 2.5 and newer).
2553 (Note that ctypes is already part of Python versions 2.5 and newer).
2489
2554
2490 Defaulting color scheme to 'NoColor'"""
2555 Defaulting color scheme to 'NoColor'"""
2491 new_scheme = 'NoColor'
2556 new_scheme = 'NoColor'
2492 warn(msg)
2557 warn(msg)
2493
2558
2494 # readline option is 0
2559 # readline option is 0
2495 if not shell.has_readline:
2560 if not shell.has_readline:
2496 new_scheme = 'NoColor'
2561 new_scheme = 'NoColor'
2497
2562
2498 # Set prompt colors
2563 # Set prompt colors
2499 try:
2564 try:
2500 shell.outputcache.set_colors(new_scheme)
2565 shell.outputcache.set_colors(new_scheme)
2501 except:
2566 except:
2502 color_switch_err('prompt')
2567 color_switch_err('prompt')
2503 else:
2568 else:
2504 shell.colors = \
2569 shell.colors = \
2505 shell.outputcache.color_table.active_scheme_name
2570 shell.outputcache.color_table.active_scheme_name
2506 # Set exception colors
2571 # Set exception colors
2507 try:
2572 try:
2508 shell.InteractiveTB.set_colors(scheme = new_scheme)
2573 shell.InteractiveTB.set_colors(scheme = new_scheme)
2509 shell.SyntaxTB.set_colors(scheme = new_scheme)
2574 shell.SyntaxTB.set_colors(scheme = new_scheme)
2510 except:
2575 except:
2511 color_switch_err('exception')
2576 color_switch_err('exception')
2512
2577
2513 # threaded shells use a verbose traceback in sys.excepthook
2578 # threaded shells use a verbose traceback in sys.excepthook
2514 if shell.isthreaded:
2579 if shell.isthreaded:
2515 try:
2580 try:
2516 shell.sys_excepthook.set_colors(scheme=new_scheme)
2581 shell.sys_excepthook.set_colors(scheme=new_scheme)
2517 except:
2582 except:
2518 color_switch_err('system exception handler')
2583 color_switch_err('system exception handler')
2519
2584
2520 # Set info (for 'object?') colors
2585 # Set info (for 'object?') colors
2521 if shell.color_info:
2586 if shell.color_info:
2522 try:
2587 try:
2523 shell.inspector.set_active_scheme(new_scheme)
2588 shell.inspector.set_active_scheme(new_scheme)
2524 except:
2589 except:
2525 color_switch_err('object inspector')
2590 color_switch_err('object inspector')
2526 else:
2591 else:
2527 shell.inspector.set_active_scheme('NoColor')
2592 shell.inspector.set_active_scheme('NoColor')
2528
2593
2529 def magic_color_info(self,parameter_s = ''):
2594 def magic_color_info(self,parameter_s = ''):
2530 """Toggle color_info.
2595 """Toggle color_info.
2531
2596
2532 The color_info configuration parameter controls whether colors are
2597 The color_info configuration parameter controls whether colors are
2533 used for displaying object details (by things like %psource, %pfile or
2598 used for displaying object details (by things like %psource, %pfile or
2534 the '?' system). This function toggles this value with each call.
2599 the '?' system). This function toggles this value with each call.
2535
2600
2536 Note that unless you have a fairly recent pager (less works better
2601 Note that unless you have a fairly recent pager (less works better
2537 than more) in your system, using colored object information displays
2602 than more) in your system, using colored object information displays
2538 will not work properly. Test it and see."""
2603 will not work properly. Test it and see."""
2539
2604
2540 self.shell.color_info = not self.shell.color_info
2605 self.shell.color_info = not self.shell.color_info
2541 self.magic_colors(self.shell.colors)
2606 self.magic_colors(self.shell.colors)
2542 print 'Object introspection functions have now coloring:',
2607 print 'Object introspection functions have now coloring:',
2543 print ['OFF','ON'][int(self.shell.color_info)]
2608 print ['OFF','ON'][int(self.shell.color_info)]
2544
2609
2545 def magic_Pprint(self, parameter_s=''):
2610 def magic_Pprint(self, parameter_s=''):
2546 """Toggle pretty printing on/off."""
2611 """Toggle pretty printing on/off."""
2547
2612
2548 self.shell.pprint = 1 - self.shell.pprint
2613 self.shell.pprint = 1 - self.shell.pprint
2549 print 'Pretty printing has been turned', \
2614 print 'Pretty printing has been turned', \
2550 ['OFF','ON'][self.shell.pprint]
2615 ['OFF','ON'][self.shell.pprint]
2551
2616
2552 def magic_Exit(self, parameter_s=''):
2617 def magic_Exit(self, parameter_s=''):
2553 """Exit IPython without confirmation."""
2618 """Exit IPython without confirmation."""
2554
2619
2555 self.shell.ask_exit()
2620 self.shell.ask_exit()
2556
2621
2557 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2622 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2558 magic_exit = magic_quit = magic_Quit = magic_Exit
2623 magic_exit = magic_quit = magic_Quit = magic_Exit
2559
2624
2560 #......................................................................
2625 #......................................................................
2561 # Functions to implement unix shell-type things
2626 # Functions to implement unix shell-type things
2562
2627
2563 @testdec.skip_doctest
2628 @testdec.skip_doctest
2564 def magic_alias(self, parameter_s = ''):
2629 def magic_alias(self, parameter_s = ''):
2565 """Define an alias for a system command.
2630 """Define an alias for a system command.
2566
2631
2567 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2632 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2568
2633
2569 Then, typing 'alias_name params' will execute the system command 'cmd
2634 Then, typing 'alias_name params' will execute the system command 'cmd
2570 params' (from your underlying operating system).
2635 params' (from your underlying operating system).
2571
2636
2572 Aliases have lower precedence than magic functions and Python normal
2637 Aliases have lower precedence than magic functions and Python normal
2573 variables, so if 'foo' is both a Python variable and an alias, the
2638 variables, so if 'foo' is both a Python variable and an alias, the
2574 alias can not be executed until 'del foo' removes the Python variable.
2639 alias can not be executed until 'del foo' removes the Python variable.
2575
2640
2576 You can use the %l specifier in an alias definition to represent the
2641 You can use the %l specifier in an alias definition to represent the
2577 whole line when the alias is called. For example:
2642 whole line when the alias is called. For example:
2578
2643
2579 In [2]: alias all echo "Input in brackets: <%l>"
2644 In [2]: alias all echo "Input in brackets: <%l>"
2580 In [3]: all hello world
2645 In [3]: all hello world
2581 Input in brackets: <hello world>
2646 Input in brackets: <hello world>
2582
2647
2583 You can also define aliases with parameters using %s specifiers (one
2648 You can also define aliases with parameters using %s specifiers (one
2584 per parameter):
2649 per parameter):
2585
2650
2586 In [1]: alias parts echo first %s second %s
2651 In [1]: alias parts echo first %s second %s
2587 In [2]: %parts A B
2652 In [2]: %parts A B
2588 first A second B
2653 first A second B
2589 In [3]: %parts A
2654 In [3]: %parts A
2590 Incorrect number of arguments: 2 expected.
2655 Incorrect number of arguments: 2 expected.
2591 parts is an alias to: 'echo first %s second %s'
2656 parts is an alias to: 'echo first %s second %s'
2592
2657
2593 Note that %l and %s are mutually exclusive. You can only use one or
2658 Note that %l and %s are mutually exclusive. You can only use one or
2594 the other in your aliases.
2659 the other in your aliases.
2595
2660
2596 Aliases expand Python variables just like system calls using ! or !!
2661 Aliases expand Python variables just like system calls using ! or !!
2597 do: all expressions prefixed with '$' get expanded. For details of
2662 do: all expressions prefixed with '$' get expanded. For details of
2598 the semantic rules, see PEP-215:
2663 the semantic rules, see PEP-215:
2599 http://www.python.org/peps/pep-0215.html. This is the library used by
2664 http://www.python.org/peps/pep-0215.html. This is the library used by
2600 IPython for variable expansion. If you want to access a true shell
2665 IPython for variable expansion. If you want to access a true shell
2601 variable, an extra $ is necessary to prevent its expansion by IPython:
2666 variable, an extra $ is necessary to prevent its expansion by IPython:
2602
2667
2603 In [6]: alias show echo
2668 In [6]: alias show echo
2604 In [7]: PATH='A Python string'
2669 In [7]: PATH='A Python string'
2605 In [8]: show $PATH
2670 In [8]: show $PATH
2606 A Python string
2671 A Python string
2607 In [9]: show $$PATH
2672 In [9]: show $$PATH
2608 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2673 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2609
2674
2610 You can use the alias facility to acess all of $PATH. See the %rehash
2675 You can use the alias facility to acess all of $PATH. See the %rehash
2611 and %rehashx functions, which automatically create aliases for the
2676 and %rehashx functions, which automatically create aliases for the
2612 contents of your $PATH.
2677 contents of your $PATH.
2613
2678
2614 If called with no parameters, %alias prints the current alias table."""
2679 If called with no parameters, %alias prints the current alias table."""
2615
2680
2616 par = parameter_s.strip()
2681 par = parameter_s.strip()
2617 if not par:
2682 if not par:
2618 stored = self.db.get('stored_aliases', {} )
2683 stored = self.db.get('stored_aliases', {} )
2619 aliases = sorted(self.shell.alias_manager.aliases)
2684 aliases = sorted(self.shell.alias_manager.aliases)
2620 # for k, v in stored:
2685 # for k, v in stored:
2621 # atab.append(k, v[0])
2686 # atab.append(k, v[0])
2622
2687
2623 print "Total number of aliases:", len(aliases)
2688 print "Total number of aliases:", len(aliases)
2624 return aliases
2689 return aliases
2625
2690
2626 # Now try to define a new one
2691 # Now try to define a new one
2627 try:
2692 try:
2628 alias,cmd = par.split(None, 1)
2693 alias,cmd = par.split(None, 1)
2629 except:
2694 except:
2630 print oinspect.getdoc(self.magic_alias)
2695 print oinspect.getdoc(self.magic_alias)
2631 else:
2696 else:
2632 self.shell.alias_manager.soft_define_alias(alias, cmd)
2697 self.shell.alias_manager.soft_define_alias(alias, cmd)
2633 # end magic_alias
2698 # end magic_alias
2634
2699
2635 def magic_unalias(self, parameter_s = ''):
2700 def magic_unalias(self, parameter_s = ''):
2636 """Remove an alias"""
2701 """Remove an alias"""
2637
2702
2638 aname = parameter_s.strip()
2703 aname = parameter_s.strip()
2639 self.shell.alias_manager.undefine_alias(aname)
2704 self.shell.alias_manager.undefine_alias(aname)
2640 stored = self.db.get('stored_aliases', {} )
2705 stored = self.db.get('stored_aliases', {} )
2641 if aname in stored:
2706 if aname in stored:
2642 print "Removing %stored alias",aname
2707 print "Removing %stored alias",aname
2643 del stored[aname]
2708 del stored[aname]
2644 self.db['stored_aliases'] = stored
2709 self.db['stored_aliases'] = stored
2645
2710
2646
2711
2647 def magic_rehashx(self, parameter_s = ''):
2712 def magic_rehashx(self, parameter_s = ''):
2648 """Update the alias table with all executable files in $PATH.
2713 """Update the alias table with all executable files in $PATH.
2649
2714
2650 This version explicitly checks that every entry in $PATH is a file
2715 This version explicitly checks that every entry in $PATH is a file
2651 with execute access (os.X_OK), so it is much slower than %rehash.
2716 with execute access (os.X_OK), so it is much slower than %rehash.
2652
2717
2653 Under Windows, it checks executability as a match agains a
2718 Under Windows, it checks executability as a match agains a
2654 '|'-separated string of extensions, stored in the IPython config
2719 '|'-separated string of extensions, stored in the IPython config
2655 variable win_exec_ext. This defaults to 'exe|com|bat'.
2720 variable win_exec_ext. This defaults to 'exe|com|bat'.
2656
2721
2657 This function also resets the root module cache of module completer,
2722 This function also resets the root module cache of module completer,
2658 used on slow filesystems.
2723 used on slow filesystems.
2659 """
2724 """
2660 from IPython.core.alias import InvalidAliasError
2725 from IPython.core.alias import InvalidAliasError
2661
2726
2662 # for the benefit of module completer in ipy_completers.py
2727 # for the benefit of module completer in ipy_completers.py
2663 del self.db['rootmodules']
2728 del self.db['rootmodules']
2664
2729
2665 path = [os.path.abspath(os.path.expanduser(p)) for p in
2730 path = [os.path.abspath(os.path.expanduser(p)) for p in
2666 os.environ.get('PATH','').split(os.pathsep)]
2731 os.environ.get('PATH','').split(os.pathsep)]
2667 path = filter(os.path.isdir,path)
2732 path = filter(os.path.isdir,path)
2668
2733
2669 syscmdlist = []
2734 syscmdlist = []
2670 # Now define isexec in a cross platform manner.
2735 # Now define isexec in a cross platform manner.
2671 if os.name == 'posix':
2736 if os.name == 'posix':
2672 isexec = lambda fname:os.path.isfile(fname) and \
2737 isexec = lambda fname:os.path.isfile(fname) and \
2673 os.access(fname,os.X_OK)
2738 os.access(fname,os.X_OK)
2674 else:
2739 else:
2675 try:
2740 try:
2676 winext = os.environ['pathext'].replace(';','|').replace('.','')
2741 winext = os.environ['pathext'].replace(';','|').replace('.','')
2677 except KeyError:
2742 except KeyError:
2678 winext = 'exe|com|bat|py'
2743 winext = 'exe|com|bat|py'
2679 if 'py' not in winext:
2744 if 'py' not in winext:
2680 winext += '|py'
2745 winext += '|py'
2681 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2746 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2682 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2747 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2683 savedir = os.getcwd()
2748 savedir = os.getcwd()
2684
2749
2685 # Now walk the paths looking for executables to alias.
2750 # Now walk the paths looking for executables to alias.
2686 try:
2751 try:
2687 # write the whole loop for posix/Windows so we don't have an if in
2752 # write the whole loop for posix/Windows so we don't have an if in
2688 # the innermost part
2753 # the innermost part
2689 if os.name == 'posix':
2754 if os.name == 'posix':
2690 for pdir in path:
2755 for pdir in path:
2691 os.chdir(pdir)
2756 os.chdir(pdir)
2692 for ff in os.listdir(pdir):
2757 for ff in os.listdir(pdir):
2693 if isexec(ff):
2758 if isexec(ff):
2694 try:
2759 try:
2695 # Removes dots from the name since ipython
2760 # Removes dots from the name since ipython
2696 # will assume names with dots to be python.
2761 # will assume names with dots to be python.
2697 self.shell.alias_manager.define_alias(
2762 self.shell.alias_manager.define_alias(
2698 ff.replace('.',''), ff)
2763 ff.replace('.',''), ff)
2699 except InvalidAliasError:
2764 except InvalidAliasError:
2700 pass
2765 pass
2701 else:
2766 else:
2702 syscmdlist.append(ff)
2767 syscmdlist.append(ff)
2703 else:
2768 else:
2704 no_alias = self.shell.alias_manager.no_alias
2769 no_alias = self.shell.alias_manager.no_alias
2705 for pdir in path:
2770 for pdir in path:
2706 os.chdir(pdir)
2771 os.chdir(pdir)
2707 for ff in os.listdir(pdir):
2772 for ff in os.listdir(pdir):
2708 base, ext = os.path.splitext(ff)
2773 base, ext = os.path.splitext(ff)
2709 if isexec(ff) and base.lower() not in no_alias:
2774 if isexec(ff) and base.lower() not in no_alias:
2710 if ext.lower() == '.exe':
2775 if ext.lower() == '.exe':
2711 ff = base
2776 ff = base
2712 try:
2777 try:
2713 # Removes dots from the name since ipython
2778 # Removes dots from the name since ipython
2714 # will assume names with dots to be python.
2779 # will assume names with dots to be python.
2715 self.shell.alias_manager.define_alias(
2780 self.shell.alias_manager.define_alias(
2716 base.lower().replace('.',''), ff)
2781 base.lower().replace('.',''), ff)
2717 except InvalidAliasError:
2782 except InvalidAliasError:
2718 pass
2783 pass
2719 syscmdlist.append(ff)
2784 syscmdlist.append(ff)
2720 db = self.db
2785 db = self.db
2721 db['syscmdlist'] = syscmdlist
2786 db['syscmdlist'] = syscmdlist
2722 finally:
2787 finally:
2723 os.chdir(savedir)
2788 os.chdir(savedir)
2724
2789
2725 def magic_pwd(self, parameter_s = ''):
2790 def magic_pwd(self, parameter_s = ''):
2726 """Return the current working directory path."""
2791 """Return the current working directory path."""
2727 return os.getcwd()
2792 return os.getcwd()
2728
2793
2729 def magic_cd(self, parameter_s=''):
2794 def magic_cd(self, parameter_s=''):
2730 """Change the current working directory.
2795 """Change the current working directory.
2731
2796
2732 This command automatically maintains an internal list of directories
2797 This command automatically maintains an internal list of directories
2733 you visit during your IPython session, in the variable _dh. The
2798 you visit during your IPython session, in the variable _dh. The
2734 command %dhist shows this history nicely formatted. You can also
2799 command %dhist shows this history nicely formatted. You can also
2735 do 'cd -<tab>' to see directory history conveniently.
2800 do 'cd -<tab>' to see directory history conveniently.
2736
2801
2737 Usage:
2802 Usage:
2738
2803
2739 cd 'dir': changes to directory 'dir'.
2804 cd 'dir': changes to directory 'dir'.
2740
2805
2741 cd -: changes to the last visited directory.
2806 cd -: changes to the last visited directory.
2742
2807
2743 cd -<n>: changes to the n-th directory in the directory history.
2808 cd -<n>: changes to the n-th directory in the directory history.
2744
2809
2745 cd --foo: change to directory that matches 'foo' in history
2810 cd --foo: change to directory that matches 'foo' in history
2746
2811
2747 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2812 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2748 (note: cd <bookmark_name> is enough if there is no
2813 (note: cd <bookmark_name> is enough if there is no
2749 directory <bookmark_name>, but a bookmark with the name exists.)
2814 directory <bookmark_name>, but a bookmark with the name exists.)
2750 'cd -b <tab>' allows you to tab-complete bookmark names.
2815 'cd -b <tab>' allows you to tab-complete bookmark names.
2751
2816
2752 Options:
2817 Options:
2753
2818
2754 -q: quiet. Do not print the working directory after the cd command is
2819 -q: quiet. Do not print the working directory after the cd command is
2755 executed. By default IPython's cd command does print this directory,
2820 executed. By default IPython's cd command does print this directory,
2756 since the default prompts do not display path information.
2821 since the default prompts do not display path information.
2757
2822
2758 Note that !cd doesn't work for this purpose because the shell where
2823 Note that !cd doesn't work for this purpose because the shell where
2759 !command runs is immediately discarded after executing 'command'."""
2824 !command runs is immediately discarded after executing 'command'."""
2760
2825
2761 parameter_s = parameter_s.strip()
2826 parameter_s = parameter_s.strip()
2762 #bkms = self.shell.persist.get("bookmarks",{})
2827 #bkms = self.shell.persist.get("bookmarks",{})
2763
2828
2764 oldcwd = os.getcwd()
2829 oldcwd = os.getcwd()
2765 numcd = re.match(r'(-)(\d+)$',parameter_s)
2830 numcd = re.match(r'(-)(\d+)$',parameter_s)
2766 # jump in directory history by number
2831 # jump in directory history by number
2767 if numcd:
2832 if numcd:
2768 nn = int(numcd.group(2))
2833 nn = int(numcd.group(2))
2769 try:
2834 try:
2770 ps = self.shell.user_ns['_dh'][nn]
2835 ps = self.shell.user_ns['_dh'][nn]
2771 except IndexError:
2836 except IndexError:
2772 print 'The requested directory does not exist in history.'
2837 print 'The requested directory does not exist in history.'
2773 return
2838 return
2774 else:
2839 else:
2775 opts = {}
2840 opts = {}
2776 elif parameter_s.startswith('--'):
2841 elif parameter_s.startswith('--'):
2777 ps = None
2842 ps = None
2778 fallback = None
2843 fallback = None
2779 pat = parameter_s[2:]
2844 pat = parameter_s[2:]
2780 dh = self.shell.user_ns['_dh']
2845 dh = self.shell.user_ns['_dh']
2781 # first search only by basename (last component)
2846 # first search only by basename (last component)
2782 for ent in reversed(dh):
2847 for ent in reversed(dh):
2783 if pat in os.path.basename(ent) and os.path.isdir(ent):
2848 if pat in os.path.basename(ent) and os.path.isdir(ent):
2784 ps = ent
2849 ps = ent
2785 break
2850 break
2786
2851
2787 if fallback is None and pat in ent and os.path.isdir(ent):
2852 if fallback is None and pat in ent and os.path.isdir(ent):
2788 fallback = ent
2853 fallback = ent
2789
2854
2790 # if we have no last part match, pick the first full path match
2855 # if we have no last part match, pick the first full path match
2791 if ps is None:
2856 if ps is None:
2792 ps = fallback
2857 ps = fallback
2793
2858
2794 if ps is None:
2859 if ps is None:
2795 print "No matching entry in directory history"
2860 print "No matching entry in directory history"
2796 return
2861 return
2797 else:
2862 else:
2798 opts = {}
2863 opts = {}
2799
2864
2800
2865
2801 else:
2866 else:
2802 #turn all non-space-escaping backslashes to slashes,
2867 #turn all non-space-escaping backslashes to slashes,
2803 # for c:\windows\directory\names\
2868 # for c:\windows\directory\names\
2804 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2869 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2805 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2870 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2806 # jump to previous
2871 # jump to previous
2807 if ps == '-':
2872 if ps == '-':
2808 try:
2873 try:
2809 ps = self.shell.user_ns['_dh'][-2]
2874 ps = self.shell.user_ns['_dh'][-2]
2810 except IndexError:
2875 except IndexError:
2811 raise UsageError('%cd -: No previous directory to change to.')
2876 raise UsageError('%cd -: No previous directory to change to.')
2812 # jump to bookmark if needed
2877 # jump to bookmark if needed
2813 else:
2878 else:
2814 if not os.path.isdir(ps) or opts.has_key('b'):
2879 if not os.path.isdir(ps) or opts.has_key('b'):
2815 bkms = self.db.get('bookmarks', {})
2880 bkms = self.db.get('bookmarks', {})
2816
2881
2817 if bkms.has_key(ps):
2882 if bkms.has_key(ps):
2818 target = bkms[ps]
2883 target = bkms[ps]
2819 print '(bookmark:%s) -> %s' % (ps,target)
2884 print '(bookmark:%s) -> %s' % (ps,target)
2820 ps = target
2885 ps = target
2821 else:
2886 else:
2822 if opts.has_key('b'):
2887 if opts.has_key('b'):
2823 raise UsageError("Bookmark '%s' not found. "
2888 raise UsageError("Bookmark '%s' not found. "
2824 "Use '%%bookmark -l' to see your bookmarks." % ps)
2889 "Use '%%bookmark -l' to see your bookmarks." % ps)
2825
2890
2826 # at this point ps should point to the target dir
2891 # at this point ps should point to the target dir
2827 if ps:
2892 if ps:
2828 try:
2893 try:
2829 os.chdir(os.path.expanduser(ps))
2894 os.chdir(os.path.expanduser(ps))
2830 if self.shell.term_title:
2895 if self.shell.term_title:
2831 set_term_title('IPython: ' + abbrev_cwd())
2896 set_term_title('IPython: ' + abbrev_cwd())
2832 except OSError:
2897 except OSError:
2833 print sys.exc_info()[1]
2898 print sys.exc_info()[1]
2834 else:
2899 else:
2835 cwd = os.getcwd()
2900 cwd = os.getcwd()
2836 dhist = self.shell.user_ns['_dh']
2901 dhist = self.shell.user_ns['_dh']
2837 if oldcwd != cwd:
2902 if oldcwd != cwd:
2838 dhist.append(cwd)
2903 dhist.append(cwd)
2839 self.db['dhist'] = compress_dhist(dhist)[-100:]
2904 self.db['dhist'] = compress_dhist(dhist)[-100:]
2840
2905
2841 else:
2906 else:
2842 os.chdir(self.shell.home_dir)
2907 os.chdir(self.shell.home_dir)
2843 if self.shell.term_title:
2908 if self.shell.term_title:
2844 set_term_title('IPython: ' + '~')
2909 set_term_title('IPython: ' + '~')
2845 cwd = os.getcwd()
2910 cwd = os.getcwd()
2846 dhist = self.shell.user_ns['_dh']
2911 dhist = self.shell.user_ns['_dh']
2847
2912
2848 if oldcwd != cwd:
2913 if oldcwd != cwd:
2849 dhist.append(cwd)
2914 dhist.append(cwd)
2850 self.db['dhist'] = compress_dhist(dhist)[-100:]
2915 self.db['dhist'] = compress_dhist(dhist)[-100:]
2851 if not 'q' in opts and self.shell.user_ns['_dh']:
2916 if not 'q' in opts and self.shell.user_ns['_dh']:
2852 print self.shell.user_ns['_dh'][-1]
2917 print self.shell.user_ns['_dh'][-1]
2853
2918
2854
2919
2855 def magic_env(self, parameter_s=''):
2920 def magic_env(self, parameter_s=''):
2856 """List environment variables."""
2921 """List environment variables."""
2857
2922
2858 return os.environ.data
2923 return os.environ.data
2859
2924
2860 def magic_pushd(self, parameter_s=''):
2925 def magic_pushd(self, parameter_s=''):
2861 """Place the current dir on stack and change directory.
2926 """Place the current dir on stack and change directory.
2862
2927
2863 Usage:\\
2928 Usage:\\
2864 %pushd ['dirname']
2929 %pushd ['dirname']
2865 """
2930 """
2866
2931
2867 dir_s = self.shell.dir_stack
2932 dir_s = self.shell.dir_stack
2868 tgt = os.path.expanduser(parameter_s)
2933 tgt = os.path.expanduser(parameter_s)
2869 cwd = os.getcwd().replace(self.home_dir,'~')
2934 cwd = os.getcwd().replace(self.home_dir,'~')
2870 if tgt:
2935 if tgt:
2871 self.magic_cd(parameter_s)
2936 self.magic_cd(parameter_s)
2872 dir_s.insert(0,cwd)
2937 dir_s.insert(0,cwd)
2873 return self.magic_dirs()
2938 return self.magic_dirs()
2874
2939
2875 def magic_popd(self, parameter_s=''):
2940 def magic_popd(self, parameter_s=''):
2876 """Change to directory popped off the top of the stack.
2941 """Change to directory popped off the top of the stack.
2877 """
2942 """
2878 if not self.shell.dir_stack:
2943 if not self.shell.dir_stack:
2879 raise UsageError("%popd on empty stack")
2944 raise UsageError("%popd on empty stack")
2880 top = self.shell.dir_stack.pop(0)
2945 top = self.shell.dir_stack.pop(0)
2881 self.magic_cd(top)
2946 self.magic_cd(top)
2882 print "popd ->",top
2947 print "popd ->",top
2883
2948
2884 def magic_dirs(self, parameter_s=''):
2949 def magic_dirs(self, parameter_s=''):
2885 """Return the current directory stack."""
2950 """Return the current directory stack."""
2886
2951
2887 return self.shell.dir_stack
2952 return self.shell.dir_stack
2888
2953
2889 def magic_dhist(self, parameter_s=''):
2954 def magic_dhist(self, parameter_s=''):
2890 """Print your history of visited directories.
2955 """Print your history of visited directories.
2891
2956
2892 %dhist -> print full history\\
2957 %dhist -> print full history\\
2893 %dhist n -> print last n entries only\\
2958 %dhist n -> print last n entries only\\
2894 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2959 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2895
2960
2896 This history is automatically maintained by the %cd command, and
2961 This history is automatically maintained by the %cd command, and
2897 always available as the global list variable _dh. You can use %cd -<n>
2962 always available as the global list variable _dh. You can use %cd -<n>
2898 to go to directory number <n>.
2963 to go to directory number <n>.
2899
2964
2900 Note that most of time, you should view directory history by entering
2965 Note that most of time, you should view directory history by entering
2901 cd -<TAB>.
2966 cd -<TAB>.
2902
2967
2903 """
2968 """
2904
2969
2905 dh = self.shell.user_ns['_dh']
2970 dh = self.shell.user_ns['_dh']
2906 if parameter_s:
2971 if parameter_s:
2907 try:
2972 try:
2908 args = map(int,parameter_s.split())
2973 args = map(int,parameter_s.split())
2909 except:
2974 except:
2910 self.arg_err(Magic.magic_dhist)
2975 self.arg_err(Magic.magic_dhist)
2911 return
2976 return
2912 if len(args) == 1:
2977 if len(args) == 1:
2913 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2978 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2914 elif len(args) == 2:
2979 elif len(args) == 2:
2915 ini,fin = args
2980 ini,fin = args
2916 else:
2981 else:
2917 self.arg_err(Magic.magic_dhist)
2982 self.arg_err(Magic.magic_dhist)
2918 return
2983 return
2919 else:
2984 else:
2920 ini,fin = 0,len(dh)
2985 ini,fin = 0,len(dh)
2921 nlprint(dh,
2986 nlprint(dh,
2922 header = 'Directory history (kept in _dh)',
2987 header = 'Directory history (kept in _dh)',
2923 start=ini,stop=fin)
2988 start=ini,stop=fin)
2924
2989
2925 @testdec.skip_doctest
2990 @testdec.skip_doctest
2926 def magic_sc(self, parameter_s=''):
2991 def magic_sc(self, parameter_s=''):
2927 """Shell capture - execute a shell command and capture its output.
2992 """Shell capture - execute a shell command and capture its output.
2928
2993
2929 DEPRECATED. Suboptimal, retained for backwards compatibility.
2994 DEPRECATED. Suboptimal, retained for backwards compatibility.
2930
2995
2931 You should use the form 'var = !command' instead. Example:
2996 You should use the form 'var = !command' instead. Example:
2932
2997
2933 "%sc -l myfiles = ls ~" should now be written as
2998 "%sc -l myfiles = ls ~" should now be written as
2934
2999
2935 "myfiles = !ls ~"
3000 "myfiles = !ls ~"
2936
3001
2937 myfiles.s, myfiles.l and myfiles.n still apply as documented
3002 myfiles.s, myfiles.l and myfiles.n still apply as documented
2938 below.
3003 below.
2939
3004
2940 --
3005 --
2941 %sc [options] varname=command
3006 %sc [options] varname=command
2942
3007
2943 IPython will run the given command using commands.getoutput(), and
3008 IPython will run the given command using commands.getoutput(), and
2944 will then update the user's interactive namespace with a variable
3009 will then update the user's interactive namespace with a variable
2945 called varname, containing the value of the call. Your command can
3010 called varname, containing the value of the call. Your command can
2946 contain shell wildcards, pipes, etc.
3011 contain shell wildcards, pipes, etc.
2947
3012
2948 The '=' sign in the syntax is mandatory, and the variable name you
3013 The '=' sign in the syntax is mandatory, and the variable name you
2949 supply must follow Python's standard conventions for valid names.
3014 supply must follow Python's standard conventions for valid names.
2950
3015
2951 (A special format without variable name exists for internal use)
3016 (A special format without variable name exists for internal use)
2952
3017
2953 Options:
3018 Options:
2954
3019
2955 -l: list output. Split the output on newlines into a list before
3020 -l: list output. Split the output on newlines into a list before
2956 assigning it to the given variable. By default the output is stored
3021 assigning it to the given variable. By default the output is stored
2957 as a single string.
3022 as a single string.
2958
3023
2959 -v: verbose. Print the contents of the variable.
3024 -v: verbose. Print the contents of the variable.
2960
3025
2961 In most cases you should not need to split as a list, because the
3026 In most cases you should not need to split as a list, because the
2962 returned value is a special type of string which can automatically
3027 returned value is a special type of string which can automatically
2963 provide its contents either as a list (split on newlines) or as a
3028 provide its contents either as a list (split on newlines) or as a
2964 space-separated string. These are convenient, respectively, either
3029 space-separated string. These are convenient, respectively, either
2965 for sequential processing or to be passed to a shell command.
3030 for sequential processing or to be passed to a shell command.
2966
3031
2967 For example:
3032 For example:
2968
3033
2969 # all-random
3034 # all-random
2970
3035
2971 # Capture into variable a
3036 # Capture into variable a
2972 In [1]: sc a=ls *py
3037 In [1]: sc a=ls *py
2973
3038
2974 # a is a string with embedded newlines
3039 # a is a string with embedded newlines
2975 In [2]: a
3040 In [2]: a
2976 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3041 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2977
3042
2978 # which can be seen as a list:
3043 # which can be seen as a list:
2979 In [3]: a.l
3044 In [3]: a.l
2980 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3045 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2981
3046
2982 # or as a whitespace-separated string:
3047 # or as a whitespace-separated string:
2983 In [4]: a.s
3048 In [4]: a.s
2984 Out[4]: 'setup.py win32_manual_post_install.py'
3049 Out[4]: 'setup.py win32_manual_post_install.py'
2985
3050
2986 # a.s is useful to pass as a single command line:
3051 # a.s is useful to pass as a single command line:
2987 In [5]: !wc -l $a.s
3052 In [5]: !wc -l $a.s
2988 146 setup.py
3053 146 setup.py
2989 130 win32_manual_post_install.py
3054 130 win32_manual_post_install.py
2990 276 total
3055 276 total
2991
3056
2992 # while the list form is useful to loop over:
3057 # while the list form is useful to loop over:
2993 In [6]: for f in a.l:
3058 In [6]: for f in a.l:
2994 ...: !wc -l $f
3059 ...: !wc -l $f
2995 ...:
3060 ...:
2996 146 setup.py
3061 146 setup.py
2997 130 win32_manual_post_install.py
3062 130 win32_manual_post_install.py
2998
3063
2999 Similiarly, the lists returned by the -l option are also special, in
3064 Similiarly, the lists returned by the -l option are also special, in
3000 the sense that you can equally invoke the .s attribute on them to
3065 the sense that you can equally invoke the .s attribute on them to
3001 automatically get a whitespace-separated string from their contents:
3066 automatically get a whitespace-separated string from their contents:
3002
3067
3003 In [7]: sc -l b=ls *py
3068 In [7]: sc -l b=ls *py
3004
3069
3005 In [8]: b
3070 In [8]: b
3006 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3071 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3007
3072
3008 In [9]: b.s
3073 In [9]: b.s
3009 Out[9]: 'setup.py win32_manual_post_install.py'
3074 Out[9]: 'setup.py win32_manual_post_install.py'
3010
3075
3011 In summary, both the lists and strings used for ouptut capture have
3076 In summary, both the lists and strings used for ouptut capture have
3012 the following special attributes:
3077 the following special attributes:
3013
3078
3014 .l (or .list) : value as list.
3079 .l (or .list) : value as list.
3015 .n (or .nlstr): value as newline-separated string.
3080 .n (or .nlstr): value as newline-separated string.
3016 .s (or .spstr): value as space-separated string.
3081 .s (or .spstr): value as space-separated string.
3017 """
3082 """
3018
3083
3019 opts,args = self.parse_options(parameter_s,'lv')
3084 opts,args = self.parse_options(parameter_s,'lv')
3020 # Try to get a variable name and command to run
3085 # Try to get a variable name and command to run
3021 try:
3086 try:
3022 # the variable name must be obtained from the parse_options
3087 # the variable name must be obtained from the parse_options
3023 # output, which uses shlex.split to strip options out.
3088 # output, which uses shlex.split to strip options out.
3024 var,_ = args.split('=',1)
3089 var,_ = args.split('=',1)
3025 var = var.strip()
3090 var = var.strip()
3026 # But the the command has to be extracted from the original input
3091 # But the the command has to be extracted from the original input
3027 # parameter_s, not on what parse_options returns, to avoid the
3092 # parameter_s, not on what parse_options returns, to avoid the
3028 # quote stripping which shlex.split performs on it.
3093 # quote stripping which shlex.split performs on it.
3029 _,cmd = parameter_s.split('=',1)
3094 _,cmd = parameter_s.split('=',1)
3030 except ValueError:
3095 except ValueError:
3031 var,cmd = '',''
3096 var,cmd = '',''
3032 # If all looks ok, proceed
3097 # If all looks ok, proceed
3033 out,err = self.shell.getoutputerror(cmd)
3098 out,err = self.shell.getoutputerror(cmd)
3034 if err:
3099 if err:
3035 print >> Term.cerr,err
3100 print >> Term.cerr,err
3036 if opts.has_key('l'):
3101 if opts.has_key('l'):
3037 out = SList(out.split('\n'))
3102 out = SList(out.split('\n'))
3038 else:
3103 else:
3039 out = LSString(out)
3104 out = LSString(out)
3040 if opts.has_key('v'):
3105 if opts.has_key('v'):
3041 print '%s ==\n%s' % (var,pformat(out))
3106 print '%s ==\n%s' % (var,pformat(out))
3042 if var:
3107 if var:
3043 self.shell.user_ns.update({var:out})
3108 self.shell.user_ns.update({var:out})
3044 else:
3109 else:
3045 return out
3110 return out
3046
3111
3047 def magic_sx(self, parameter_s=''):
3112 def magic_sx(self, parameter_s=''):
3048 """Shell execute - run a shell command and capture its output.
3113 """Shell execute - run a shell command and capture its output.
3049
3114
3050 %sx command
3115 %sx command
3051
3116
3052 IPython will run the given command using commands.getoutput(), and
3117 IPython will run the given command using commands.getoutput(), and
3053 return the result formatted as a list (split on '\\n'). Since the
3118 return the result formatted as a list (split on '\\n'). Since the
3054 output is _returned_, it will be stored in ipython's regular output
3119 output is _returned_, it will be stored in ipython's regular output
3055 cache Out[N] and in the '_N' automatic variables.
3120 cache Out[N] and in the '_N' automatic variables.
3056
3121
3057 Notes:
3122 Notes:
3058
3123
3059 1) If an input line begins with '!!', then %sx is automatically
3124 1) If an input line begins with '!!', then %sx is automatically
3060 invoked. That is, while:
3125 invoked. That is, while:
3061 !ls
3126 !ls
3062 causes ipython to simply issue system('ls'), typing
3127 causes ipython to simply issue system('ls'), typing
3063 !!ls
3128 !!ls
3064 is a shorthand equivalent to:
3129 is a shorthand equivalent to:
3065 %sx ls
3130 %sx ls
3066
3131
3067 2) %sx differs from %sc in that %sx automatically splits into a list,
3132 2) %sx differs from %sc in that %sx automatically splits into a list,
3068 like '%sc -l'. The reason for this is to make it as easy as possible
3133 like '%sc -l'. The reason for this is to make it as easy as possible
3069 to process line-oriented shell output via further python commands.
3134 to process line-oriented shell output via further python commands.
3070 %sc is meant to provide much finer control, but requires more
3135 %sc is meant to provide much finer control, but requires more
3071 typing.
3136 typing.
3072
3137
3073 3) Just like %sc -l, this is a list with special attributes:
3138 3) Just like %sc -l, this is a list with special attributes:
3074
3139
3075 .l (or .list) : value as list.
3140 .l (or .list) : value as list.
3076 .n (or .nlstr): value as newline-separated string.
3141 .n (or .nlstr): value as newline-separated string.
3077 .s (or .spstr): value as whitespace-separated string.
3142 .s (or .spstr): value as whitespace-separated string.
3078
3143
3079 This is very useful when trying to use such lists as arguments to
3144 This is very useful when trying to use such lists as arguments to
3080 system commands."""
3145 system commands."""
3081
3146
3082 if parameter_s:
3147 if parameter_s:
3083 out,err = self.shell.getoutputerror(parameter_s)
3148 out,err = self.shell.getoutputerror(parameter_s)
3084 if err:
3149 if err:
3085 print >> Term.cerr,err
3150 print >> Term.cerr,err
3086 return SList(out.split('\n'))
3151 return SList(out.split('\n'))
3087
3152
3088 def magic_bg(self, parameter_s=''):
3153 def magic_bg(self, parameter_s=''):
3089 """Run a job in the background, in a separate thread.
3154 """Run a job in the background, in a separate thread.
3090
3155
3091 For example,
3156 For example,
3092
3157
3093 %bg myfunc(x,y,z=1)
3158 %bg myfunc(x,y,z=1)
3094
3159
3095 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3160 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3096 execution starts, a message will be printed indicating the job
3161 execution starts, a message will be printed indicating the job
3097 number. If your job number is 5, you can use
3162 number. If your job number is 5, you can use
3098
3163
3099 myvar = jobs.result(5) or myvar = jobs[5].result
3164 myvar = jobs.result(5) or myvar = jobs[5].result
3100
3165
3101 to assign this result to variable 'myvar'.
3166 to assign this result to variable 'myvar'.
3102
3167
3103 IPython has a job manager, accessible via the 'jobs' object. You can
3168 IPython has a job manager, accessible via the 'jobs' object. You can
3104 type jobs? to get more information about it, and use jobs.<TAB> to see
3169 type jobs? to get more information about it, and use jobs.<TAB> to see
3105 its attributes. All attributes not starting with an underscore are
3170 its attributes. All attributes not starting with an underscore are
3106 meant for public use.
3171 meant for public use.
3107
3172
3108 In particular, look at the jobs.new() method, which is used to create
3173 In particular, look at the jobs.new() method, which is used to create
3109 new jobs. This magic %bg function is just a convenience wrapper
3174 new jobs. This magic %bg function is just a convenience wrapper
3110 around jobs.new(), for expression-based jobs. If you want to create a
3175 around jobs.new(), for expression-based jobs. If you want to create a
3111 new job with an explicit function object and arguments, you must call
3176 new job with an explicit function object and arguments, you must call
3112 jobs.new() directly.
3177 jobs.new() directly.
3113
3178
3114 The jobs.new docstring also describes in detail several important
3179 The jobs.new docstring also describes in detail several important
3115 caveats associated with a thread-based model for background job
3180 caveats associated with a thread-based model for background job
3116 execution. Type jobs.new? for details.
3181 execution. Type jobs.new? for details.
3117
3182
3118 You can check the status of all jobs with jobs.status().
3183 You can check the status of all jobs with jobs.status().
3119
3184
3120 The jobs variable is set by IPython into the Python builtin namespace.
3185 The jobs variable is set by IPython into the Python builtin namespace.
3121 If you ever declare a variable named 'jobs', you will shadow this
3186 If you ever declare a variable named 'jobs', you will shadow this
3122 name. You can either delete your global jobs variable to regain
3187 name. You can either delete your global jobs variable to regain
3123 access to the job manager, or make a new name and assign it manually
3188 access to the job manager, or make a new name and assign it manually
3124 to the manager (stored in IPython's namespace). For example, to
3189 to the manager (stored in IPython's namespace). For example, to
3125 assign the job manager to the Jobs name, use:
3190 assign the job manager to the Jobs name, use:
3126
3191
3127 Jobs = __builtins__.jobs"""
3192 Jobs = __builtins__.jobs"""
3128
3193
3129 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3194 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3130
3195
3131 def magic_r(self, parameter_s=''):
3196 def magic_r(self, parameter_s=''):
3132 """Repeat previous input.
3197 """Repeat previous input.
3133
3198
3134 Note: Consider using the more powerfull %rep instead!
3199 Note: Consider using the more powerfull %rep instead!
3135
3200
3136 If given an argument, repeats the previous command which starts with
3201 If given an argument, repeats the previous command which starts with
3137 the same string, otherwise it just repeats the previous input.
3202 the same string, otherwise it just repeats the previous input.
3138
3203
3139 Shell escaped commands (with ! as first character) are not recognized
3204 Shell escaped commands (with ! as first character) are not recognized
3140 by this system, only pure python code and magic commands.
3205 by this system, only pure python code and magic commands.
3141 """
3206 """
3142
3207
3143 start = parameter_s.strip()
3208 start = parameter_s.strip()
3144 esc_magic = ESC_MAGIC
3209 esc_magic = ESC_MAGIC
3145 # Identify magic commands even if automagic is on (which means
3210 # Identify magic commands even if automagic is on (which means
3146 # the in-memory version is different from that typed by the user).
3211 # the in-memory version is different from that typed by the user).
3147 if self.shell.automagic:
3212 if self.shell.automagic:
3148 start_magic = esc_magic+start
3213 start_magic = esc_magic+start
3149 else:
3214 else:
3150 start_magic = start
3215 start_magic = start
3151 # Look through the input history in reverse
3216 # Look through the input history in reverse
3152 for n in range(len(self.shell.input_hist)-2,0,-1):
3217 for n in range(len(self.shell.input_hist)-2,0,-1):
3153 input = self.shell.input_hist[n]
3218 input = self.shell.input_hist[n]
3154 # skip plain 'r' lines so we don't recurse to infinity
3219 # skip plain 'r' lines so we don't recurse to infinity
3155 if input != '_ip.magic("r")\n' and \
3220 if input != '_ip.magic("r")\n' and \
3156 (input.startswith(start) or input.startswith(start_magic)):
3221 (input.startswith(start) or input.startswith(start_magic)):
3157 #print 'match',`input` # dbg
3222 #print 'match',`input` # dbg
3158 print 'Executing:',input,
3223 print 'Executing:',input,
3159 self.shell.runlines(input)
3224 self.shell.runlines(input)
3160 return
3225 return
3161 print 'No previous input matching `%s` found.' % start
3226 print 'No previous input matching `%s` found.' % start
3162
3227
3163
3228
3164 def magic_bookmark(self, parameter_s=''):
3229 def magic_bookmark(self, parameter_s=''):
3165 """Manage IPython's bookmark system.
3230 """Manage IPython's bookmark system.
3166
3231
3167 %bookmark <name> - set bookmark to current dir
3232 %bookmark <name> - set bookmark to current dir
3168 %bookmark <name> <dir> - set bookmark to <dir>
3233 %bookmark <name> <dir> - set bookmark to <dir>
3169 %bookmark -l - list all bookmarks
3234 %bookmark -l - list all bookmarks
3170 %bookmark -d <name> - remove bookmark
3235 %bookmark -d <name> - remove bookmark
3171 %bookmark -r - remove all bookmarks
3236 %bookmark -r - remove all bookmarks
3172
3237
3173 You can later on access a bookmarked folder with:
3238 You can later on access a bookmarked folder with:
3174 %cd -b <name>
3239 %cd -b <name>
3175 or simply '%cd <name>' if there is no directory called <name> AND
3240 or simply '%cd <name>' if there is no directory called <name> AND
3176 there is such a bookmark defined.
3241 there is such a bookmark defined.
3177
3242
3178 Your bookmarks persist through IPython sessions, but they are
3243 Your bookmarks persist through IPython sessions, but they are
3179 associated with each profile."""
3244 associated with each profile."""
3180
3245
3181 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3246 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3182 if len(args) > 2:
3247 if len(args) > 2:
3183 raise UsageError("%bookmark: too many arguments")
3248 raise UsageError("%bookmark: too many arguments")
3184
3249
3185 bkms = self.db.get('bookmarks',{})
3250 bkms = self.db.get('bookmarks',{})
3186
3251
3187 if opts.has_key('d'):
3252 if opts.has_key('d'):
3188 try:
3253 try:
3189 todel = args[0]
3254 todel = args[0]
3190 except IndexError:
3255 except IndexError:
3191 raise UsageError(
3256 raise UsageError(
3192 "%bookmark -d: must provide a bookmark to delete")
3257 "%bookmark -d: must provide a bookmark to delete")
3193 else:
3258 else:
3194 try:
3259 try:
3195 del bkms[todel]
3260 del bkms[todel]
3196 except KeyError:
3261 except KeyError:
3197 raise UsageError(
3262 raise UsageError(
3198 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3263 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3199
3264
3200 elif opts.has_key('r'):
3265 elif opts.has_key('r'):
3201 bkms = {}
3266 bkms = {}
3202 elif opts.has_key('l'):
3267 elif opts.has_key('l'):
3203 bks = bkms.keys()
3268 bks = bkms.keys()
3204 bks.sort()
3269 bks.sort()
3205 if bks:
3270 if bks:
3206 size = max(map(len,bks))
3271 size = max(map(len,bks))
3207 else:
3272 else:
3208 size = 0
3273 size = 0
3209 fmt = '%-'+str(size)+'s -> %s'
3274 fmt = '%-'+str(size)+'s -> %s'
3210 print 'Current bookmarks:'
3275 print 'Current bookmarks:'
3211 for bk in bks:
3276 for bk in bks:
3212 print fmt % (bk,bkms[bk])
3277 print fmt % (bk,bkms[bk])
3213 else:
3278 else:
3214 if not args:
3279 if not args:
3215 raise UsageError("%bookmark: You must specify the bookmark name")
3280 raise UsageError("%bookmark: You must specify the bookmark name")
3216 elif len(args)==1:
3281 elif len(args)==1:
3217 bkms[args[0]] = os.getcwd()
3282 bkms[args[0]] = os.getcwd()
3218 elif len(args)==2:
3283 elif len(args)==2:
3219 bkms[args[0]] = args[1]
3284 bkms[args[0]] = args[1]
3220 self.db['bookmarks'] = bkms
3285 self.db['bookmarks'] = bkms
3221
3286
3222 def magic_pycat(self, parameter_s=''):
3287 def magic_pycat(self, parameter_s=''):
3223 """Show a syntax-highlighted file through a pager.
3288 """Show a syntax-highlighted file through a pager.
3224
3289
3225 This magic is similar to the cat utility, but it will assume the file
3290 This magic is similar to the cat utility, but it will assume the file
3226 to be Python source and will show it with syntax highlighting. """
3291 to be Python source and will show it with syntax highlighting. """
3227
3292
3228 try:
3293 try:
3229 filename = get_py_filename(parameter_s)
3294 filename = get_py_filename(parameter_s)
3230 cont = file_read(filename)
3295 cont = file_read(filename)
3231 except IOError:
3296 except IOError:
3232 try:
3297 try:
3233 cont = eval(parameter_s,self.user_ns)
3298 cont = eval(parameter_s,self.user_ns)
3234 except NameError:
3299 except NameError:
3235 cont = None
3300 cont = None
3236 if cont is None:
3301 if cont is None:
3237 print "Error: no such file or variable"
3302 print "Error: no such file or variable"
3238 return
3303 return
3239
3304
3240 page(self.shell.pycolorize(cont),
3305 page(self.shell.pycolorize(cont),
3241 screen_lines=self.shell.usable_screen_length)
3306 screen_lines=self.shell.usable_screen_length)
3242
3307
3243 def _rerun_pasted(self):
3308 def _rerun_pasted(self):
3244 """ Rerun a previously pasted command.
3309 """ Rerun a previously pasted command.
3245 """
3310 """
3246 b = self.user_ns.get('pasted_block', None)
3311 b = self.user_ns.get('pasted_block', None)
3247 if b is None:
3312 if b is None:
3248 raise UsageError('No previous pasted block available')
3313 raise UsageError('No previous pasted block available')
3249 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3314 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3250 exec b in self.user_ns
3315 exec b in self.user_ns
3251
3316
3252 def _get_pasted_lines(self, sentinel):
3317 def _get_pasted_lines(self, sentinel):
3253 """ Yield pasted lines until the user enters the given sentinel value.
3318 """ Yield pasted lines until the user enters the given sentinel value.
3254 """
3319 """
3255 from IPython.core import iplib
3320 from IPython.core import iplib
3256 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3321 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3257 while True:
3322 while True:
3258 l = iplib.raw_input_original(':')
3323 l = iplib.raw_input_original(':')
3259 if l == sentinel:
3324 if l == sentinel:
3260 return
3325 return
3261 else:
3326 else:
3262 yield l
3327 yield l
3263
3328
3264 def _strip_pasted_lines_for_code(self, raw_lines):
3329 def _strip_pasted_lines_for_code(self, raw_lines):
3265 """ Strip non-code parts of a sequence of lines to return a block of
3330 """ Strip non-code parts of a sequence of lines to return a block of
3266 code.
3331 code.
3267 """
3332 """
3268 # Regular expressions that declare text we strip from the input:
3333 # Regular expressions that declare text we strip from the input:
3269 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3334 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3270 r'^\s*(\s?>)+', # Python input prompt
3335 r'^\s*(\s?>)+', # Python input prompt
3271 r'^\s*\.{3,}', # Continuation prompts
3336 r'^\s*\.{3,}', # Continuation prompts
3272 r'^\++',
3337 r'^\++',
3273 ]
3338 ]
3274
3339
3275 strip_from_start = map(re.compile,strip_re)
3340 strip_from_start = map(re.compile,strip_re)
3276
3341
3277 lines = []
3342 lines = []
3278 for l in raw_lines:
3343 for l in raw_lines:
3279 for pat in strip_from_start:
3344 for pat in strip_from_start:
3280 l = pat.sub('',l)
3345 l = pat.sub('',l)
3281 lines.append(l)
3346 lines.append(l)
3282
3347
3283 block = "\n".join(lines) + '\n'
3348 block = "\n".join(lines) + '\n'
3284 #print "block:\n",block
3349 #print "block:\n",block
3285 return block
3350 return block
3286
3351
3287 def _execute_block(self, block, par):
3352 def _execute_block(self, block, par):
3288 """ Execute a block, or store it in a variable, per the user's request.
3353 """ Execute a block, or store it in a variable, per the user's request.
3289 """
3354 """
3290 if not par:
3355 if not par:
3291 b = textwrap.dedent(block)
3356 b = textwrap.dedent(block)
3292 self.user_ns['pasted_block'] = b
3357 self.user_ns['pasted_block'] = b
3293 exec b in self.user_ns
3358 exec b in self.user_ns
3294 else:
3359 else:
3295 self.user_ns[par] = SList(block.splitlines())
3360 self.user_ns[par] = SList(block.splitlines())
3296 print "Block assigned to '%s'" % par
3361 print "Block assigned to '%s'" % par
3297
3362
3298 def magic_cpaste(self, parameter_s=''):
3363 def magic_cpaste(self, parameter_s=''):
3299 """Allows you to paste & execute a pre-formatted code block from clipboard.
3364 """Allows you to paste & execute a pre-formatted code block from clipboard.
3300
3365
3301 You must terminate the block with '--' (two minus-signs) alone on the
3366 You must terminate the block with '--' (two minus-signs) alone on the
3302 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3367 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3303 is the new sentinel for this operation)
3368 is the new sentinel for this operation)
3304
3369
3305 The block is dedented prior to execution to enable execution of method
3370 The block is dedented prior to execution to enable execution of method
3306 definitions. '>' and '+' characters at the beginning of a line are
3371 definitions. '>' and '+' characters at the beginning of a line are
3307 ignored, to allow pasting directly from e-mails, diff files and
3372 ignored, to allow pasting directly from e-mails, diff files and
3308 doctests (the '...' continuation prompt is also stripped). The
3373 doctests (the '...' continuation prompt is also stripped). The
3309 executed block is also assigned to variable named 'pasted_block' for
3374 executed block is also assigned to variable named 'pasted_block' for
3310 later editing with '%edit pasted_block'.
3375 later editing with '%edit pasted_block'.
3311
3376
3312 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3377 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3313 This assigns the pasted block to variable 'foo' as string, without
3378 This assigns the pasted block to variable 'foo' as string, without
3314 dedenting or executing it (preceding >>> and + is still stripped)
3379 dedenting or executing it (preceding >>> and + is still stripped)
3315
3380
3316 '%cpaste -r' re-executes the block previously entered by cpaste.
3381 '%cpaste -r' re-executes the block previously entered by cpaste.
3317
3382
3318 Do not be alarmed by garbled output on Windows (it's a readline bug).
3383 Do not be alarmed by garbled output on Windows (it's a readline bug).
3319 Just press enter and type -- (and press enter again) and the block
3384 Just press enter and type -- (and press enter again) and the block
3320 will be what was just pasted.
3385 will be what was just pasted.
3321
3386
3322 IPython statements (magics, shell escapes) are not supported (yet).
3387 IPython statements (magics, shell escapes) are not supported (yet).
3323
3388
3324 See also
3389 See also
3325 --------
3390 --------
3326 paste: automatically pull code from clipboard.
3391 paste: automatically pull code from clipboard.
3327 """
3392 """
3328
3393
3329 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3394 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3330 par = args.strip()
3395 par = args.strip()
3331 if opts.has_key('r'):
3396 if opts.has_key('r'):
3332 self._rerun_pasted()
3397 self._rerun_pasted()
3333 return
3398 return
3334
3399
3335 sentinel = opts.get('s','--')
3400 sentinel = opts.get('s','--')
3336
3401
3337 block = self._strip_pasted_lines_for_code(
3402 block = self._strip_pasted_lines_for_code(
3338 self._get_pasted_lines(sentinel))
3403 self._get_pasted_lines(sentinel))
3339
3404
3340 self._execute_block(block, par)
3405 self._execute_block(block, par)
3341
3406
3342 def magic_paste(self, parameter_s=''):
3407 def magic_paste(self, parameter_s=''):
3343 """Allows you to paste & execute a pre-formatted code block from clipboard.
3408 """Allows you to paste & execute a pre-formatted code block from clipboard.
3344
3409
3345 The text is pulled directly from the clipboard without user
3410 The text is pulled directly from the clipboard without user
3346 intervention and printed back on the screen before execution (unless
3411 intervention and printed back on the screen before execution (unless
3347 the -q flag is given to force quiet mode).
3412 the -q flag is given to force quiet mode).
3348
3413
3349 The block is dedented prior to execution to enable execution of method
3414 The block is dedented prior to execution to enable execution of method
3350 definitions. '>' and '+' characters at the beginning of a line are
3415 definitions. '>' and '+' characters at the beginning of a line are
3351 ignored, to allow pasting directly from e-mails, diff files and
3416 ignored, to allow pasting directly from e-mails, diff files and
3352 doctests (the '...' continuation prompt is also stripped). The
3417 doctests (the '...' continuation prompt is also stripped). The
3353 executed block is also assigned to variable named 'pasted_block' for
3418 executed block is also assigned to variable named 'pasted_block' for
3354 later editing with '%edit pasted_block'.
3419 later editing with '%edit pasted_block'.
3355
3420
3356 You can also pass a variable name as an argument, e.g. '%paste foo'.
3421 You can also pass a variable name as an argument, e.g. '%paste foo'.
3357 This assigns the pasted block to variable 'foo' as string, without
3422 This assigns the pasted block to variable 'foo' as string, without
3358 dedenting or executing it (preceding >>> and + is still stripped)
3423 dedenting or executing it (preceding >>> and + is still stripped)
3359
3424
3360 Options
3425 Options
3361 -------
3426 -------
3362
3427
3363 -r: re-executes the block previously entered by cpaste.
3428 -r: re-executes the block previously entered by cpaste.
3364
3429
3365 -q: quiet mode: do not echo the pasted text back to the terminal.
3430 -q: quiet mode: do not echo the pasted text back to the terminal.
3366
3431
3367 IPython statements (magics, shell escapes) are not supported (yet).
3432 IPython statements (magics, shell escapes) are not supported (yet).
3368
3433
3369 See also
3434 See also
3370 --------
3435 --------
3371 cpaste: manually paste code into terminal until you mark its end.
3436 cpaste: manually paste code into terminal until you mark its end.
3372 """
3437 """
3373 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3438 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3374 par = args.strip()
3439 par = args.strip()
3375 if opts.has_key('r'):
3440 if opts.has_key('r'):
3376 self._rerun_pasted()
3441 self._rerun_pasted()
3377 return
3442 return
3378
3443
3379 text = self.shell.hooks.clipboard_get()
3444 text = self.shell.hooks.clipboard_get()
3380 block = self._strip_pasted_lines_for_code(text.splitlines())
3445 block = self._strip_pasted_lines_for_code(text.splitlines())
3381
3446
3382 # By default, echo back to terminal unless quiet mode is requested
3447 # By default, echo back to terminal unless quiet mode is requested
3383 if not opts.has_key('q'):
3448 if not opts.has_key('q'):
3384 write = self.shell.write
3449 write = self.shell.write
3385 write(self.shell.pycolorize(block))
3450 write(self.shell.pycolorize(block))
3386 if not block.endswith('\n'):
3451 if not block.endswith('\n'):
3387 write('\n')
3452 write('\n')
3388 write("## -- End pasted text --\n")
3453 write("## -- End pasted text --\n")
3389
3454
3390 self._execute_block(block, par)
3455 self._execute_block(block, par)
3391
3456
3392 def magic_quickref(self,arg):
3457 def magic_quickref(self,arg):
3393 """ Show a quick reference sheet """
3458 """ Show a quick reference sheet """
3394 import IPython.core.usage
3459 import IPython.core.usage
3395 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3460 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3396
3461
3397 page(qr)
3462 page(qr)
3398
3463
3399 def magic_doctest_mode(self,parameter_s=''):
3464 def magic_doctest_mode(self,parameter_s=''):
3400 """Toggle doctest mode on and off.
3465 """Toggle doctest mode on and off.
3401
3466
3402 This mode allows you to toggle the prompt behavior between normal
3467 This mode allows you to toggle the prompt behavior between normal
3403 IPython prompts and ones that are as similar to the default IPython
3468 IPython prompts and ones that are as similar to the default IPython
3404 interpreter as possible.
3469 interpreter as possible.
3405
3470
3406 It also supports the pasting of code snippets that have leading '>>>'
3471 It also supports the pasting of code snippets that have leading '>>>'
3407 and '...' prompts in them. This means that you can paste doctests from
3472 and '...' prompts in them. This means that you can paste doctests from
3408 files or docstrings (even if they have leading whitespace), and the
3473 files or docstrings (even if they have leading whitespace), and the
3409 code will execute correctly. You can then use '%history -tn' to see
3474 code will execute correctly. You can then use '%history -tn' to see
3410 the translated history without line numbers; this will give you the
3475 the translated history without line numbers; this will give you the
3411 input after removal of all the leading prompts and whitespace, which
3476 input after removal of all the leading prompts and whitespace, which
3412 can be pasted back into an editor.
3477 can be pasted back into an editor.
3413
3478
3414 With these features, you can switch into this mode easily whenever you
3479 With these features, you can switch into this mode easily whenever you
3415 need to do testing and changes to doctests, without having to leave
3480 need to do testing and changes to doctests, without having to leave
3416 your existing IPython session.
3481 your existing IPython session.
3417 """
3482 """
3418
3483
3419 from IPython.utils.ipstruct import Struct
3484 from IPython.utils.ipstruct import Struct
3420
3485
3421 # Shorthands
3486 # Shorthands
3422 shell = self.shell
3487 shell = self.shell
3423 oc = shell.outputcache
3488 oc = shell.outputcache
3424 meta = shell.meta
3489 meta = shell.meta
3425 # dstore is a data store kept in the instance metadata bag to track any
3490 # dstore is a data store kept in the instance metadata bag to track any
3426 # changes we make, so we can undo them later.
3491 # changes we make, so we can undo them later.
3427 dstore = meta.setdefault('doctest_mode',Struct())
3492 dstore = meta.setdefault('doctest_mode',Struct())
3428 save_dstore = dstore.setdefault
3493 save_dstore = dstore.setdefault
3429
3494
3430 # save a few values we'll need to recover later
3495 # save a few values we'll need to recover later
3431 mode = save_dstore('mode',False)
3496 mode = save_dstore('mode',False)
3432 save_dstore('rc_pprint',shell.pprint)
3497 save_dstore('rc_pprint',shell.pprint)
3433 save_dstore('xmode',shell.InteractiveTB.mode)
3498 save_dstore('xmode',shell.InteractiveTB.mode)
3434 save_dstore('rc_separate_out',shell.separate_out)
3499 save_dstore('rc_separate_out',shell.separate_out)
3435 save_dstore('rc_separate_out2',shell.separate_out2)
3500 save_dstore('rc_separate_out2',shell.separate_out2)
3436 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3501 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3437 save_dstore('rc_separate_in',shell.separate_in)
3502 save_dstore('rc_separate_in',shell.separate_in)
3438
3503
3439 if mode == False:
3504 if mode == False:
3440 # turn on
3505 # turn on
3441 oc.prompt1.p_template = '>>> '
3506 oc.prompt1.p_template = '>>> '
3442 oc.prompt2.p_template = '... '
3507 oc.prompt2.p_template = '... '
3443 oc.prompt_out.p_template = ''
3508 oc.prompt_out.p_template = ''
3444
3509
3445 # Prompt separators like plain python
3510 # Prompt separators like plain python
3446 oc.input_sep = oc.prompt1.sep = ''
3511 oc.input_sep = oc.prompt1.sep = ''
3447 oc.output_sep = ''
3512 oc.output_sep = ''
3448 oc.output_sep2 = ''
3513 oc.output_sep2 = ''
3449
3514
3450 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3515 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3451 oc.prompt_out.pad_left = False
3516 oc.prompt_out.pad_left = False
3452
3517
3453 shell.pprint = False
3518 shell.pprint = False
3454
3519
3455 shell.magic_xmode('Plain')
3520 shell.magic_xmode('Plain')
3456
3521
3457 else:
3522 else:
3458 # turn off
3523 # turn off
3459 oc.prompt1.p_template = shell.prompt_in1
3524 oc.prompt1.p_template = shell.prompt_in1
3460 oc.prompt2.p_template = shell.prompt_in2
3525 oc.prompt2.p_template = shell.prompt_in2
3461 oc.prompt_out.p_template = shell.prompt_out
3526 oc.prompt_out.p_template = shell.prompt_out
3462
3527
3463 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3528 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3464
3529
3465 oc.output_sep = dstore.rc_separate_out
3530 oc.output_sep = dstore.rc_separate_out
3466 oc.output_sep2 = dstore.rc_separate_out2
3531 oc.output_sep2 = dstore.rc_separate_out2
3467
3532
3468 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3533 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3469 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3534 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3470
3535
3471 shell.pprint = dstore.rc_pprint
3536 shell.pprint = dstore.rc_pprint
3472
3537
3473 shell.magic_xmode(dstore.xmode)
3538 shell.magic_xmode(dstore.xmode)
3474
3539
3475 # Store new mode and inform
3540 # Store new mode and inform
3476 dstore.mode = bool(1-int(mode))
3541 dstore.mode = bool(1-int(mode))
3477 print 'Doctest mode is:',
3542 print 'Doctest mode is:',
3478 print ['OFF','ON'][dstore.mode]
3543 print ['OFF','ON'][dstore.mode]
3479
3544
3480 def magic_gui(self, parameter_s=''):
3545 def magic_gui(self, parameter_s=''):
3481 """Enable or disable IPython GUI event loop integration.
3546 """Enable or disable IPython GUI event loop integration.
3482
3547
3483 %gui [-a] [GUINAME]
3548 %gui [-a] [GUINAME]
3484
3549
3485 This magic replaces IPython's threaded shells that were activated
3550 This magic replaces IPython's threaded shells that were activated
3486 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3551 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3487 can now be enabled, disabled and swtiched at runtime and keyboard
3552 can now be enabled, disabled and swtiched at runtime and keyboard
3488 interrupts should work without any problems. The following toolkits
3553 interrupts should work without any problems. The following toolkits
3489 are supported: wxPython, PyQt4, PyGTK, and Tk::
3554 are supported: wxPython, PyQt4, PyGTK, and Tk::
3490
3555
3491 %gui wx # enable wxPython event loop integration
3556 %gui wx # enable wxPython event loop integration
3492 %gui qt4|qt # enable PyQt4 event loop integration
3557 %gui qt4|qt # enable PyQt4 event loop integration
3493 %gui gtk # enable PyGTK event loop integration
3558 %gui gtk # enable PyGTK event loop integration
3494 %gui tk # enable Tk event loop integration
3559 %gui tk # enable Tk event loop integration
3495 %gui # disable all event loop integration
3560 %gui # disable all event loop integration
3496
3561
3497 WARNING: after any of these has been called you can simply create
3562 WARNING: after any of these has been called you can simply create
3498 an application object, but DO NOT start the event loop yourself, as
3563 an application object, but DO NOT start the event loop yourself, as
3499 we have already handled that.
3564 we have already handled that.
3500
3565
3501 If you want us to create an appropriate application object add the
3566 If you want us to create an appropriate application object add the
3502 "-a" flag to your command::
3567 "-a" flag to your command::
3503
3568
3504 %gui -a wx
3569 %gui -a wx
3505
3570
3506 This is highly recommended for most users.
3571 This is highly recommended for most users.
3507 """
3572 """
3508 opts, arg = self.parse_options(parameter_s,'a')
3573 opts, arg = self.parse_options(parameter_s,'a')
3509 if arg=='': arg = None
3574 if arg=='': arg = None
3510 return enable_gui(arg, 'a' in opts)
3575 return enable_gui(arg, 'a' in opts)
3511
3576
3512 def magic_load_ext(self, module_str):
3577 def magic_load_ext(self, module_str):
3513 """Load an IPython extension by its module name."""
3578 """Load an IPython extension by its module name."""
3514 return self.load_extension(module_str)
3579 return self.load_extension(module_str)
3515
3580
3516 def magic_unload_ext(self, module_str):
3581 def magic_unload_ext(self, module_str):
3517 """Unload an IPython extension by its module name."""
3582 """Unload an IPython extension by its module name."""
3518 self.unload_extension(module_str)
3583 self.unload_extension(module_str)
3519
3584
3520 def magic_reload_ext(self, module_str):
3585 def magic_reload_ext(self, module_str):
3521 """Reload an IPython extension by its module name."""
3586 """Reload an IPython extension by its module name."""
3522 self.reload_extension(module_str)
3587 self.reload_extension(module_str)
3523
3588
3524 @testdec.skip_doctest
3589 @testdec.skip_doctest
3525 def magic_install_profiles(self, s):
3590 def magic_install_profiles(self, s):
3526 """Install the default IPython profiles into the .ipython dir.
3591 """Install the default IPython profiles into the .ipython dir.
3527
3592
3528 If the default profiles have already been installed, they will not
3593 If the default profiles have already been installed, they will not
3529 be overwritten. You can force overwriting them by using the ``-o``
3594 be overwritten. You can force overwriting them by using the ``-o``
3530 option::
3595 option::
3531
3596
3532 In [1]: %install_profiles -o
3597 In [1]: %install_profiles -o
3533 """
3598 """
3534 if '-o' in s:
3599 if '-o' in s:
3535 overwrite = True
3600 overwrite = True
3536 else:
3601 else:
3537 overwrite = False
3602 overwrite = False
3538 from IPython.config import profile
3603 from IPython.config import profile
3539 profile_dir = os.path.split(profile.__file__)[0]
3604 profile_dir = os.path.split(profile.__file__)[0]
3540 ipython_dir = self.ipython_dir
3605 ipython_dir = self.ipython_dir
3541 files = os.listdir(profile_dir)
3606 files = os.listdir(profile_dir)
3542
3607
3543 to_install = []
3608 to_install = []
3544 for f in files:
3609 for f in files:
3545 if f.startswith('ipython_config'):
3610 if f.startswith('ipython_config'):
3546 src = os.path.join(profile_dir, f)
3611 src = os.path.join(profile_dir, f)
3547 dst = os.path.join(ipython_dir, f)
3612 dst = os.path.join(ipython_dir, f)
3548 if (not os.path.isfile(dst)) or overwrite:
3613 if (not os.path.isfile(dst)) or overwrite:
3549 to_install.append((f, src, dst))
3614 to_install.append((f, src, dst))
3550 if len(to_install)>0:
3615 if len(to_install)>0:
3551 print "Installing profiles to: ", ipython_dir
3616 print "Installing profiles to: ", ipython_dir
3552 for (f, src, dst) in to_install:
3617 for (f, src, dst) in to_install:
3553 shutil.copy(src, dst)
3618 shutil.copy(src, dst)
3554 print " %s" % f
3619 print " %s" % f
3555
3620
3556 def magic_install_default_config(self, s):
3621 def magic_install_default_config(self, s):
3557 """Install IPython's default config file into the .ipython dir.
3622 """Install IPython's default config file into the .ipython dir.
3558
3623
3559 If the default config file (:file:`ipython_config.py`) is already
3624 If the default config file (:file:`ipython_config.py`) is already
3560 installed, it will not be overwritten. You can force overwriting
3625 installed, it will not be overwritten. You can force overwriting
3561 by using the ``-o`` option::
3626 by using the ``-o`` option::
3562
3627
3563 In [1]: %install_default_config
3628 In [1]: %install_default_config
3564 """
3629 """
3565 if '-o' in s:
3630 if '-o' in s:
3566 overwrite = True
3631 overwrite = True
3567 else:
3632 else:
3568 overwrite = False
3633 overwrite = False
3569 from IPython.config import default
3634 from IPython.config import default
3570 config_dir = os.path.split(default.__file__)[0]
3635 config_dir = os.path.split(default.__file__)[0]
3571 ipython_dir = self.ipython_dir
3636 ipython_dir = self.ipython_dir
3572 default_config_file_name = 'ipython_config.py'
3637 default_config_file_name = 'ipython_config.py'
3573 src = os.path.join(config_dir, default_config_file_name)
3638 src = os.path.join(config_dir, default_config_file_name)
3574 dst = os.path.join(ipython_dir, default_config_file_name)
3639 dst = os.path.join(ipython_dir, default_config_file_name)
3575 if (not os.path.isfile(dst)) or overwrite:
3640 if (not os.path.isfile(dst)) or overwrite:
3576 shutil.copy(src, dst)
3641 shutil.copy(src, dst)
3577 print "Installing default config file: %s" % dst
3642 print "Installing default config file: %s" % dst
3578
3643
3579 # Pylab support: simple wrappers that activate pylab, load gui input
3644 # Pylab support: simple wrappers that activate pylab, load gui input
3580 # handling and modify slightly %run
3645 # handling and modify slightly %run
3581
3646
3582 @testdec.skip_doctest
3647 @testdec.skip_doctest
3583 def _pylab_magic_run(self, parameter_s=''):
3648 def _pylab_magic_run(self, parameter_s=''):
3584 Magic.magic_run(self, parameter_s,
3649 Magic.magic_run(self, parameter_s,
3585 runner=mpl_runner(self.shell.safe_execfile))
3650 runner=mpl_runner(self.shell.safe_execfile))
3586
3651
3587 _pylab_magic_run.__doc__ = magic_run.__doc__
3652 _pylab_magic_run.__doc__ = magic_run.__doc__
3588
3653
3589 @testdec.skip_doctest
3654 @testdec.skip_doctest
3590 def magic_pylab(self, s):
3655 def magic_pylab(self, s):
3591 """Load numpy and matplotlib to work interactively.
3656 """Load numpy and matplotlib to work interactively.
3592
3657
3593 %pylab [GUINAME]
3658 %pylab [GUINAME]
3594
3659
3595 This function lets you activate pylab (matplotlib, numpy and
3660 This function lets you activate pylab (matplotlib, numpy and
3596 interactive support) at any point during an IPython session.
3661 interactive support) at any point during an IPython session.
3597
3662
3598 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3663 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3599 pylab and mlab, as well as all names from numpy and pylab.
3664 pylab and mlab, as well as all names from numpy and pylab.
3600
3665
3601 Parameters
3666 Parameters
3602 ----------
3667 ----------
3603 guiname : optional
3668 guiname : optional
3604 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3669 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3605 'tk'). If given, the corresponding Matplotlib backend is used,
3670 'tk'). If given, the corresponding Matplotlib backend is used,
3606 otherwise matplotlib's default (which you can override in your
3671 otherwise matplotlib's default (which you can override in your
3607 matplotlib config file) is used.
3672 matplotlib config file) is used.
3608
3673
3609 Examples
3674 Examples
3610 --------
3675 --------
3611 In this case, where the MPL default is TkAgg:
3676 In this case, where the MPL default is TkAgg:
3612 In [2]: %pylab
3677 In [2]: %pylab
3613
3678
3614 Welcome to pylab, a matplotlib-based Python environment.
3679 Welcome to pylab, a matplotlib-based Python environment.
3615 Backend in use: TkAgg
3680 Backend in use: TkAgg
3616 For more information, type 'help(pylab)'.
3681 For more information, type 'help(pylab)'.
3617
3682
3618 But you can explicitly request a different backend:
3683 But you can explicitly request a different backend:
3619 In [3]: %pylab qt
3684 In [3]: %pylab qt
3620
3685
3621 Welcome to pylab, a matplotlib-based Python environment.
3686 Welcome to pylab, a matplotlib-based Python environment.
3622 Backend in use: Qt4Agg
3687 Backend in use: Qt4Agg
3623 For more information, type 'help(pylab)'.
3688 For more information, type 'help(pylab)'.
3624 """
3689 """
3625 self.shell.enable_pylab(s)
3690 self.shell.enable_pylab(s)
3626
3691
3627 def magic_tb(self, s):
3692 def magic_tb(self, s):
3628 """Print the last traceback with the currently active exception mode.
3693 """Print the last traceback with the currently active exception mode.
3629
3694
3630 See %xmode for changing exception reporting modes."""
3695 See %xmode for changing exception reporting modes."""
3631 self.shell.showtraceback()
3696 self.shell.showtraceback()
3632
3697
3633 # end Magic
3698 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now