##// END OF EJS Templates
Add init_environment(), %less, %more, %man and %clear/%cls, in zmq shell....
Fernando Perez -
Show More
@@ -1,2523 +1,2528 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.inputlist import InputList
48 from IPython.core.inputlist import InputList
49 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.inputsplitter import IPythonInputSplitter
50 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
51 from IPython.core.magic import Magic
51 from IPython.core.magic import Magic
52 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
53 from IPython.core.plugin import PluginManager
53 from IPython.core.plugin import PluginManager
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
55 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
56 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
57 from IPython.utils import io
57 from IPython.utils import io
58 from IPython.utils import pickleshare
58 from IPython.utils import pickleshare
59 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
60 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
61 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
63 from IPython.utils.process import system, getoutput
63 from IPython.utils.process import system, getoutput
64 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.strdispatch import StrDispatch
65 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.syspathcontext import prepended_to_syspath
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
66 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
68 List, Unicode, Instance, Type)
68 List, Unicode, Instance, Type)
69 from IPython.utils.warn import warn, error, fatal
69 from IPython.utils.warn import warn, error, fatal
70 import IPython.core.hooks
70 import IPython.core.hooks
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 def softspace(file, newvalue):
87 def softspace(file, newvalue):
88 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
89
89
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102
102
103 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
104
104
105 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(exceptions.Exception): pass
106
106
107 class Bunch: pass
107 class Bunch: pass
108
108
109
109
110 def get_default_colors():
110 def get_default_colors():
111 if sys.platform=='darwin':
111 if sys.platform=='darwin':
112 return "LightBG"
112 return "LightBG"
113 elif os.name=='nt':
113 elif os.name=='nt':
114 return 'Linux'
114 return 'Linux'
115 else:
115 else:
116 return 'Linux'
116 return 'Linux'
117
117
118
118
119 class SeparateStr(Str):
119 class SeparateStr(Str):
120 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
121
121
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 """
123 """
124
124
125 def validate(self, obj, value):
125 def validate(self, obj, value):
126 if value == '0': value = ''
126 if value == '0': value = ''
127 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
128 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
129
129
130 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
131 pass
131 pass
132
132
133
133
134 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
135 # Main IPython class
135 # Main IPython class
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137
137
138
138
139 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
141
141
142 _instance = None
142 _instance = None
143 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
144 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
145 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
146 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
147 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
148 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
149 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
152 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 displayhook_class = Type(DisplayHook)
154 displayhook_class = Type(DisplayHook)
155 exit_now = CBool(False)
155 exit_now = CBool(False)
156 filename = Str("<ipython console>")
156 filename = Str("<ipython console>")
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
159 logstart = CBool(False, config=True)
159 logstart = CBool(False, config=True)
160 logfile = Str('', config=True)
160 logfile = Str('', config=True)
161 logappend = Str('', config=True)
161 logappend = Str('', config=True)
162 object_info_string_level = Enum((0,1,2), default_value=0,
162 object_info_string_level = Enum((0,1,2), default_value=0,
163 config=True)
163 config=True)
164 pdb = CBool(False, config=True)
164 pdb = CBool(False, config=True)
165
165
166 pprint = CBool(True, config=True)
166 pprint = CBool(True, config=True)
167 profile = Str('', config=True)
167 profile = Str('', config=True)
168 prompt_in1 = Str('In [\\#]: ', config=True)
168 prompt_in1 = Str('In [\\#]: ', config=True)
169 prompt_in2 = Str(' .\\D.: ', config=True)
169 prompt_in2 = Str(' .\\D.: ', config=True)
170 prompt_out = Str('Out[\\#]: ', config=True)
170 prompt_out = Str('Out[\\#]: ', config=True)
171 prompts_pad_left = CBool(True, config=True)
171 prompts_pad_left = CBool(True, config=True)
172 quiet = CBool(False, config=True)
172 quiet = CBool(False, config=True)
173
173
174 # The readline stuff will eventually be moved to the terminal subclass
174 # The readline stuff will eventually be moved to the terminal subclass
175 # but for now, we can't do that as readline is welded in everywhere.
175 # but for now, we can't do that as readline is welded in everywhere.
176 readline_use = CBool(True, config=True)
176 readline_use = CBool(True, config=True)
177 readline_merge_completions = CBool(True, config=True)
177 readline_merge_completions = CBool(True, config=True)
178 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
178 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
179 readline_remove_delims = Str('-/~', config=True)
179 readline_remove_delims = Str('-/~', config=True)
180 readline_parse_and_bind = List([
180 readline_parse_and_bind = List([
181 'tab: complete',
181 'tab: complete',
182 '"\C-l": clear-screen',
182 '"\C-l": clear-screen',
183 'set show-all-if-ambiguous on',
183 'set show-all-if-ambiguous on',
184 '"\C-o": tab-insert',
184 '"\C-o": tab-insert',
185 '"\M-i": " "',
185 '"\M-i": " "',
186 '"\M-o": "\d\d\d\d"',
186 '"\M-o": "\d\d\d\d"',
187 '"\M-I": "\d\d\d\d"',
187 '"\M-I": "\d\d\d\d"',
188 '"\C-r": reverse-search-history',
188 '"\C-r": reverse-search-history',
189 '"\C-s": forward-search-history',
189 '"\C-s": forward-search-history',
190 '"\C-p": history-search-backward',
190 '"\C-p": history-search-backward',
191 '"\C-n": history-search-forward',
191 '"\C-n": history-search-forward',
192 '"\e[A": history-search-backward',
192 '"\e[A": history-search-backward',
193 '"\e[B": history-search-forward',
193 '"\e[B": history-search-forward',
194 '"\C-k": kill-line',
194 '"\C-k": kill-line',
195 '"\C-u": unix-line-discard',
195 '"\C-u": unix-line-discard',
196 ], allow_none=False, config=True)
196 ], allow_none=False, config=True)
197
197
198 # TODO: this part of prompt management should be moved to the frontends.
198 # TODO: this part of prompt management should be moved to the frontends.
199 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
199 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
200 separate_in = SeparateStr('\n', config=True)
200 separate_in = SeparateStr('\n', config=True)
201 separate_out = SeparateStr('', config=True)
201 separate_out = SeparateStr('', config=True)
202 separate_out2 = SeparateStr('', config=True)
202 separate_out2 = SeparateStr('', config=True)
203 wildcards_case_sensitive = CBool(True, config=True)
203 wildcards_case_sensitive = CBool(True, config=True)
204 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
204 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
205 default_value='Context', config=True)
205 default_value='Context', config=True)
206
206
207 # Subcomponents of InteractiveShell
207 # Subcomponents of InteractiveShell
208 alias_manager = Instance('IPython.core.alias.AliasManager')
208 alias_manager = Instance('IPython.core.alias.AliasManager')
209 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
209 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
210 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
210 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
211 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
211 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
212 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
212 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
213 plugin_manager = Instance('IPython.core.plugin.PluginManager')
213 plugin_manager = Instance('IPython.core.plugin.PluginManager')
214 payload_manager = Instance('IPython.core.payload.PayloadManager')
214 payload_manager = Instance('IPython.core.payload.PayloadManager')
215
215
216 # Private interface
216 # Private interface
217 _post_execute = set()
217 _post_execute = set()
218
218
219 def __init__(self, config=None, ipython_dir=None,
219 def __init__(self, config=None, ipython_dir=None,
220 user_ns=None, user_global_ns=None,
220 user_ns=None, user_global_ns=None,
221 custom_exceptions=((), None)):
221 custom_exceptions=((), None)):
222
222
223 # This is where traits with a config_key argument are updated
223 # This is where traits with a config_key argument are updated
224 # from the values on config.
224 # from the values on config.
225 super(InteractiveShell, self).__init__(config=config)
225 super(InteractiveShell, self).__init__(config=config)
226
226
227 # These are relatively independent and stateless
227 # These are relatively independent and stateless
228 self.init_ipython_dir(ipython_dir)
228 self.init_ipython_dir(ipython_dir)
229 self.init_instance_attrs()
229 self.init_instance_attrs()
230 self.init_environment()
230
231
231 # Create namespaces (user_ns, user_global_ns, etc.)
232 # Create namespaces (user_ns, user_global_ns, etc.)
232 self.init_create_namespaces(user_ns, user_global_ns)
233 self.init_create_namespaces(user_ns, user_global_ns)
233 # This has to be done after init_create_namespaces because it uses
234 # This has to be done after init_create_namespaces because it uses
234 # something in self.user_ns, but before init_sys_modules, which
235 # something in self.user_ns, but before init_sys_modules, which
235 # is the first thing to modify sys.
236 # is the first thing to modify sys.
236 # TODO: When we override sys.stdout and sys.stderr before this class
237 # TODO: When we override sys.stdout and sys.stderr before this class
237 # is created, we are saving the overridden ones here. Not sure if this
238 # is created, we are saving the overridden ones here. Not sure if this
238 # is what we want to do.
239 # is what we want to do.
239 self.save_sys_module_state()
240 self.save_sys_module_state()
240 self.init_sys_modules()
241 self.init_sys_modules()
241
242
242 self.init_history()
243 self.init_history()
243 self.init_encoding()
244 self.init_encoding()
244 self.init_prefilter()
245 self.init_prefilter()
245
246
246 Magic.__init__(self, self)
247 Magic.__init__(self, self)
247
248
248 self.init_syntax_highlighting()
249 self.init_syntax_highlighting()
249 self.init_hooks()
250 self.init_hooks()
250 self.init_pushd_popd_magic()
251 self.init_pushd_popd_magic()
251 # self.init_traceback_handlers use to be here, but we moved it below
252 # self.init_traceback_handlers use to be here, but we moved it below
252 # because it and init_io have to come after init_readline.
253 # because it and init_io have to come after init_readline.
253 self.init_user_ns()
254 self.init_user_ns()
254 self.init_logger()
255 self.init_logger()
255 self.init_alias()
256 self.init_alias()
256 self.init_builtins()
257 self.init_builtins()
257
258
258 # pre_config_initialization
259 # pre_config_initialization
259 self.init_shadow_hist()
260 self.init_shadow_hist()
260
261
261 # The next section should contain everything that was in ipmaker.
262 # The next section should contain everything that was in ipmaker.
262 self.init_logstart()
263 self.init_logstart()
263
264
264 # The following was in post_config_initialization
265 # The following was in post_config_initialization
265 self.init_inspector()
266 self.init_inspector()
266 # init_readline() must come before init_io(), because init_io uses
267 # init_readline() must come before init_io(), because init_io uses
267 # readline related things.
268 # readline related things.
268 self.init_readline()
269 self.init_readline()
269 # init_completer must come after init_readline, because it needs to
270 # init_completer must come after init_readline, because it needs to
270 # know whether readline is present or not system-wide to configure the
271 # know whether readline is present or not system-wide to configure the
271 # completers, since the completion machinery can now operate
272 # completers, since the completion machinery can now operate
272 # independently of readline (e.g. over the network)
273 # independently of readline (e.g. over the network)
273 self.init_completer()
274 self.init_completer()
274 # TODO: init_io() needs to happen before init_traceback handlers
275 # TODO: init_io() needs to happen before init_traceback handlers
275 # because the traceback handlers hardcode the stdout/stderr streams.
276 # because the traceback handlers hardcode the stdout/stderr streams.
276 # This logic in in debugger.Pdb and should eventually be changed.
277 # This logic in in debugger.Pdb and should eventually be changed.
277 self.init_io()
278 self.init_io()
278 self.init_traceback_handlers(custom_exceptions)
279 self.init_traceback_handlers(custom_exceptions)
279 self.init_prompts()
280 self.init_prompts()
280 self.init_displayhook()
281 self.init_displayhook()
281 self.init_reload_doctest()
282 self.init_reload_doctest()
282 self.init_magics()
283 self.init_magics()
283 self.init_pdb()
284 self.init_pdb()
284 self.init_extension_manager()
285 self.init_extension_manager()
285 self.init_plugin_manager()
286 self.init_plugin_manager()
286 self.init_payload()
287 self.init_payload()
287 self.hooks.late_startup_hook()
288 self.hooks.late_startup_hook()
288 atexit.register(self.atexit_operations)
289 atexit.register(self.atexit_operations)
289
290
290 @classmethod
291 @classmethod
291 def instance(cls, *args, **kwargs):
292 def instance(cls, *args, **kwargs):
292 """Returns a global InteractiveShell instance."""
293 """Returns a global InteractiveShell instance."""
293 if cls._instance is None:
294 if cls._instance is None:
294 inst = cls(*args, **kwargs)
295 inst = cls(*args, **kwargs)
295 # Now make sure that the instance will also be returned by
296 # Now make sure that the instance will also be returned by
296 # the subclasses instance attribute.
297 # the subclasses instance attribute.
297 for subclass in cls.mro():
298 for subclass in cls.mro():
298 if issubclass(cls, subclass) and \
299 if issubclass(cls, subclass) and \
299 issubclass(subclass, InteractiveShell):
300 issubclass(subclass, InteractiveShell):
300 subclass._instance = inst
301 subclass._instance = inst
301 else:
302 else:
302 break
303 break
303 if isinstance(cls._instance, cls):
304 if isinstance(cls._instance, cls):
304 return cls._instance
305 return cls._instance
305 else:
306 else:
306 raise MultipleInstanceError(
307 raise MultipleInstanceError(
307 'Multiple incompatible subclass instances of '
308 'Multiple incompatible subclass instances of '
308 'InteractiveShell are being created.'
309 'InteractiveShell are being created.'
309 )
310 )
310
311
311 @classmethod
312 @classmethod
312 def initialized(cls):
313 def initialized(cls):
313 return hasattr(cls, "_instance")
314 return hasattr(cls, "_instance")
314
315
315 def get_ipython(self):
316 def get_ipython(self):
316 """Return the currently running IPython instance."""
317 """Return the currently running IPython instance."""
317 return self
318 return self
318
319
319 #-------------------------------------------------------------------------
320 #-------------------------------------------------------------------------
320 # Trait changed handlers
321 # Trait changed handlers
321 #-------------------------------------------------------------------------
322 #-------------------------------------------------------------------------
322
323
323 def _ipython_dir_changed(self, name, new):
324 def _ipython_dir_changed(self, name, new):
324 if not os.path.isdir(new):
325 if not os.path.isdir(new):
325 os.makedirs(new, mode = 0777)
326 os.makedirs(new, mode = 0777)
326
327
327 def set_autoindent(self,value=None):
328 def set_autoindent(self,value=None):
328 """Set the autoindent flag, checking for readline support.
329 """Set the autoindent flag, checking for readline support.
329
330
330 If called with no arguments, it acts as a toggle."""
331 If called with no arguments, it acts as a toggle."""
331
332
332 if not self.has_readline:
333 if not self.has_readline:
333 if os.name == 'posix':
334 if os.name == 'posix':
334 warn("The auto-indent feature requires the readline library")
335 warn("The auto-indent feature requires the readline library")
335 self.autoindent = 0
336 self.autoindent = 0
336 return
337 return
337 if value is None:
338 if value is None:
338 self.autoindent = not self.autoindent
339 self.autoindent = not self.autoindent
339 else:
340 else:
340 self.autoindent = value
341 self.autoindent = value
341
342
342 #-------------------------------------------------------------------------
343 #-------------------------------------------------------------------------
343 # init_* methods called by __init__
344 # init_* methods called by __init__
344 #-------------------------------------------------------------------------
345 #-------------------------------------------------------------------------
345
346
346 def init_ipython_dir(self, ipython_dir):
347 def init_ipython_dir(self, ipython_dir):
347 if ipython_dir is not None:
348 if ipython_dir is not None:
348 self.ipython_dir = ipython_dir
349 self.ipython_dir = ipython_dir
349 self.config.Global.ipython_dir = self.ipython_dir
350 self.config.Global.ipython_dir = self.ipython_dir
350 return
351 return
351
352
352 if hasattr(self.config.Global, 'ipython_dir'):
353 if hasattr(self.config.Global, 'ipython_dir'):
353 self.ipython_dir = self.config.Global.ipython_dir
354 self.ipython_dir = self.config.Global.ipython_dir
354 else:
355 else:
355 self.ipython_dir = get_ipython_dir()
356 self.ipython_dir = get_ipython_dir()
356
357
357 # All children can just read this
358 # All children can just read this
358 self.config.Global.ipython_dir = self.ipython_dir
359 self.config.Global.ipython_dir = self.ipython_dir
359
360
360 def init_instance_attrs(self):
361 def init_instance_attrs(self):
361 self.more = False
362 self.more = False
362
363
363 # command compiler
364 # command compiler
364 self.compile = codeop.CommandCompiler()
365 self.compile = codeop.CommandCompiler()
365
366
366 # User input buffer
367 # User input buffer
367 self.buffer = []
368 self.buffer = []
368
369
369 # Make an empty namespace, which extension writers can rely on both
370 # Make an empty namespace, which extension writers can rely on both
370 # existing and NEVER being used by ipython itself. This gives them a
371 # existing and NEVER being used by ipython itself. This gives them a
371 # convenient location for storing additional information and state
372 # convenient location for storing additional information and state
372 # their extensions may require, without fear of collisions with other
373 # their extensions may require, without fear of collisions with other
373 # ipython names that may develop later.
374 # ipython names that may develop later.
374 self.meta = Struct()
375 self.meta = Struct()
375
376
376 # Object variable to store code object waiting execution. This is
377 # Object variable to store code object waiting execution. This is
377 # used mainly by the multithreaded shells, but it can come in handy in
378 # used mainly by the multithreaded shells, but it can come in handy in
378 # other situations. No need to use a Queue here, since it's a single
379 # other situations. No need to use a Queue here, since it's a single
379 # item which gets cleared once run.
380 # item which gets cleared once run.
380 self.code_to_run = None
381 self.code_to_run = None
381
382
382 # Temporary files used for various purposes. Deleted at exit.
383 # Temporary files used for various purposes. Deleted at exit.
383 self.tempfiles = []
384 self.tempfiles = []
384
385
385 # Keep track of readline usage (later set by init_readline)
386 # Keep track of readline usage (later set by init_readline)
386 self.has_readline = False
387 self.has_readline = False
387
388
388 # keep track of where we started running (mainly for crash post-mortem)
389 # keep track of where we started running (mainly for crash post-mortem)
389 # This is not being used anywhere currently.
390 # This is not being used anywhere currently.
390 self.starting_dir = os.getcwd()
391 self.starting_dir = os.getcwd()
391
392
392 # Indentation management
393 # Indentation management
393 self.indent_current_nsp = 0
394 self.indent_current_nsp = 0
394
395
395 # Input splitter, to split entire cells of input into either individual
396 # Input splitter, to split entire cells of input into either individual
396 # interactive statements or whole blocks.
397 # interactive statements or whole blocks.
397 self.input_splitter = IPythonInputSplitter()
398 self.input_splitter = IPythonInputSplitter()
398
399
400 def init_environment(self):
401 """Any changes we need to make to the user's environment."""
402 pass
403
399 def init_encoding(self):
404 def init_encoding(self):
400 # Get system encoding at startup time. Certain terminals (like Emacs
405 # Get system encoding at startup time. Certain terminals (like Emacs
401 # under Win32 have it set to None, and we need to have a known valid
406 # under Win32 have it set to None, and we need to have a known valid
402 # encoding to use in the raw_input() method
407 # encoding to use in the raw_input() method
403 try:
408 try:
404 self.stdin_encoding = sys.stdin.encoding or 'ascii'
409 self.stdin_encoding = sys.stdin.encoding or 'ascii'
405 except AttributeError:
410 except AttributeError:
406 self.stdin_encoding = 'ascii'
411 self.stdin_encoding = 'ascii'
407
412
408 def init_syntax_highlighting(self):
413 def init_syntax_highlighting(self):
409 # Python source parser/formatter for syntax highlighting
414 # Python source parser/formatter for syntax highlighting
410 pyformat = PyColorize.Parser().format
415 pyformat = PyColorize.Parser().format
411 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
416 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
412
417
413 def init_pushd_popd_magic(self):
418 def init_pushd_popd_magic(self):
414 # for pushd/popd management
419 # for pushd/popd management
415 try:
420 try:
416 self.home_dir = get_home_dir()
421 self.home_dir = get_home_dir()
417 except HomeDirError, msg:
422 except HomeDirError, msg:
418 fatal(msg)
423 fatal(msg)
419
424
420 self.dir_stack = []
425 self.dir_stack = []
421
426
422 def init_logger(self):
427 def init_logger(self):
423 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
428 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
424 # local shortcut, this is used a LOT
429 # local shortcut, this is used a LOT
425 self.log = self.logger.log
430 self.log = self.logger.log
426
431
427 def init_logstart(self):
432 def init_logstart(self):
428 if self.logappend:
433 if self.logappend:
429 self.magic_logstart(self.logappend + ' append')
434 self.magic_logstart(self.logappend + ' append')
430 elif self.logfile:
435 elif self.logfile:
431 self.magic_logstart(self.logfile)
436 self.magic_logstart(self.logfile)
432 elif self.logstart:
437 elif self.logstart:
433 self.magic_logstart()
438 self.magic_logstart()
434
439
435 def init_builtins(self):
440 def init_builtins(self):
436 self.builtin_trap = BuiltinTrap(shell=self)
441 self.builtin_trap = BuiltinTrap(shell=self)
437
442
438 def init_inspector(self):
443 def init_inspector(self):
439 # Object inspector
444 # Object inspector
440 self.inspector = oinspect.Inspector(oinspect.InspectColors,
445 self.inspector = oinspect.Inspector(oinspect.InspectColors,
441 PyColorize.ANSICodeColors,
446 PyColorize.ANSICodeColors,
442 'NoColor',
447 'NoColor',
443 self.object_info_string_level)
448 self.object_info_string_level)
444
449
445 def init_io(self):
450 def init_io(self):
446 # This will just use sys.stdout and sys.stderr. If you want to
451 # This will just use sys.stdout and sys.stderr. If you want to
447 # override sys.stdout and sys.stderr themselves, you need to do that
452 # override sys.stdout and sys.stderr themselves, you need to do that
448 # *before* instantiating this class, because Term holds onto
453 # *before* instantiating this class, because Term holds onto
449 # references to the underlying streams.
454 # references to the underlying streams.
450 if sys.platform == 'win32' and self.has_readline:
455 if sys.platform == 'win32' and self.has_readline:
451 Term = io.IOTerm(cout=self.readline._outputfile,
456 Term = io.IOTerm(cout=self.readline._outputfile,
452 cerr=self.readline._outputfile)
457 cerr=self.readline._outputfile)
453 else:
458 else:
454 Term = io.IOTerm()
459 Term = io.IOTerm()
455 io.Term = Term
460 io.Term = Term
456
461
457 def init_prompts(self):
462 def init_prompts(self):
458 # TODO: This is a pass for now because the prompts are managed inside
463 # TODO: This is a pass for now because the prompts are managed inside
459 # the DisplayHook. Once there is a separate prompt manager, this
464 # the DisplayHook. Once there is a separate prompt manager, this
460 # will initialize that object and all prompt related information.
465 # will initialize that object and all prompt related information.
461 pass
466 pass
462
467
463 def init_displayhook(self):
468 def init_displayhook(self):
464 # Initialize displayhook, set in/out prompts and printing system
469 # Initialize displayhook, set in/out prompts and printing system
465 self.displayhook = self.displayhook_class(
470 self.displayhook = self.displayhook_class(
466 shell=self,
471 shell=self,
467 cache_size=self.cache_size,
472 cache_size=self.cache_size,
468 input_sep = self.separate_in,
473 input_sep = self.separate_in,
469 output_sep = self.separate_out,
474 output_sep = self.separate_out,
470 output_sep2 = self.separate_out2,
475 output_sep2 = self.separate_out2,
471 ps1 = self.prompt_in1,
476 ps1 = self.prompt_in1,
472 ps2 = self.prompt_in2,
477 ps2 = self.prompt_in2,
473 ps_out = self.prompt_out,
478 ps_out = self.prompt_out,
474 pad_left = self.prompts_pad_left
479 pad_left = self.prompts_pad_left
475 )
480 )
476 # This is a context manager that installs/revmoes the displayhook at
481 # This is a context manager that installs/revmoes the displayhook at
477 # the appropriate time.
482 # the appropriate time.
478 self.display_trap = DisplayTrap(hook=self.displayhook)
483 self.display_trap = DisplayTrap(hook=self.displayhook)
479
484
480 def init_reload_doctest(self):
485 def init_reload_doctest(self):
481 # Do a proper resetting of doctest, including the necessary displayhook
486 # Do a proper resetting of doctest, including the necessary displayhook
482 # monkeypatching
487 # monkeypatching
483 try:
488 try:
484 doctest_reload()
489 doctest_reload()
485 except ImportError:
490 except ImportError:
486 warn("doctest module does not exist.")
491 warn("doctest module does not exist.")
487
492
488 #-------------------------------------------------------------------------
493 #-------------------------------------------------------------------------
489 # Things related to injections into the sys module
494 # Things related to injections into the sys module
490 #-------------------------------------------------------------------------
495 #-------------------------------------------------------------------------
491
496
492 def save_sys_module_state(self):
497 def save_sys_module_state(self):
493 """Save the state of hooks in the sys module.
498 """Save the state of hooks in the sys module.
494
499
495 This has to be called after self.user_ns is created.
500 This has to be called after self.user_ns is created.
496 """
501 """
497 self._orig_sys_module_state = {}
502 self._orig_sys_module_state = {}
498 self._orig_sys_module_state['stdin'] = sys.stdin
503 self._orig_sys_module_state['stdin'] = sys.stdin
499 self._orig_sys_module_state['stdout'] = sys.stdout
504 self._orig_sys_module_state['stdout'] = sys.stdout
500 self._orig_sys_module_state['stderr'] = sys.stderr
505 self._orig_sys_module_state['stderr'] = sys.stderr
501 self._orig_sys_module_state['excepthook'] = sys.excepthook
506 self._orig_sys_module_state['excepthook'] = sys.excepthook
502 try:
507 try:
503 self._orig_sys_modules_main_name = self.user_ns['__name__']
508 self._orig_sys_modules_main_name = self.user_ns['__name__']
504 except KeyError:
509 except KeyError:
505 pass
510 pass
506
511
507 def restore_sys_module_state(self):
512 def restore_sys_module_state(self):
508 """Restore the state of the sys module."""
513 """Restore the state of the sys module."""
509 try:
514 try:
510 for k, v in self._orig_sys_module_state.items():
515 for k, v in self._orig_sys_module_state.items():
511 setattr(sys, k, v)
516 setattr(sys, k, v)
512 except AttributeError:
517 except AttributeError:
513 pass
518 pass
514 # Reset what what done in self.init_sys_modules
519 # Reset what what done in self.init_sys_modules
515 try:
520 try:
516 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
521 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
517 except (AttributeError, KeyError):
522 except (AttributeError, KeyError):
518 pass
523 pass
519
524
520 #-------------------------------------------------------------------------
525 #-------------------------------------------------------------------------
521 # Things related to hooks
526 # Things related to hooks
522 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
523
528
524 def init_hooks(self):
529 def init_hooks(self):
525 # hooks holds pointers used for user-side customizations
530 # hooks holds pointers used for user-side customizations
526 self.hooks = Struct()
531 self.hooks = Struct()
527
532
528 self.strdispatchers = {}
533 self.strdispatchers = {}
529
534
530 # Set all default hooks, defined in the IPython.hooks module.
535 # Set all default hooks, defined in the IPython.hooks module.
531 hooks = IPython.core.hooks
536 hooks = IPython.core.hooks
532 for hook_name in hooks.__all__:
537 for hook_name in hooks.__all__:
533 # default hooks have priority 100, i.e. low; user hooks should have
538 # default hooks have priority 100, i.e. low; user hooks should have
534 # 0-100 priority
539 # 0-100 priority
535 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
540 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
536
541
537 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
542 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
538 """set_hook(name,hook) -> sets an internal IPython hook.
543 """set_hook(name,hook) -> sets an internal IPython hook.
539
544
540 IPython exposes some of its internal API as user-modifiable hooks. By
545 IPython exposes some of its internal API as user-modifiable hooks. By
541 adding your function to one of these hooks, you can modify IPython's
546 adding your function to one of these hooks, you can modify IPython's
542 behavior to call at runtime your own routines."""
547 behavior to call at runtime your own routines."""
543
548
544 # At some point in the future, this should validate the hook before it
549 # At some point in the future, this should validate the hook before it
545 # accepts it. Probably at least check that the hook takes the number
550 # accepts it. Probably at least check that the hook takes the number
546 # of args it's supposed to.
551 # of args it's supposed to.
547
552
548 f = new.instancemethod(hook,self,self.__class__)
553 f = new.instancemethod(hook,self,self.__class__)
549
554
550 # check if the hook is for strdispatcher first
555 # check if the hook is for strdispatcher first
551 if str_key is not None:
556 if str_key is not None:
552 sdp = self.strdispatchers.get(name, StrDispatch())
557 sdp = self.strdispatchers.get(name, StrDispatch())
553 sdp.add_s(str_key, f, priority )
558 sdp.add_s(str_key, f, priority )
554 self.strdispatchers[name] = sdp
559 self.strdispatchers[name] = sdp
555 return
560 return
556 if re_key is not None:
561 if re_key is not None:
557 sdp = self.strdispatchers.get(name, StrDispatch())
562 sdp = self.strdispatchers.get(name, StrDispatch())
558 sdp.add_re(re.compile(re_key), f, priority )
563 sdp.add_re(re.compile(re_key), f, priority )
559 self.strdispatchers[name] = sdp
564 self.strdispatchers[name] = sdp
560 return
565 return
561
566
562 dp = getattr(self.hooks, name, None)
567 dp = getattr(self.hooks, name, None)
563 if name not in IPython.core.hooks.__all__:
568 if name not in IPython.core.hooks.__all__:
564 print "Warning! Hook '%s' is not one of %s" % \
569 print "Warning! Hook '%s' is not one of %s" % \
565 (name, IPython.core.hooks.__all__ )
570 (name, IPython.core.hooks.__all__ )
566 if not dp:
571 if not dp:
567 dp = IPython.core.hooks.CommandChainDispatcher()
572 dp = IPython.core.hooks.CommandChainDispatcher()
568
573
569 try:
574 try:
570 dp.add(f,priority)
575 dp.add(f,priority)
571 except AttributeError:
576 except AttributeError:
572 # it was not commandchain, plain old func - replace
577 # it was not commandchain, plain old func - replace
573 dp = f
578 dp = f
574
579
575 setattr(self.hooks,name, dp)
580 setattr(self.hooks,name, dp)
576
581
577 def register_post_execute(self, func):
582 def register_post_execute(self, func):
578 """Register a function for calling after code execution.
583 """Register a function for calling after code execution.
579 """
584 """
580 if not callable(func):
585 if not callable(func):
581 raise ValueError('argument %s must be callable' % func)
586 raise ValueError('argument %s must be callable' % func)
582 self._post_execute.add(func)
587 self._post_execute.add(func)
583
588
584 #-------------------------------------------------------------------------
589 #-------------------------------------------------------------------------
585 # Things related to the "main" module
590 # Things related to the "main" module
586 #-------------------------------------------------------------------------
591 #-------------------------------------------------------------------------
587
592
588 def new_main_mod(self,ns=None):
593 def new_main_mod(self,ns=None):
589 """Return a new 'main' module object for user code execution.
594 """Return a new 'main' module object for user code execution.
590 """
595 """
591 main_mod = self._user_main_module
596 main_mod = self._user_main_module
592 init_fakemod_dict(main_mod,ns)
597 init_fakemod_dict(main_mod,ns)
593 return main_mod
598 return main_mod
594
599
595 def cache_main_mod(self,ns,fname):
600 def cache_main_mod(self,ns,fname):
596 """Cache a main module's namespace.
601 """Cache a main module's namespace.
597
602
598 When scripts are executed via %run, we must keep a reference to the
603 When scripts are executed via %run, we must keep a reference to the
599 namespace of their __main__ module (a FakeModule instance) around so
604 namespace of their __main__ module (a FakeModule instance) around so
600 that Python doesn't clear it, rendering objects defined therein
605 that Python doesn't clear it, rendering objects defined therein
601 useless.
606 useless.
602
607
603 This method keeps said reference in a private dict, keyed by the
608 This method keeps said reference in a private dict, keyed by the
604 absolute path of the module object (which corresponds to the script
609 absolute path of the module object (which corresponds to the script
605 path). This way, for multiple executions of the same script we only
610 path). This way, for multiple executions of the same script we only
606 keep one copy of the namespace (the last one), thus preventing memory
611 keep one copy of the namespace (the last one), thus preventing memory
607 leaks from old references while allowing the objects from the last
612 leaks from old references while allowing the objects from the last
608 execution to be accessible.
613 execution to be accessible.
609
614
610 Note: we can not allow the actual FakeModule instances to be deleted,
615 Note: we can not allow the actual FakeModule instances to be deleted,
611 because of how Python tears down modules (it hard-sets all their
616 because of how Python tears down modules (it hard-sets all their
612 references to None without regard for reference counts). This method
617 references to None without regard for reference counts). This method
613 must therefore make a *copy* of the given namespace, to allow the
618 must therefore make a *copy* of the given namespace, to allow the
614 original module's __dict__ to be cleared and reused.
619 original module's __dict__ to be cleared and reused.
615
620
616
621
617 Parameters
622 Parameters
618 ----------
623 ----------
619 ns : a namespace (a dict, typically)
624 ns : a namespace (a dict, typically)
620
625
621 fname : str
626 fname : str
622 Filename associated with the namespace.
627 Filename associated with the namespace.
623
628
624 Examples
629 Examples
625 --------
630 --------
626
631
627 In [10]: import IPython
632 In [10]: import IPython
628
633
629 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
634 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
630
635
631 In [12]: IPython.__file__ in _ip._main_ns_cache
636 In [12]: IPython.__file__ in _ip._main_ns_cache
632 Out[12]: True
637 Out[12]: True
633 """
638 """
634 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
639 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
635
640
636 def clear_main_mod_cache(self):
641 def clear_main_mod_cache(self):
637 """Clear the cache of main modules.
642 """Clear the cache of main modules.
638
643
639 Mainly for use by utilities like %reset.
644 Mainly for use by utilities like %reset.
640
645
641 Examples
646 Examples
642 --------
647 --------
643
648
644 In [15]: import IPython
649 In [15]: import IPython
645
650
646 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
651 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
647
652
648 In [17]: len(_ip._main_ns_cache) > 0
653 In [17]: len(_ip._main_ns_cache) > 0
649 Out[17]: True
654 Out[17]: True
650
655
651 In [18]: _ip.clear_main_mod_cache()
656 In [18]: _ip.clear_main_mod_cache()
652
657
653 In [19]: len(_ip._main_ns_cache) == 0
658 In [19]: len(_ip._main_ns_cache) == 0
654 Out[19]: True
659 Out[19]: True
655 """
660 """
656 self._main_ns_cache.clear()
661 self._main_ns_cache.clear()
657
662
658 #-------------------------------------------------------------------------
663 #-------------------------------------------------------------------------
659 # Things related to debugging
664 # Things related to debugging
660 #-------------------------------------------------------------------------
665 #-------------------------------------------------------------------------
661
666
662 def init_pdb(self):
667 def init_pdb(self):
663 # Set calling of pdb on exceptions
668 # Set calling of pdb on exceptions
664 # self.call_pdb is a property
669 # self.call_pdb is a property
665 self.call_pdb = self.pdb
670 self.call_pdb = self.pdb
666
671
667 def _get_call_pdb(self):
672 def _get_call_pdb(self):
668 return self._call_pdb
673 return self._call_pdb
669
674
670 def _set_call_pdb(self,val):
675 def _set_call_pdb(self,val):
671
676
672 if val not in (0,1,False,True):
677 if val not in (0,1,False,True):
673 raise ValueError,'new call_pdb value must be boolean'
678 raise ValueError,'new call_pdb value must be boolean'
674
679
675 # store value in instance
680 # store value in instance
676 self._call_pdb = val
681 self._call_pdb = val
677
682
678 # notify the actual exception handlers
683 # notify the actual exception handlers
679 self.InteractiveTB.call_pdb = val
684 self.InteractiveTB.call_pdb = val
680
685
681 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
686 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
682 'Control auto-activation of pdb at exceptions')
687 'Control auto-activation of pdb at exceptions')
683
688
684 def debugger(self,force=False):
689 def debugger(self,force=False):
685 """Call the pydb/pdb debugger.
690 """Call the pydb/pdb debugger.
686
691
687 Keywords:
692 Keywords:
688
693
689 - force(False): by default, this routine checks the instance call_pdb
694 - force(False): by default, this routine checks the instance call_pdb
690 flag and does not actually invoke the debugger if the flag is false.
695 flag and does not actually invoke the debugger if the flag is false.
691 The 'force' option forces the debugger to activate even if the flag
696 The 'force' option forces the debugger to activate even if the flag
692 is false.
697 is false.
693 """
698 """
694
699
695 if not (force or self.call_pdb):
700 if not (force or self.call_pdb):
696 return
701 return
697
702
698 if not hasattr(sys,'last_traceback'):
703 if not hasattr(sys,'last_traceback'):
699 error('No traceback has been produced, nothing to debug.')
704 error('No traceback has been produced, nothing to debug.')
700 return
705 return
701
706
702 # use pydb if available
707 # use pydb if available
703 if debugger.has_pydb:
708 if debugger.has_pydb:
704 from pydb import pm
709 from pydb import pm
705 else:
710 else:
706 # fallback to our internal debugger
711 # fallback to our internal debugger
707 pm = lambda : self.InteractiveTB.debugger(force=True)
712 pm = lambda : self.InteractiveTB.debugger(force=True)
708 self.history_saving_wrapper(pm)()
713 self.history_saving_wrapper(pm)()
709
714
710 #-------------------------------------------------------------------------
715 #-------------------------------------------------------------------------
711 # Things related to IPython's various namespaces
716 # Things related to IPython's various namespaces
712 #-------------------------------------------------------------------------
717 #-------------------------------------------------------------------------
713
718
714 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
719 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
715 # Create the namespace where the user will operate. user_ns is
720 # Create the namespace where the user will operate. user_ns is
716 # normally the only one used, and it is passed to the exec calls as
721 # normally the only one used, and it is passed to the exec calls as
717 # the locals argument. But we do carry a user_global_ns namespace
722 # the locals argument. But we do carry a user_global_ns namespace
718 # given as the exec 'globals' argument, This is useful in embedding
723 # given as the exec 'globals' argument, This is useful in embedding
719 # situations where the ipython shell opens in a context where the
724 # situations where the ipython shell opens in a context where the
720 # distinction between locals and globals is meaningful. For
725 # distinction between locals and globals is meaningful. For
721 # non-embedded contexts, it is just the same object as the user_ns dict.
726 # non-embedded contexts, it is just the same object as the user_ns dict.
722
727
723 # FIXME. For some strange reason, __builtins__ is showing up at user
728 # FIXME. For some strange reason, __builtins__ is showing up at user
724 # level as a dict instead of a module. This is a manual fix, but I
729 # level as a dict instead of a module. This is a manual fix, but I
725 # should really track down where the problem is coming from. Alex
730 # should really track down where the problem is coming from. Alex
726 # Schmolck reported this problem first.
731 # Schmolck reported this problem first.
727
732
728 # A useful post by Alex Martelli on this topic:
733 # A useful post by Alex Martelli on this topic:
729 # Re: inconsistent value from __builtins__
734 # Re: inconsistent value from __builtins__
730 # Von: Alex Martelli <aleaxit@yahoo.com>
735 # Von: Alex Martelli <aleaxit@yahoo.com>
731 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
736 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
732 # Gruppen: comp.lang.python
737 # Gruppen: comp.lang.python
733
738
734 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
739 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
735 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
740 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
736 # > <type 'dict'>
741 # > <type 'dict'>
737 # > >>> print type(__builtins__)
742 # > >>> print type(__builtins__)
738 # > <type 'module'>
743 # > <type 'module'>
739 # > Is this difference in return value intentional?
744 # > Is this difference in return value intentional?
740
745
741 # Well, it's documented that '__builtins__' can be either a dictionary
746 # Well, it's documented that '__builtins__' can be either a dictionary
742 # or a module, and it's been that way for a long time. Whether it's
747 # or a module, and it's been that way for a long time. Whether it's
743 # intentional (or sensible), I don't know. In any case, the idea is
748 # intentional (or sensible), I don't know. In any case, the idea is
744 # that if you need to access the built-in namespace directly, you
749 # that if you need to access the built-in namespace directly, you
745 # should start with "import __builtin__" (note, no 's') which will
750 # should start with "import __builtin__" (note, no 's') which will
746 # definitely give you a module. Yeah, it's somewhat confusing:-(.
751 # definitely give you a module. Yeah, it's somewhat confusing:-(.
747
752
748 # These routines return properly built dicts as needed by the rest of
753 # These routines return properly built dicts as needed by the rest of
749 # the code, and can also be used by extension writers to generate
754 # the code, and can also be used by extension writers to generate
750 # properly initialized namespaces.
755 # properly initialized namespaces.
751 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
756 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
752 user_global_ns)
757 user_global_ns)
753
758
754 # Assign namespaces
759 # Assign namespaces
755 # This is the namespace where all normal user variables live
760 # This is the namespace where all normal user variables live
756 self.user_ns = user_ns
761 self.user_ns = user_ns
757 self.user_global_ns = user_global_ns
762 self.user_global_ns = user_global_ns
758
763
759 # An auxiliary namespace that checks what parts of the user_ns were
764 # An auxiliary namespace that checks what parts of the user_ns were
760 # loaded at startup, so we can list later only variables defined in
765 # loaded at startup, so we can list later only variables defined in
761 # actual interactive use. Since it is always a subset of user_ns, it
766 # actual interactive use. Since it is always a subset of user_ns, it
762 # doesn't need to be separately tracked in the ns_table.
767 # doesn't need to be separately tracked in the ns_table.
763 self.user_ns_hidden = {}
768 self.user_ns_hidden = {}
764
769
765 # A namespace to keep track of internal data structures to prevent
770 # A namespace to keep track of internal data structures to prevent
766 # them from cluttering user-visible stuff. Will be updated later
771 # them from cluttering user-visible stuff. Will be updated later
767 self.internal_ns = {}
772 self.internal_ns = {}
768
773
769 # Now that FakeModule produces a real module, we've run into a nasty
774 # Now that FakeModule produces a real module, we've run into a nasty
770 # problem: after script execution (via %run), the module where the user
775 # problem: after script execution (via %run), the module where the user
771 # code ran is deleted. Now that this object is a true module (needed
776 # code ran is deleted. Now that this object is a true module (needed
772 # so docetst and other tools work correctly), the Python module
777 # so docetst and other tools work correctly), the Python module
773 # teardown mechanism runs over it, and sets to None every variable
778 # teardown mechanism runs over it, and sets to None every variable
774 # present in that module. Top-level references to objects from the
779 # present in that module. Top-level references to objects from the
775 # script survive, because the user_ns is updated with them. However,
780 # script survive, because the user_ns is updated with them. However,
776 # calling functions defined in the script that use other things from
781 # calling functions defined in the script that use other things from
777 # the script will fail, because the function's closure had references
782 # the script will fail, because the function's closure had references
778 # to the original objects, which are now all None. So we must protect
783 # to the original objects, which are now all None. So we must protect
779 # these modules from deletion by keeping a cache.
784 # these modules from deletion by keeping a cache.
780 #
785 #
781 # To avoid keeping stale modules around (we only need the one from the
786 # To avoid keeping stale modules around (we only need the one from the
782 # last run), we use a dict keyed with the full path to the script, so
787 # last run), we use a dict keyed with the full path to the script, so
783 # only the last version of the module is held in the cache. Note,
788 # only the last version of the module is held in the cache. Note,
784 # however, that we must cache the module *namespace contents* (their
789 # however, that we must cache the module *namespace contents* (their
785 # __dict__). Because if we try to cache the actual modules, old ones
790 # __dict__). Because if we try to cache the actual modules, old ones
786 # (uncached) could be destroyed while still holding references (such as
791 # (uncached) could be destroyed while still holding references (such as
787 # those held by GUI objects that tend to be long-lived)>
792 # those held by GUI objects that tend to be long-lived)>
788 #
793 #
789 # The %reset command will flush this cache. See the cache_main_mod()
794 # The %reset command will flush this cache. See the cache_main_mod()
790 # and clear_main_mod_cache() methods for details on use.
795 # and clear_main_mod_cache() methods for details on use.
791
796
792 # This is the cache used for 'main' namespaces
797 # This is the cache used for 'main' namespaces
793 self._main_ns_cache = {}
798 self._main_ns_cache = {}
794 # And this is the single instance of FakeModule whose __dict__ we keep
799 # And this is the single instance of FakeModule whose __dict__ we keep
795 # copying and clearing for reuse on each %run
800 # copying and clearing for reuse on each %run
796 self._user_main_module = FakeModule()
801 self._user_main_module = FakeModule()
797
802
798 # A table holding all the namespaces IPython deals with, so that
803 # A table holding all the namespaces IPython deals with, so that
799 # introspection facilities can search easily.
804 # introspection facilities can search easily.
800 self.ns_table = {'user':user_ns,
805 self.ns_table = {'user':user_ns,
801 'user_global':user_global_ns,
806 'user_global':user_global_ns,
802 'internal':self.internal_ns,
807 'internal':self.internal_ns,
803 'builtin':__builtin__.__dict__
808 'builtin':__builtin__.__dict__
804 }
809 }
805
810
806 # Similarly, track all namespaces where references can be held and that
811 # Similarly, track all namespaces where references can be held and that
807 # we can safely clear (so it can NOT include builtin). This one can be
812 # we can safely clear (so it can NOT include builtin). This one can be
808 # a simple list.
813 # a simple list.
809 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
814 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
810 self.internal_ns, self._main_ns_cache ]
815 self.internal_ns, self._main_ns_cache ]
811
816
812 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
817 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
813 """Return a valid local and global user interactive namespaces.
818 """Return a valid local and global user interactive namespaces.
814
819
815 This builds a dict with the minimal information needed to operate as a
820 This builds a dict with the minimal information needed to operate as a
816 valid IPython user namespace, which you can pass to the various
821 valid IPython user namespace, which you can pass to the various
817 embedding classes in ipython. The default implementation returns the
822 embedding classes in ipython. The default implementation returns the
818 same dict for both the locals and the globals to allow functions to
823 same dict for both the locals and the globals to allow functions to
819 refer to variables in the namespace. Customized implementations can
824 refer to variables in the namespace. Customized implementations can
820 return different dicts. The locals dictionary can actually be anything
825 return different dicts. The locals dictionary can actually be anything
821 following the basic mapping protocol of a dict, but the globals dict
826 following the basic mapping protocol of a dict, but the globals dict
822 must be a true dict, not even a subclass. It is recommended that any
827 must be a true dict, not even a subclass. It is recommended that any
823 custom object for the locals namespace synchronize with the globals
828 custom object for the locals namespace synchronize with the globals
824 dict somehow.
829 dict somehow.
825
830
826 Raises TypeError if the provided globals namespace is not a true dict.
831 Raises TypeError if the provided globals namespace is not a true dict.
827
832
828 Parameters
833 Parameters
829 ----------
834 ----------
830 user_ns : dict-like, optional
835 user_ns : dict-like, optional
831 The current user namespace. The items in this namespace should
836 The current user namespace. The items in this namespace should
832 be included in the output. If None, an appropriate blank
837 be included in the output. If None, an appropriate blank
833 namespace should be created.
838 namespace should be created.
834 user_global_ns : dict, optional
839 user_global_ns : dict, optional
835 The current user global namespace. The items in this namespace
840 The current user global namespace. The items in this namespace
836 should be included in the output. If None, an appropriate
841 should be included in the output. If None, an appropriate
837 blank namespace should be created.
842 blank namespace should be created.
838
843
839 Returns
844 Returns
840 -------
845 -------
841 A pair of dictionary-like object to be used as the local namespace
846 A pair of dictionary-like object to be used as the local namespace
842 of the interpreter and a dict to be used as the global namespace.
847 of the interpreter and a dict to be used as the global namespace.
843 """
848 """
844
849
845
850
846 # We must ensure that __builtin__ (without the final 's') is always
851 # We must ensure that __builtin__ (without the final 's') is always
847 # available and pointing to the __builtin__ *module*. For more details:
852 # available and pointing to the __builtin__ *module*. For more details:
848 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
853 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
849
854
850 if user_ns is None:
855 if user_ns is None:
851 # Set __name__ to __main__ to better match the behavior of the
856 # Set __name__ to __main__ to better match the behavior of the
852 # normal interpreter.
857 # normal interpreter.
853 user_ns = {'__name__' :'__main__',
858 user_ns = {'__name__' :'__main__',
854 '__builtin__' : __builtin__,
859 '__builtin__' : __builtin__,
855 '__builtins__' : __builtin__,
860 '__builtins__' : __builtin__,
856 }
861 }
857 else:
862 else:
858 user_ns.setdefault('__name__','__main__')
863 user_ns.setdefault('__name__','__main__')
859 user_ns.setdefault('__builtin__',__builtin__)
864 user_ns.setdefault('__builtin__',__builtin__)
860 user_ns.setdefault('__builtins__',__builtin__)
865 user_ns.setdefault('__builtins__',__builtin__)
861
866
862 if user_global_ns is None:
867 if user_global_ns is None:
863 user_global_ns = user_ns
868 user_global_ns = user_ns
864 if type(user_global_ns) is not dict:
869 if type(user_global_ns) is not dict:
865 raise TypeError("user_global_ns must be a true dict; got %r"
870 raise TypeError("user_global_ns must be a true dict; got %r"
866 % type(user_global_ns))
871 % type(user_global_ns))
867
872
868 return user_ns, user_global_ns
873 return user_ns, user_global_ns
869
874
870 def init_sys_modules(self):
875 def init_sys_modules(self):
871 # We need to insert into sys.modules something that looks like a
876 # We need to insert into sys.modules something that looks like a
872 # module but which accesses the IPython namespace, for shelve and
877 # module but which accesses the IPython namespace, for shelve and
873 # pickle to work interactively. Normally they rely on getting
878 # pickle to work interactively. Normally they rely on getting
874 # everything out of __main__, but for embedding purposes each IPython
879 # everything out of __main__, but for embedding purposes each IPython
875 # instance has its own private namespace, so we can't go shoving
880 # instance has its own private namespace, so we can't go shoving
876 # everything into __main__.
881 # everything into __main__.
877
882
878 # note, however, that we should only do this for non-embedded
883 # note, however, that we should only do this for non-embedded
879 # ipythons, which really mimic the __main__.__dict__ with their own
884 # ipythons, which really mimic the __main__.__dict__ with their own
880 # namespace. Embedded instances, on the other hand, should not do
885 # namespace. Embedded instances, on the other hand, should not do
881 # this because they need to manage the user local/global namespaces
886 # this because they need to manage the user local/global namespaces
882 # only, but they live within a 'normal' __main__ (meaning, they
887 # only, but they live within a 'normal' __main__ (meaning, they
883 # shouldn't overtake the execution environment of the script they're
888 # shouldn't overtake the execution environment of the script they're
884 # embedded in).
889 # embedded in).
885
890
886 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
891 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
887
892
888 try:
893 try:
889 main_name = self.user_ns['__name__']
894 main_name = self.user_ns['__name__']
890 except KeyError:
895 except KeyError:
891 raise KeyError('user_ns dictionary MUST have a "__name__" key')
896 raise KeyError('user_ns dictionary MUST have a "__name__" key')
892 else:
897 else:
893 sys.modules[main_name] = FakeModule(self.user_ns)
898 sys.modules[main_name] = FakeModule(self.user_ns)
894
899
895 def init_user_ns(self):
900 def init_user_ns(self):
896 """Initialize all user-visible namespaces to their minimum defaults.
901 """Initialize all user-visible namespaces to their minimum defaults.
897
902
898 Certain history lists are also initialized here, as they effectively
903 Certain history lists are also initialized here, as they effectively
899 act as user namespaces.
904 act as user namespaces.
900
905
901 Notes
906 Notes
902 -----
907 -----
903 All data structures here are only filled in, they are NOT reset by this
908 All data structures here are only filled in, they are NOT reset by this
904 method. If they were not empty before, data will simply be added to
909 method. If they were not empty before, data will simply be added to
905 therm.
910 therm.
906 """
911 """
907 # This function works in two parts: first we put a few things in
912 # This function works in two parts: first we put a few things in
908 # user_ns, and we sync that contents into user_ns_hidden so that these
913 # user_ns, and we sync that contents into user_ns_hidden so that these
909 # initial variables aren't shown by %who. After the sync, we add the
914 # initial variables aren't shown by %who. After the sync, we add the
910 # rest of what we *do* want the user to see with %who even on a new
915 # rest of what we *do* want the user to see with %who even on a new
911 # session (probably nothing, so theye really only see their own stuff)
916 # session (probably nothing, so theye really only see their own stuff)
912
917
913 # The user dict must *always* have a __builtin__ reference to the
918 # The user dict must *always* have a __builtin__ reference to the
914 # Python standard __builtin__ namespace, which must be imported.
919 # Python standard __builtin__ namespace, which must be imported.
915 # This is so that certain operations in prompt evaluation can be
920 # This is so that certain operations in prompt evaluation can be
916 # reliably executed with builtins. Note that we can NOT use
921 # reliably executed with builtins. Note that we can NOT use
917 # __builtins__ (note the 's'), because that can either be a dict or a
922 # __builtins__ (note the 's'), because that can either be a dict or a
918 # module, and can even mutate at runtime, depending on the context
923 # module, and can even mutate at runtime, depending on the context
919 # (Python makes no guarantees on it). In contrast, __builtin__ is
924 # (Python makes no guarantees on it). In contrast, __builtin__ is
920 # always a module object, though it must be explicitly imported.
925 # always a module object, though it must be explicitly imported.
921
926
922 # For more details:
927 # For more details:
923 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
928 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
924 ns = dict(__builtin__ = __builtin__)
929 ns = dict(__builtin__ = __builtin__)
925
930
926 # Put 'help' in the user namespace
931 # Put 'help' in the user namespace
927 try:
932 try:
928 from site import _Helper
933 from site import _Helper
929 ns['help'] = _Helper()
934 ns['help'] = _Helper()
930 except ImportError:
935 except ImportError:
931 warn('help() not available - check site.py')
936 warn('help() not available - check site.py')
932
937
933 # make global variables for user access to the histories
938 # make global variables for user access to the histories
934 ns['_ih'] = self.input_hist
939 ns['_ih'] = self.input_hist
935 ns['_oh'] = self.output_hist
940 ns['_oh'] = self.output_hist
936 ns['_dh'] = self.dir_hist
941 ns['_dh'] = self.dir_hist
937
942
938 ns['_sh'] = shadowns
943 ns['_sh'] = shadowns
939
944
940 # user aliases to input and output histories. These shouldn't show up
945 # user aliases to input and output histories. These shouldn't show up
941 # in %who, as they can have very large reprs.
946 # in %who, as they can have very large reprs.
942 ns['In'] = self.input_hist
947 ns['In'] = self.input_hist
943 ns['Out'] = self.output_hist
948 ns['Out'] = self.output_hist
944
949
945 # Store myself as the public api!!!
950 # Store myself as the public api!!!
946 ns['get_ipython'] = self.get_ipython
951 ns['get_ipython'] = self.get_ipython
947
952
948 # Sync what we've added so far to user_ns_hidden so these aren't seen
953 # Sync what we've added so far to user_ns_hidden so these aren't seen
949 # by %who
954 # by %who
950 self.user_ns_hidden.update(ns)
955 self.user_ns_hidden.update(ns)
951
956
952 # Anything put into ns now would show up in %who. Think twice before
957 # Anything put into ns now would show up in %who. Think twice before
953 # putting anything here, as we really want %who to show the user their
958 # putting anything here, as we really want %who to show the user their
954 # stuff, not our variables.
959 # stuff, not our variables.
955
960
956 # Finally, update the real user's namespace
961 # Finally, update the real user's namespace
957 self.user_ns.update(ns)
962 self.user_ns.update(ns)
958
963
959
964
960 def reset(self):
965 def reset(self):
961 """Clear all internal namespaces.
966 """Clear all internal namespaces.
962
967
963 Note that this is much more aggressive than %reset, since it clears
968 Note that this is much more aggressive than %reset, since it clears
964 fully all namespaces, as well as all input/output lists.
969 fully all namespaces, as well as all input/output lists.
965 """
970 """
966 for ns in self.ns_refs_table:
971 for ns in self.ns_refs_table:
967 ns.clear()
972 ns.clear()
968
973
969 self.alias_manager.clear_aliases()
974 self.alias_manager.clear_aliases()
970
975
971 # Clear input and output histories
976 # Clear input and output histories
972 self.input_hist[:] = []
977 self.input_hist[:] = []
973 self.input_hist_raw[:] = []
978 self.input_hist_raw[:] = []
974 self.output_hist.clear()
979 self.output_hist.clear()
975
980
976 # Restore the user namespaces to minimal usability
981 # Restore the user namespaces to minimal usability
977 self.init_user_ns()
982 self.init_user_ns()
978
983
979 # Restore the default and user aliases
984 # Restore the default and user aliases
980 self.alias_manager.init_aliases()
985 self.alias_manager.init_aliases()
981
986
982 def reset_selective(self, regex=None):
987 def reset_selective(self, regex=None):
983 """Clear selective variables from internal namespaces based on a
988 """Clear selective variables from internal namespaces based on a
984 specified regular expression.
989 specified regular expression.
985
990
986 Parameters
991 Parameters
987 ----------
992 ----------
988 regex : string or compiled pattern, optional
993 regex : string or compiled pattern, optional
989 A regular expression pattern that will be used in searching
994 A regular expression pattern that will be used in searching
990 variable names in the users namespaces.
995 variable names in the users namespaces.
991 """
996 """
992 if regex is not None:
997 if regex is not None:
993 try:
998 try:
994 m = re.compile(regex)
999 m = re.compile(regex)
995 except TypeError:
1000 except TypeError:
996 raise TypeError('regex must be a string or compiled pattern')
1001 raise TypeError('regex must be a string or compiled pattern')
997 # Search for keys in each namespace that match the given regex
1002 # Search for keys in each namespace that match the given regex
998 # If a match is found, delete the key/value pair.
1003 # If a match is found, delete the key/value pair.
999 for ns in self.ns_refs_table:
1004 for ns in self.ns_refs_table:
1000 for var in ns:
1005 for var in ns:
1001 if m.search(var):
1006 if m.search(var):
1002 del ns[var]
1007 del ns[var]
1003
1008
1004 def push(self, variables, interactive=True):
1009 def push(self, variables, interactive=True):
1005 """Inject a group of variables into the IPython user namespace.
1010 """Inject a group of variables into the IPython user namespace.
1006
1011
1007 Parameters
1012 Parameters
1008 ----------
1013 ----------
1009 variables : dict, str or list/tuple of str
1014 variables : dict, str or list/tuple of str
1010 The variables to inject into the user's namespace. If a dict, a
1015 The variables to inject into the user's namespace. If a dict, a
1011 simple update is done. If a str, the string is assumed to have
1016 simple update is done. If a str, the string is assumed to have
1012 variable names separated by spaces. A list/tuple of str can also
1017 variable names separated by spaces. A list/tuple of str can also
1013 be used to give the variable names. If just the variable names are
1018 be used to give the variable names. If just the variable names are
1014 give (list/tuple/str) then the variable values looked up in the
1019 give (list/tuple/str) then the variable values looked up in the
1015 callers frame.
1020 callers frame.
1016 interactive : bool
1021 interactive : bool
1017 If True (default), the variables will be listed with the ``who``
1022 If True (default), the variables will be listed with the ``who``
1018 magic.
1023 magic.
1019 """
1024 """
1020 vdict = None
1025 vdict = None
1021
1026
1022 # We need a dict of name/value pairs to do namespace updates.
1027 # We need a dict of name/value pairs to do namespace updates.
1023 if isinstance(variables, dict):
1028 if isinstance(variables, dict):
1024 vdict = variables
1029 vdict = variables
1025 elif isinstance(variables, (basestring, list, tuple)):
1030 elif isinstance(variables, (basestring, list, tuple)):
1026 if isinstance(variables, basestring):
1031 if isinstance(variables, basestring):
1027 vlist = variables.split()
1032 vlist = variables.split()
1028 else:
1033 else:
1029 vlist = variables
1034 vlist = variables
1030 vdict = {}
1035 vdict = {}
1031 cf = sys._getframe(1)
1036 cf = sys._getframe(1)
1032 for name in vlist:
1037 for name in vlist:
1033 try:
1038 try:
1034 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1039 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1035 except:
1040 except:
1036 print ('Could not get variable %s from %s' %
1041 print ('Could not get variable %s from %s' %
1037 (name,cf.f_code.co_name))
1042 (name,cf.f_code.co_name))
1038 else:
1043 else:
1039 raise ValueError('variables must be a dict/str/list/tuple')
1044 raise ValueError('variables must be a dict/str/list/tuple')
1040
1045
1041 # Propagate variables to user namespace
1046 # Propagate variables to user namespace
1042 self.user_ns.update(vdict)
1047 self.user_ns.update(vdict)
1043
1048
1044 # And configure interactive visibility
1049 # And configure interactive visibility
1045 config_ns = self.user_ns_hidden
1050 config_ns = self.user_ns_hidden
1046 if interactive:
1051 if interactive:
1047 for name, val in vdict.iteritems():
1052 for name, val in vdict.iteritems():
1048 config_ns.pop(name, None)
1053 config_ns.pop(name, None)
1049 else:
1054 else:
1050 for name,val in vdict.iteritems():
1055 for name,val in vdict.iteritems():
1051 config_ns[name] = val
1056 config_ns[name] = val
1052
1057
1053 #-------------------------------------------------------------------------
1058 #-------------------------------------------------------------------------
1054 # Things related to object introspection
1059 # Things related to object introspection
1055 #-------------------------------------------------------------------------
1060 #-------------------------------------------------------------------------
1056 def _ofind(self, oname, namespaces=None):
1061 def _ofind(self, oname, namespaces=None):
1057 """Find an object in the available namespaces.
1062 """Find an object in the available namespaces.
1058
1063
1059 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1064 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1060
1065
1061 Has special code to detect magic functions.
1066 Has special code to detect magic functions.
1062 """
1067 """
1063 #oname = oname.strip()
1068 #oname = oname.strip()
1064 #print '1- oname: <%r>' % oname # dbg
1069 #print '1- oname: <%r>' % oname # dbg
1065 try:
1070 try:
1066 oname = oname.strip().encode('ascii')
1071 oname = oname.strip().encode('ascii')
1067 #print '2- oname: <%r>' % oname # dbg
1072 #print '2- oname: <%r>' % oname # dbg
1068 except UnicodeEncodeError:
1073 except UnicodeEncodeError:
1069 print 'Python identifiers can only contain ascii characters.'
1074 print 'Python identifiers can only contain ascii characters.'
1070 return dict(found=False)
1075 return dict(found=False)
1071
1076
1072 alias_ns = None
1077 alias_ns = None
1073 if namespaces is None:
1078 if namespaces is None:
1074 # Namespaces to search in:
1079 # Namespaces to search in:
1075 # Put them in a list. The order is important so that we
1080 # Put them in a list. The order is important so that we
1076 # find things in the same order that Python finds them.
1081 # find things in the same order that Python finds them.
1077 namespaces = [ ('Interactive', self.user_ns),
1082 namespaces = [ ('Interactive', self.user_ns),
1078 ('IPython internal', self.internal_ns),
1083 ('IPython internal', self.internal_ns),
1079 ('Python builtin', __builtin__.__dict__),
1084 ('Python builtin', __builtin__.__dict__),
1080 ('Alias', self.alias_manager.alias_table),
1085 ('Alias', self.alias_manager.alias_table),
1081 ]
1086 ]
1082 alias_ns = self.alias_manager.alias_table
1087 alias_ns = self.alias_manager.alias_table
1083
1088
1084 # initialize results to 'null'
1089 # initialize results to 'null'
1085 found = False; obj = None; ospace = None; ds = None;
1090 found = False; obj = None; ospace = None; ds = None;
1086 ismagic = False; isalias = False; parent = None
1091 ismagic = False; isalias = False; parent = None
1087
1092
1088 # We need to special-case 'print', which as of python2.6 registers as a
1093 # We need to special-case 'print', which as of python2.6 registers as a
1089 # function but should only be treated as one if print_function was
1094 # function but should only be treated as one if print_function was
1090 # loaded with a future import. In this case, just bail.
1095 # loaded with a future import. In this case, just bail.
1091 if (oname == 'print' and not (self.compile.compiler.flags &
1096 if (oname == 'print' and not (self.compile.compiler.flags &
1092 __future__.CO_FUTURE_PRINT_FUNCTION)):
1097 __future__.CO_FUTURE_PRINT_FUNCTION)):
1093 return {'found':found, 'obj':obj, 'namespace':ospace,
1098 return {'found':found, 'obj':obj, 'namespace':ospace,
1094 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1099 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1095
1100
1096 # Look for the given name by splitting it in parts. If the head is
1101 # Look for the given name by splitting it in parts. If the head is
1097 # found, then we look for all the remaining parts as members, and only
1102 # found, then we look for all the remaining parts as members, and only
1098 # declare success if we can find them all.
1103 # declare success if we can find them all.
1099 oname_parts = oname.split('.')
1104 oname_parts = oname.split('.')
1100 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1105 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1101 for nsname,ns in namespaces:
1106 for nsname,ns in namespaces:
1102 try:
1107 try:
1103 obj = ns[oname_head]
1108 obj = ns[oname_head]
1104 except KeyError:
1109 except KeyError:
1105 continue
1110 continue
1106 else:
1111 else:
1107 #print 'oname_rest:', oname_rest # dbg
1112 #print 'oname_rest:', oname_rest # dbg
1108 for part in oname_rest:
1113 for part in oname_rest:
1109 try:
1114 try:
1110 parent = obj
1115 parent = obj
1111 obj = getattr(obj,part)
1116 obj = getattr(obj,part)
1112 except:
1117 except:
1113 # Blanket except b/c some badly implemented objects
1118 # Blanket except b/c some badly implemented objects
1114 # allow __getattr__ to raise exceptions other than
1119 # allow __getattr__ to raise exceptions other than
1115 # AttributeError, which then crashes IPython.
1120 # AttributeError, which then crashes IPython.
1116 break
1121 break
1117 else:
1122 else:
1118 # If we finish the for loop (no break), we got all members
1123 # If we finish the for loop (no break), we got all members
1119 found = True
1124 found = True
1120 ospace = nsname
1125 ospace = nsname
1121 if ns == alias_ns:
1126 if ns == alias_ns:
1122 isalias = True
1127 isalias = True
1123 break # namespace loop
1128 break # namespace loop
1124
1129
1125 # Try to see if it's magic
1130 # Try to see if it's magic
1126 if not found:
1131 if not found:
1127 if oname.startswith(ESC_MAGIC):
1132 if oname.startswith(ESC_MAGIC):
1128 oname = oname[1:]
1133 oname = oname[1:]
1129 obj = getattr(self,'magic_'+oname,None)
1134 obj = getattr(self,'magic_'+oname,None)
1130 if obj is not None:
1135 if obj is not None:
1131 found = True
1136 found = True
1132 ospace = 'IPython internal'
1137 ospace = 'IPython internal'
1133 ismagic = True
1138 ismagic = True
1134
1139
1135 # Last try: special-case some literals like '', [], {}, etc:
1140 # Last try: special-case some literals like '', [], {}, etc:
1136 if not found and oname_head in ["''",'""','[]','{}','()']:
1141 if not found and oname_head in ["''",'""','[]','{}','()']:
1137 obj = eval(oname_head)
1142 obj = eval(oname_head)
1138 found = True
1143 found = True
1139 ospace = 'Interactive'
1144 ospace = 'Interactive'
1140
1145
1141 return {'found':found, 'obj':obj, 'namespace':ospace,
1146 return {'found':found, 'obj':obj, 'namespace':ospace,
1142 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1147 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1143
1148
1144 def _ofind_property(self, oname, info):
1149 def _ofind_property(self, oname, info):
1145 """Second part of object finding, to look for property details."""
1150 """Second part of object finding, to look for property details."""
1146 if info.found:
1151 if info.found:
1147 # Get the docstring of the class property if it exists.
1152 # Get the docstring of the class property if it exists.
1148 path = oname.split('.')
1153 path = oname.split('.')
1149 root = '.'.join(path[:-1])
1154 root = '.'.join(path[:-1])
1150 if info.parent is not None:
1155 if info.parent is not None:
1151 try:
1156 try:
1152 target = getattr(info.parent, '__class__')
1157 target = getattr(info.parent, '__class__')
1153 # The object belongs to a class instance.
1158 # The object belongs to a class instance.
1154 try:
1159 try:
1155 target = getattr(target, path[-1])
1160 target = getattr(target, path[-1])
1156 # The class defines the object.
1161 # The class defines the object.
1157 if isinstance(target, property):
1162 if isinstance(target, property):
1158 oname = root + '.__class__.' + path[-1]
1163 oname = root + '.__class__.' + path[-1]
1159 info = Struct(self._ofind(oname))
1164 info = Struct(self._ofind(oname))
1160 except AttributeError: pass
1165 except AttributeError: pass
1161 except AttributeError: pass
1166 except AttributeError: pass
1162
1167
1163 # We return either the new info or the unmodified input if the object
1168 # We return either the new info or the unmodified input if the object
1164 # hadn't been found
1169 # hadn't been found
1165 return info
1170 return info
1166
1171
1167 def _object_find(self, oname, namespaces=None):
1172 def _object_find(self, oname, namespaces=None):
1168 """Find an object and return a struct with info about it."""
1173 """Find an object and return a struct with info about it."""
1169 inf = Struct(self._ofind(oname, namespaces))
1174 inf = Struct(self._ofind(oname, namespaces))
1170 return Struct(self._ofind_property(oname, inf))
1175 return Struct(self._ofind_property(oname, inf))
1171
1176
1172 def _inspect(self, meth, oname, namespaces=None, **kw):
1177 def _inspect(self, meth, oname, namespaces=None, **kw):
1173 """Generic interface to the inspector system.
1178 """Generic interface to the inspector system.
1174
1179
1175 This function is meant to be called by pdef, pdoc & friends."""
1180 This function is meant to be called by pdef, pdoc & friends."""
1176 info = self._object_find(oname)
1181 info = self._object_find(oname)
1177 if info.found:
1182 if info.found:
1178 pmethod = getattr(self.inspector, meth)
1183 pmethod = getattr(self.inspector, meth)
1179 formatter = format_screen if info.ismagic else None
1184 formatter = format_screen if info.ismagic else None
1180 if meth == 'pdoc':
1185 if meth == 'pdoc':
1181 pmethod(info.obj, oname, formatter)
1186 pmethod(info.obj, oname, formatter)
1182 elif meth == 'pinfo':
1187 elif meth == 'pinfo':
1183 pmethod(info.obj, oname, formatter, info, **kw)
1188 pmethod(info.obj, oname, formatter, info, **kw)
1184 else:
1189 else:
1185 pmethod(info.obj, oname)
1190 pmethod(info.obj, oname)
1186 else:
1191 else:
1187 print 'Object `%s` not found.' % oname
1192 print 'Object `%s` not found.' % oname
1188 return 'not found' # so callers can take other action
1193 return 'not found' # so callers can take other action
1189
1194
1190 def object_inspect(self, oname):
1195 def object_inspect(self, oname):
1191 info = self._object_find(oname)
1196 info = self._object_find(oname)
1192 if info.found:
1197 if info.found:
1193 return self.inspector.info(info.obj, info=info)
1198 return self.inspector.info(info.obj, info=info)
1194 else:
1199 else:
1195 return oinspect.mk_object_info({'found' : False})
1200 return oinspect.mk_object_info({'found' : False})
1196
1201
1197 #-------------------------------------------------------------------------
1202 #-------------------------------------------------------------------------
1198 # Things related to history management
1203 # Things related to history management
1199 #-------------------------------------------------------------------------
1204 #-------------------------------------------------------------------------
1200
1205
1201 def init_history(self):
1206 def init_history(self):
1202 # List of input with multi-line handling.
1207 # List of input with multi-line handling.
1203 self.input_hist = InputList()
1208 self.input_hist = InputList()
1204 # This one will hold the 'raw' input history, without any
1209 # This one will hold the 'raw' input history, without any
1205 # pre-processing. This will allow users to retrieve the input just as
1210 # pre-processing. This will allow users to retrieve the input just as
1206 # it was exactly typed in by the user, with %hist -r.
1211 # it was exactly typed in by the user, with %hist -r.
1207 self.input_hist_raw = InputList()
1212 self.input_hist_raw = InputList()
1208
1213
1209 # list of visited directories
1214 # list of visited directories
1210 try:
1215 try:
1211 self.dir_hist = [os.getcwd()]
1216 self.dir_hist = [os.getcwd()]
1212 except OSError:
1217 except OSError:
1213 self.dir_hist = []
1218 self.dir_hist = []
1214
1219
1215 # dict of output history
1220 # dict of output history
1216 self.output_hist = {}
1221 self.output_hist = {}
1217
1222
1218 # Now the history file
1223 # Now the history file
1219 if self.profile:
1224 if self.profile:
1220 histfname = 'history-%s' % self.profile
1225 histfname = 'history-%s' % self.profile
1221 else:
1226 else:
1222 histfname = 'history'
1227 histfname = 'history'
1223 self.histfile = os.path.join(self.ipython_dir, histfname)
1228 self.histfile = os.path.join(self.ipython_dir, histfname)
1224
1229
1225 # Fill the history zero entry, user counter starts at 1
1230 # Fill the history zero entry, user counter starts at 1
1226 self.input_hist.append('\n')
1231 self.input_hist.append('\n')
1227 self.input_hist_raw.append('\n')
1232 self.input_hist_raw.append('\n')
1228
1233
1229 def init_shadow_hist(self):
1234 def init_shadow_hist(self):
1230 try:
1235 try:
1231 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1236 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1232 except exceptions.UnicodeDecodeError:
1237 except exceptions.UnicodeDecodeError:
1233 print "Your ipython_dir can't be decoded to unicode!"
1238 print "Your ipython_dir can't be decoded to unicode!"
1234 print "Please set HOME environment variable to something that"
1239 print "Please set HOME environment variable to something that"
1235 print r"only has ASCII characters, e.g. c:\home"
1240 print r"only has ASCII characters, e.g. c:\home"
1236 print "Now it is", self.ipython_dir
1241 print "Now it is", self.ipython_dir
1237 sys.exit()
1242 sys.exit()
1238 self.shadowhist = ipcorehist.ShadowHist(self.db)
1243 self.shadowhist = ipcorehist.ShadowHist(self.db)
1239
1244
1240 def savehist(self):
1245 def savehist(self):
1241 """Save input history to a file (via readline library)."""
1246 """Save input history to a file (via readline library)."""
1242
1247
1243 try:
1248 try:
1244 self.readline.write_history_file(self.histfile)
1249 self.readline.write_history_file(self.histfile)
1245 except:
1250 except:
1246 print 'Unable to save IPython command history to file: ' + \
1251 print 'Unable to save IPython command history to file: ' + \
1247 `self.histfile`
1252 `self.histfile`
1248
1253
1249 def reloadhist(self):
1254 def reloadhist(self):
1250 """Reload the input history from disk file."""
1255 """Reload the input history from disk file."""
1251
1256
1252 try:
1257 try:
1253 self.readline.clear_history()
1258 self.readline.clear_history()
1254 self.readline.read_history_file(self.shell.histfile)
1259 self.readline.read_history_file(self.shell.histfile)
1255 except AttributeError:
1260 except AttributeError:
1256 pass
1261 pass
1257
1262
1258 def history_saving_wrapper(self, func):
1263 def history_saving_wrapper(self, func):
1259 """ Wrap func for readline history saving
1264 """ Wrap func for readline history saving
1260
1265
1261 Convert func into callable that saves & restores
1266 Convert func into callable that saves & restores
1262 history around the call """
1267 history around the call """
1263
1268
1264 if self.has_readline:
1269 if self.has_readline:
1265 from IPython.utils import rlineimpl as readline
1270 from IPython.utils import rlineimpl as readline
1266 else:
1271 else:
1267 return func
1272 return func
1268
1273
1269 def wrapper():
1274 def wrapper():
1270 self.savehist()
1275 self.savehist()
1271 try:
1276 try:
1272 func()
1277 func()
1273 finally:
1278 finally:
1274 readline.read_history_file(self.histfile)
1279 readline.read_history_file(self.histfile)
1275 return wrapper
1280 return wrapper
1276
1281
1277 def get_history(self, index=None, raw=False, output=True):
1282 def get_history(self, index=None, raw=False, output=True):
1278 """Get the history list.
1283 """Get the history list.
1279
1284
1280 Get the input and output history.
1285 Get the input and output history.
1281
1286
1282 Parameters
1287 Parameters
1283 ----------
1288 ----------
1284 index : n or (n1, n2) or None
1289 index : n or (n1, n2) or None
1285 If n, then the last entries. If a tuple, then all in
1290 If n, then the last entries. If a tuple, then all in
1286 range(n1, n2). If None, then all entries. Raises IndexError if
1291 range(n1, n2). If None, then all entries. Raises IndexError if
1287 the format of index is incorrect.
1292 the format of index is incorrect.
1288 raw : bool
1293 raw : bool
1289 If True, return the raw input.
1294 If True, return the raw input.
1290 output : bool
1295 output : bool
1291 If True, then return the output as well.
1296 If True, then return the output as well.
1292
1297
1293 Returns
1298 Returns
1294 -------
1299 -------
1295 If output is True, then return a dict of tuples, keyed by the prompt
1300 If output is True, then return a dict of tuples, keyed by the prompt
1296 numbers and with values of (input, output). If output is False, then
1301 numbers and with values of (input, output). If output is False, then
1297 a dict, keyed by the prompt number with the values of input. Raises
1302 a dict, keyed by the prompt number with the values of input. Raises
1298 IndexError if no history is found.
1303 IndexError if no history is found.
1299 """
1304 """
1300 if raw:
1305 if raw:
1301 input_hist = self.input_hist_raw
1306 input_hist = self.input_hist_raw
1302 else:
1307 else:
1303 input_hist = self.input_hist
1308 input_hist = self.input_hist
1304 if output:
1309 if output:
1305 output_hist = self.user_ns['Out']
1310 output_hist = self.user_ns['Out']
1306 n = len(input_hist)
1311 n = len(input_hist)
1307 if index is None:
1312 if index is None:
1308 start=0; stop=n
1313 start=0; stop=n
1309 elif isinstance(index, int):
1314 elif isinstance(index, int):
1310 start=n-index; stop=n
1315 start=n-index; stop=n
1311 elif isinstance(index, tuple) and len(index) == 2:
1316 elif isinstance(index, tuple) and len(index) == 2:
1312 start=index[0]; stop=index[1]
1317 start=index[0]; stop=index[1]
1313 else:
1318 else:
1314 raise IndexError('Not a valid index for the input history: %r'
1319 raise IndexError('Not a valid index for the input history: %r'
1315 % index)
1320 % index)
1316 hist = {}
1321 hist = {}
1317 for i in range(start, stop):
1322 for i in range(start, stop):
1318 if output:
1323 if output:
1319 hist[i] = (input_hist[i], output_hist.get(i))
1324 hist[i] = (input_hist[i], output_hist.get(i))
1320 else:
1325 else:
1321 hist[i] = input_hist[i]
1326 hist[i] = input_hist[i]
1322 if len(hist)==0:
1327 if len(hist)==0:
1323 raise IndexError('No history for range of indices: %r' % index)
1328 raise IndexError('No history for range of indices: %r' % index)
1324 return hist
1329 return hist
1325
1330
1326 #-------------------------------------------------------------------------
1331 #-------------------------------------------------------------------------
1327 # Things related to exception handling and tracebacks (not debugging)
1332 # Things related to exception handling and tracebacks (not debugging)
1328 #-------------------------------------------------------------------------
1333 #-------------------------------------------------------------------------
1329
1334
1330 def init_traceback_handlers(self, custom_exceptions):
1335 def init_traceback_handlers(self, custom_exceptions):
1331 # Syntax error handler.
1336 # Syntax error handler.
1332 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1337 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1333
1338
1334 # The interactive one is initialized with an offset, meaning we always
1339 # The interactive one is initialized with an offset, meaning we always
1335 # want to remove the topmost item in the traceback, which is our own
1340 # want to remove the topmost item in the traceback, which is our own
1336 # internal code. Valid modes: ['Plain','Context','Verbose']
1341 # internal code. Valid modes: ['Plain','Context','Verbose']
1337 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1342 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1338 color_scheme='NoColor',
1343 color_scheme='NoColor',
1339 tb_offset = 1)
1344 tb_offset = 1)
1340
1345
1341 # The instance will store a pointer to the system-wide exception hook,
1346 # The instance will store a pointer to the system-wide exception hook,
1342 # so that runtime code (such as magics) can access it. This is because
1347 # so that runtime code (such as magics) can access it. This is because
1343 # during the read-eval loop, it may get temporarily overwritten.
1348 # during the read-eval loop, it may get temporarily overwritten.
1344 self.sys_excepthook = sys.excepthook
1349 self.sys_excepthook = sys.excepthook
1345
1350
1346 # and add any custom exception handlers the user may have specified
1351 # and add any custom exception handlers the user may have specified
1347 self.set_custom_exc(*custom_exceptions)
1352 self.set_custom_exc(*custom_exceptions)
1348
1353
1349 # Set the exception mode
1354 # Set the exception mode
1350 self.InteractiveTB.set_mode(mode=self.xmode)
1355 self.InteractiveTB.set_mode(mode=self.xmode)
1351
1356
1352 def set_custom_exc(self, exc_tuple, handler):
1357 def set_custom_exc(self, exc_tuple, handler):
1353 """set_custom_exc(exc_tuple,handler)
1358 """set_custom_exc(exc_tuple,handler)
1354
1359
1355 Set a custom exception handler, which will be called if any of the
1360 Set a custom exception handler, which will be called if any of the
1356 exceptions in exc_tuple occur in the mainloop (specifically, in the
1361 exceptions in exc_tuple occur in the mainloop (specifically, in the
1357 runcode() method.
1362 runcode() method.
1358
1363
1359 Inputs:
1364 Inputs:
1360
1365
1361 - exc_tuple: a *tuple* of valid exceptions to call the defined
1366 - exc_tuple: a *tuple* of valid exceptions to call the defined
1362 handler for. It is very important that you use a tuple, and NOT A
1367 handler for. It is very important that you use a tuple, and NOT A
1363 LIST here, because of the way Python's except statement works. If
1368 LIST here, because of the way Python's except statement works. If
1364 you only want to trap a single exception, use a singleton tuple:
1369 you only want to trap a single exception, use a singleton tuple:
1365
1370
1366 exc_tuple == (MyCustomException,)
1371 exc_tuple == (MyCustomException,)
1367
1372
1368 - handler: this must be defined as a function with the following
1373 - handler: this must be defined as a function with the following
1369 basic interface::
1374 basic interface::
1370
1375
1371 def my_handler(self, etype, value, tb, tb_offset=None)
1376 def my_handler(self, etype, value, tb, tb_offset=None)
1372 ...
1377 ...
1373 # The return value must be
1378 # The return value must be
1374 return structured_traceback
1379 return structured_traceback
1375
1380
1376 This will be made into an instance method (via new.instancemethod)
1381 This will be made into an instance method (via new.instancemethod)
1377 of IPython itself, and it will be called if any of the exceptions
1382 of IPython itself, and it will be called if any of the exceptions
1378 listed in the exc_tuple are caught. If the handler is None, an
1383 listed in the exc_tuple are caught. If the handler is None, an
1379 internal basic one is used, which just prints basic info.
1384 internal basic one is used, which just prints basic info.
1380
1385
1381 WARNING: by putting in your own exception handler into IPython's main
1386 WARNING: by putting in your own exception handler into IPython's main
1382 execution loop, you run a very good chance of nasty crashes. This
1387 execution loop, you run a very good chance of nasty crashes. This
1383 facility should only be used if you really know what you are doing."""
1388 facility should only be used if you really know what you are doing."""
1384
1389
1385 assert type(exc_tuple)==type(()) , \
1390 assert type(exc_tuple)==type(()) , \
1386 "The custom exceptions must be given AS A TUPLE."
1391 "The custom exceptions must be given AS A TUPLE."
1387
1392
1388 def dummy_handler(self,etype,value,tb):
1393 def dummy_handler(self,etype,value,tb):
1389 print '*** Simple custom exception handler ***'
1394 print '*** Simple custom exception handler ***'
1390 print 'Exception type :',etype
1395 print 'Exception type :',etype
1391 print 'Exception value:',value
1396 print 'Exception value:',value
1392 print 'Traceback :',tb
1397 print 'Traceback :',tb
1393 print 'Source code :','\n'.join(self.buffer)
1398 print 'Source code :','\n'.join(self.buffer)
1394
1399
1395 if handler is None: handler = dummy_handler
1400 if handler is None: handler = dummy_handler
1396
1401
1397 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1402 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1398 self.custom_exceptions = exc_tuple
1403 self.custom_exceptions = exc_tuple
1399
1404
1400 def excepthook(self, etype, value, tb):
1405 def excepthook(self, etype, value, tb):
1401 """One more defense for GUI apps that call sys.excepthook.
1406 """One more defense for GUI apps that call sys.excepthook.
1402
1407
1403 GUI frameworks like wxPython trap exceptions and call
1408 GUI frameworks like wxPython trap exceptions and call
1404 sys.excepthook themselves. I guess this is a feature that
1409 sys.excepthook themselves. I guess this is a feature that
1405 enables them to keep running after exceptions that would
1410 enables them to keep running after exceptions that would
1406 otherwise kill their mainloop. This is a bother for IPython
1411 otherwise kill their mainloop. This is a bother for IPython
1407 which excepts to catch all of the program exceptions with a try:
1412 which excepts to catch all of the program exceptions with a try:
1408 except: statement.
1413 except: statement.
1409
1414
1410 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1415 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1411 any app directly invokes sys.excepthook, it will look to the user like
1416 any app directly invokes sys.excepthook, it will look to the user like
1412 IPython crashed. In order to work around this, we can disable the
1417 IPython crashed. In order to work around this, we can disable the
1413 CrashHandler and replace it with this excepthook instead, which prints a
1418 CrashHandler and replace it with this excepthook instead, which prints a
1414 regular traceback using our InteractiveTB. In this fashion, apps which
1419 regular traceback using our InteractiveTB. In this fashion, apps which
1415 call sys.excepthook will generate a regular-looking exception from
1420 call sys.excepthook will generate a regular-looking exception from
1416 IPython, and the CrashHandler will only be triggered by real IPython
1421 IPython, and the CrashHandler will only be triggered by real IPython
1417 crashes.
1422 crashes.
1418
1423
1419 This hook should be used sparingly, only in places which are not likely
1424 This hook should be used sparingly, only in places which are not likely
1420 to be true IPython errors.
1425 to be true IPython errors.
1421 """
1426 """
1422 self.showtraceback((etype,value,tb),tb_offset=0)
1427 self.showtraceback((etype,value,tb),tb_offset=0)
1423
1428
1424 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1429 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1425 exception_only=False):
1430 exception_only=False):
1426 """Display the exception that just occurred.
1431 """Display the exception that just occurred.
1427
1432
1428 If nothing is known about the exception, this is the method which
1433 If nothing is known about the exception, this is the method which
1429 should be used throughout the code for presenting user tracebacks,
1434 should be used throughout the code for presenting user tracebacks,
1430 rather than directly invoking the InteractiveTB object.
1435 rather than directly invoking the InteractiveTB object.
1431
1436
1432 A specific showsyntaxerror() also exists, but this method can take
1437 A specific showsyntaxerror() also exists, but this method can take
1433 care of calling it if needed, so unless you are explicitly catching a
1438 care of calling it if needed, so unless you are explicitly catching a
1434 SyntaxError exception, don't try to analyze the stack manually and
1439 SyntaxError exception, don't try to analyze the stack manually and
1435 simply call this method."""
1440 simply call this method."""
1436
1441
1437 try:
1442 try:
1438 if exc_tuple is None:
1443 if exc_tuple is None:
1439 etype, value, tb = sys.exc_info()
1444 etype, value, tb = sys.exc_info()
1440 else:
1445 else:
1441 etype, value, tb = exc_tuple
1446 etype, value, tb = exc_tuple
1442
1447
1443 if etype is None:
1448 if etype is None:
1444 if hasattr(sys, 'last_type'):
1449 if hasattr(sys, 'last_type'):
1445 etype, value, tb = sys.last_type, sys.last_value, \
1450 etype, value, tb = sys.last_type, sys.last_value, \
1446 sys.last_traceback
1451 sys.last_traceback
1447 else:
1452 else:
1448 self.write_err('No traceback available to show.\n')
1453 self.write_err('No traceback available to show.\n')
1449 return
1454 return
1450
1455
1451 if etype is SyntaxError:
1456 if etype is SyntaxError:
1452 # Though this won't be called by syntax errors in the input
1457 # Though this won't be called by syntax errors in the input
1453 # line, there may be SyntaxError cases whith imported code.
1458 # line, there may be SyntaxError cases whith imported code.
1454 self.showsyntaxerror(filename)
1459 self.showsyntaxerror(filename)
1455 elif etype is UsageError:
1460 elif etype is UsageError:
1456 print "UsageError:", value
1461 print "UsageError:", value
1457 else:
1462 else:
1458 # WARNING: these variables are somewhat deprecated and not
1463 # WARNING: these variables are somewhat deprecated and not
1459 # necessarily safe to use in a threaded environment, but tools
1464 # necessarily safe to use in a threaded environment, but tools
1460 # like pdb depend on their existence, so let's set them. If we
1465 # like pdb depend on their existence, so let's set them. If we
1461 # find problems in the field, we'll need to revisit their use.
1466 # find problems in the field, we'll need to revisit their use.
1462 sys.last_type = etype
1467 sys.last_type = etype
1463 sys.last_value = value
1468 sys.last_value = value
1464 sys.last_traceback = tb
1469 sys.last_traceback = tb
1465
1470
1466 if etype in self.custom_exceptions:
1471 if etype in self.custom_exceptions:
1467 # FIXME: Old custom traceback objects may just return a
1472 # FIXME: Old custom traceback objects may just return a
1468 # string, in that case we just put it into a list
1473 # string, in that case we just put it into a list
1469 stb = self.CustomTB(etype, value, tb, tb_offset)
1474 stb = self.CustomTB(etype, value, tb, tb_offset)
1470 if isinstance(ctb, basestring):
1475 if isinstance(ctb, basestring):
1471 stb = [stb]
1476 stb = [stb]
1472 else:
1477 else:
1473 if exception_only:
1478 if exception_only:
1474 stb = ['An exception has occurred, use %tb to see '
1479 stb = ['An exception has occurred, use %tb to see '
1475 'the full traceback.\n']
1480 'the full traceback.\n']
1476 stb.extend(self.InteractiveTB.get_exception_only(etype,
1481 stb.extend(self.InteractiveTB.get_exception_only(etype,
1477 value))
1482 value))
1478 else:
1483 else:
1479 stb = self.InteractiveTB.structured_traceback(etype,
1484 stb = self.InteractiveTB.structured_traceback(etype,
1480 value, tb, tb_offset=tb_offset)
1485 value, tb, tb_offset=tb_offset)
1481 # FIXME: the pdb calling should be done by us, not by
1486 # FIXME: the pdb calling should be done by us, not by
1482 # the code computing the traceback.
1487 # the code computing the traceback.
1483 if self.InteractiveTB.call_pdb:
1488 if self.InteractiveTB.call_pdb:
1484 # pdb mucks up readline, fix it back
1489 # pdb mucks up readline, fix it back
1485 self.set_readline_completer()
1490 self.set_readline_completer()
1486
1491
1487 # Actually show the traceback
1492 # Actually show the traceback
1488 self._showtraceback(etype, value, stb)
1493 self._showtraceback(etype, value, stb)
1489
1494
1490 except KeyboardInterrupt:
1495 except KeyboardInterrupt:
1491 self.write_err("\nKeyboardInterrupt\n")
1496 self.write_err("\nKeyboardInterrupt\n")
1492
1497
1493 def _showtraceback(self, etype, evalue, stb):
1498 def _showtraceback(self, etype, evalue, stb):
1494 """Actually show a traceback.
1499 """Actually show a traceback.
1495
1500
1496 Subclasses may override this method to put the traceback on a different
1501 Subclasses may override this method to put the traceback on a different
1497 place, like a side channel.
1502 place, like a side channel.
1498 """
1503 """
1499 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1504 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1500
1505
1501 def showsyntaxerror(self, filename=None):
1506 def showsyntaxerror(self, filename=None):
1502 """Display the syntax error that just occurred.
1507 """Display the syntax error that just occurred.
1503
1508
1504 This doesn't display a stack trace because there isn't one.
1509 This doesn't display a stack trace because there isn't one.
1505
1510
1506 If a filename is given, it is stuffed in the exception instead
1511 If a filename is given, it is stuffed in the exception instead
1507 of what was there before (because Python's parser always uses
1512 of what was there before (because Python's parser always uses
1508 "<string>" when reading from a string).
1513 "<string>" when reading from a string).
1509 """
1514 """
1510 etype, value, last_traceback = sys.exc_info()
1515 etype, value, last_traceback = sys.exc_info()
1511
1516
1512 # See note about these variables in showtraceback() above
1517 # See note about these variables in showtraceback() above
1513 sys.last_type = etype
1518 sys.last_type = etype
1514 sys.last_value = value
1519 sys.last_value = value
1515 sys.last_traceback = last_traceback
1520 sys.last_traceback = last_traceback
1516
1521
1517 if filename and etype is SyntaxError:
1522 if filename and etype is SyntaxError:
1518 # Work hard to stuff the correct filename in the exception
1523 # Work hard to stuff the correct filename in the exception
1519 try:
1524 try:
1520 msg, (dummy_filename, lineno, offset, line) = value
1525 msg, (dummy_filename, lineno, offset, line) = value
1521 except:
1526 except:
1522 # Not the format we expect; leave it alone
1527 # Not the format we expect; leave it alone
1523 pass
1528 pass
1524 else:
1529 else:
1525 # Stuff in the right filename
1530 # Stuff in the right filename
1526 try:
1531 try:
1527 # Assume SyntaxError is a class exception
1532 # Assume SyntaxError is a class exception
1528 value = SyntaxError(msg, (filename, lineno, offset, line))
1533 value = SyntaxError(msg, (filename, lineno, offset, line))
1529 except:
1534 except:
1530 # If that failed, assume SyntaxError is a string
1535 # If that failed, assume SyntaxError is a string
1531 value = msg, (filename, lineno, offset, line)
1536 value = msg, (filename, lineno, offset, line)
1532 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1537 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1533 self._showtraceback(etype, value, stb)
1538 self._showtraceback(etype, value, stb)
1534
1539
1535 #-------------------------------------------------------------------------
1540 #-------------------------------------------------------------------------
1536 # Things related to readline
1541 # Things related to readline
1537 #-------------------------------------------------------------------------
1542 #-------------------------------------------------------------------------
1538
1543
1539 def init_readline(self):
1544 def init_readline(self):
1540 """Command history completion/saving/reloading."""
1545 """Command history completion/saving/reloading."""
1541
1546
1542 if self.readline_use:
1547 if self.readline_use:
1543 import IPython.utils.rlineimpl as readline
1548 import IPython.utils.rlineimpl as readline
1544
1549
1545 self.rl_next_input = None
1550 self.rl_next_input = None
1546 self.rl_do_indent = False
1551 self.rl_do_indent = False
1547
1552
1548 if not self.readline_use or not readline.have_readline:
1553 if not self.readline_use or not readline.have_readline:
1549 self.has_readline = False
1554 self.has_readline = False
1550 self.readline = None
1555 self.readline = None
1551 # Set a number of methods that depend on readline to be no-op
1556 # Set a number of methods that depend on readline to be no-op
1552 self.savehist = no_op
1557 self.savehist = no_op
1553 self.reloadhist = no_op
1558 self.reloadhist = no_op
1554 self.set_readline_completer = no_op
1559 self.set_readline_completer = no_op
1555 self.set_custom_completer = no_op
1560 self.set_custom_completer = no_op
1556 self.set_completer_frame = no_op
1561 self.set_completer_frame = no_op
1557 warn('Readline services not available or not loaded.')
1562 warn('Readline services not available or not loaded.')
1558 else:
1563 else:
1559 self.has_readline = True
1564 self.has_readline = True
1560 self.readline = readline
1565 self.readline = readline
1561 sys.modules['readline'] = readline
1566 sys.modules['readline'] = readline
1562
1567
1563 # Platform-specific configuration
1568 # Platform-specific configuration
1564 if os.name == 'nt':
1569 if os.name == 'nt':
1565 # FIXME - check with Frederick to see if we can harmonize
1570 # FIXME - check with Frederick to see if we can harmonize
1566 # naming conventions with pyreadline to avoid this
1571 # naming conventions with pyreadline to avoid this
1567 # platform-dependent check
1572 # platform-dependent check
1568 self.readline_startup_hook = readline.set_pre_input_hook
1573 self.readline_startup_hook = readline.set_pre_input_hook
1569 else:
1574 else:
1570 self.readline_startup_hook = readline.set_startup_hook
1575 self.readline_startup_hook = readline.set_startup_hook
1571
1576
1572 # Load user's initrc file (readline config)
1577 # Load user's initrc file (readline config)
1573 # Or if libedit is used, load editrc.
1578 # Or if libedit is used, load editrc.
1574 inputrc_name = os.environ.get('INPUTRC')
1579 inputrc_name = os.environ.get('INPUTRC')
1575 if inputrc_name is None:
1580 if inputrc_name is None:
1576 home_dir = get_home_dir()
1581 home_dir = get_home_dir()
1577 if home_dir is not None:
1582 if home_dir is not None:
1578 inputrc_name = '.inputrc'
1583 inputrc_name = '.inputrc'
1579 if readline.uses_libedit:
1584 if readline.uses_libedit:
1580 inputrc_name = '.editrc'
1585 inputrc_name = '.editrc'
1581 inputrc_name = os.path.join(home_dir, inputrc_name)
1586 inputrc_name = os.path.join(home_dir, inputrc_name)
1582 if os.path.isfile(inputrc_name):
1587 if os.path.isfile(inputrc_name):
1583 try:
1588 try:
1584 readline.read_init_file(inputrc_name)
1589 readline.read_init_file(inputrc_name)
1585 except:
1590 except:
1586 warn('Problems reading readline initialization file <%s>'
1591 warn('Problems reading readline initialization file <%s>'
1587 % inputrc_name)
1592 % inputrc_name)
1588
1593
1589 # Configure readline according to user's prefs
1594 # Configure readline according to user's prefs
1590 # This is only done if GNU readline is being used. If libedit
1595 # This is only done if GNU readline is being used. If libedit
1591 # is being used (as on Leopard) the readline config is
1596 # is being used (as on Leopard) the readline config is
1592 # not run as the syntax for libedit is different.
1597 # not run as the syntax for libedit is different.
1593 if not readline.uses_libedit:
1598 if not readline.uses_libedit:
1594 for rlcommand in self.readline_parse_and_bind:
1599 for rlcommand in self.readline_parse_and_bind:
1595 #print "loading rl:",rlcommand # dbg
1600 #print "loading rl:",rlcommand # dbg
1596 readline.parse_and_bind(rlcommand)
1601 readline.parse_and_bind(rlcommand)
1597
1602
1598 # Remove some chars from the delimiters list. If we encounter
1603 # Remove some chars from the delimiters list. If we encounter
1599 # unicode chars, discard them.
1604 # unicode chars, discard them.
1600 delims = readline.get_completer_delims().encode("ascii", "ignore")
1605 delims = readline.get_completer_delims().encode("ascii", "ignore")
1601 delims = delims.translate(string._idmap,
1606 delims = delims.translate(string._idmap,
1602 self.readline_remove_delims)
1607 self.readline_remove_delims)
1603 delims = delims.replace(ESC_MAGIC, '')
1608 delims = delims.replace(ESC_MAGIC, '')
1604 readline.set_completer_delims(delims)
1609 readline.set_completer_delims(delims)
1605 # otherwise we end up with a monster history after a while:
1610 # otherwise we end up with a monster history after a while:
1606 readline.set_history_length(1000)
1611 readline.set_history_length(1000)
1607 try:
1612 try:
1608 #print '*** Reading readline history' # dbg
1613 #print '*** Reading readline history' # dbg
1609 readline.read_history_file(self.histfile)
1614 readline.read_history_file(self.histfile)
1610 except IOError:
1615 except IOError:
1611 pass # It doesn't exist yet.
1616 pass # It doesn't exist yet.
1612
1617
1613 # If we have readline, we want our history saved upon ipython
1618 # If we have readline, we want our history saved upon ipython
1614 # exiting.
1619 # exiting.
1615 atexit.register(self.savehist)
1620 atexit.register(self.savehist)
1616
1621
1617 # Configure auto-indent for all platforms
1622 # Configure auto-indent for all platforms
1618 self.set_autoindent(self.autoindent)
1623 self.set_autoindent(self.autoindent)
1619
1624
1620 def set_next_input(self, s):
1625 def set_next_input(self, s):
1621 """ Sets the 'default' input string for the next command line.
1626 """ Sets the 'default' input string for the next command line.
1622
1627
1623 Requires readline.
1628 Requires readline.
1624
1629
1625 Example:
1630 Example:
1626
1631
1627 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1632 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1628 [D:\ipython]|2> Hello Word_ # cursor is here
1633 [D:\ipython]|2> Hello Word_ # cursor is here
1629 """
1634 """
1630
1635
1631 self.rl_next_input = s
1636 self.rl_next_input = s
1632
1637
1633 # Maybe move this to the terminal subclass?
1638 # Maybe move this to the terminal subclass?
1634 def pre_readline(self):
1639 def pre_readline(self):
1635 """readline hook to be used at the start of each line.
1640 """readline hook to be used at the start of each line.
1636
1641
1637 Currently it handles auto-indent only."""
1642 Currently it handles auto-indent only."""
1638
1643
1639 if self.rl_do_indent:
1644 if self.rl_do_indent:
1640 self.readline.insert_text(self._indent_current_str())
1645 self.readline.insert_text(self._indent_current_str())
1641 if self.rl_next_input is not None:
1646 if self.rl_next_input is not None:
1642 self.readline.insert_text(self.rl_next_input)
1647 self.readline.insert_text(self.rl_next_input)
1643 self.rl_next_input = None
1648 self.rl_next_input = None
1644
1649
1645 def _indent_current_str(self):
1650 def _indent_current_str(self):
1646 """return the current level of indentation as a string"""
1651 """return the current level of indentation as a string"""
1647 return self.indent_current_nsp * ' '
1652 return self.indent_current_nsp * ' '
1648
1653
1649 #-------------------------------------------------------------------------
1654 #-------------------------------------------------------------------------
1650 # Things related to text completion
1655 # Things related to text completion
1651 #-------------------------------------------------------------------------
1656 #-------------------------------------------------------------------------
1652
1657
1653 def init_completer(self):
1658 def init_completer(self):
1654 """Initialize the completion machinery.
1659 """Initialize the completion machinery.
1655
1660
1656 This creates completion machinery that can be used by client code,
1661 This creates completion machinery that can be used by client code,
1657 either interactively in-process (typically triggered by the readline
1662 either interactively in-process (typically triggered by the readline
1658 library), programatically (such as in test suites) or out-of-prcess
1663 library), programatically (such as in test suites) or out-of-prcess
1659 (typically over the network by remote frontends).
1664 (typically over the network by remote frontends).
1660 """
1665 """
1661 from IPython.core.completer import IPCompleter
1666 from IPython.core.completer import IPCompleter
1662 from IPython.core.completerlib import (module_completer,
1667 from IPython.core.completerlib import (module_completer,
1663 magic_run_completer, cd_completer)
1668 magic_run_completer, cd_completer)
1664
1669
1665 self.Completer = IPCompleter(self,
1670 self.Completer = IPCompleter(self,
1666 self.user_ns,
1671 self.user_ns,
1667 self.user_global_ns,
1672 self.user_global_ns,
1668 self.readline_omit__names,
1673 self.readline_omit__names,
1669 self.alias_manager.alias_table,
1674 self.alias_manager.alias_table,
1670 self.has_readline)
1675 self.has_readline)
1671
1676
1672 # Add custom completers to the basic ones built into IPCompleter
1677 # Add custom completers to the basic ones built into IPCompleter
1673 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1678 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1674 self.strdispatchers['complete_command'] = sdisp
1679 self.strdispatchers['complete_command'] = sdisp
1675 self.Completer.custom_completers = sdisp
1680 self.Completer.custom_completers = sdisp
1676
1681
1677 self.set_hook('complete_command', module_completer, str_key = 'import')
1682 self.set_hook('complete_command', module_completer, str_key = 'import')
1678 self.set_hook('complete_command', module_completer, str_key = 'from')
1683 self.set_hook('complete_command', module_completer, str_key = 'from')
1679 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1684 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1680 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1685 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1681
1686
1682 # Only configure readline if we truly are using readline. IPython can
1687 # Only configure readline if we truly are using readline. IPython can
1683 # do tab-completion over the network, in GUIs, etc, where readline
1688 # do tab-completion over the network, in GUIs, etc, where readline
1684 # itself may be absent
1689 # itself may be absent
1685 if self.has_readline:
1690 if self.has_readline:
1686 self.set_readline_completer()
1691 self.set_readline_completer()
1687
1692
1688 def complete(self, text, line=None, cursor_pos=None):
1693 def complete(self, text, line=None, cursor_pos=None):
1689 """Return the completed text and a list of completions.
1694 """Return the completed text and a list of completions.
1690
1695
1691 Parameters
1696 Parameters
1692 ----------
1697 ----------
1693
1698
1694 text : string
1699 text : string
1695 A string of text to be completed on. It can be given as empty and
1700 A string of text to be completed on. It can be given as empty and
1696 instead a line/position pair are given. In this case, the
1701 instead a line/position pair are given. In this case, the
1697 completer itself will split the line like readline does.
1702 completer itself will split the line like readline does.
1698
1703
1699 line : string, optional
1704 line : string, optional
1700 The complete line that text is part of.
1705 The complete line that text is part of.
1701
1706
1702 cursor_pos : int, optional
1707 cursor_pos : int, optional
1703 The position of the cursor on the input line.
1708 The position of the cursor on the input line.
1704
1709
1705 Returns
1710 Returns
1706 -------
1711 -------
1707 text : string
1712 text : string
1708 The actual text that was completed.
1713 The actual text that was completed.
1709
1714
1710 matches : list
1715 matches : list
1711 A sorted list with all possible completions.
1716 A sorted list with all possible completions.
1712
1717
1713 The optional arguments allow the completion to take more context into
1718 The optional arguments allow the completion to take more context into
1714 account, and are part of the low-level completion API.
1719 account, and are part of the low-level completion API.
1715
1720
1716 This is a wrapper around the completion mechanism, similar to what
1721 This is a wrapper around the completion mechanism, similar to what
1717 readline does at the command line when the TAB key is hit. By
1722 readline does at the command line when the TAB key is hit. By
1718 exposing it as a method, it can be used by other non-readline
1723 exposing it as a method, it can be used by other non-readline
1719 environments (such as GUIs) for text completion.
1724 environments (such as GUIs) for text completion.
1720
1725
1721 Simple usage example:
1726 Simple usage example:
1722
1727
1723 In [1]: x = 'hello'
1728 In [1]: x = 'hello'
1724
1729
1725 In [2]: _ip.complete('x.l')
1730 In [2]: _ip.complete('x.l')
1726 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1731 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1727 """
1732 """
1728
1733
1729 # Inject names into __builtin__ so we can complete on the added names.
1734 # Inject names into __builtin__ so we can complete on the added names.
1730 with self.builtin_trap:
1735 with self.builtin_trap:
1731 return self.Completer.complete(text, line, cursor_pos)
1736 return self.Completer.complete(text, line, cursor_pos)
1732
1737
1733 def set_custom_completer(self, completer, pos=0):
1738 def set_custom_completer(self, completer, pos=0):
1734 """Adds a new custom completer function.
1739 """Adds a new custom completer function.
1735
1740
1736 The position argument (defaults to 0) is the index in the completers
1741 The position argument (defaults to 0) is the index in the completers
1737 list where you want the completer to be inserted."""
1742 list where you want the completer to be inserted."""
1738
1743
1739 newcomp = new.instancemethod(completer,self.Completer,
1744 newcomp = new.instancemethod(completer,self.Completer,
1740 self.Completer.__class__)
1745 self.Completer.__class__)
1741 self.Completer.matchers.insert(pos,newcomp)
1746 self.Completer.matchers.insert(pos,newcomp)
1742
1747
1743 def set_readline_completer(self):
1748 def set_readline_completer(self):
1744 """Reset readline's completer to be our own."""
1749 """Reset readline's completer to be our own."""
1745 self.readline.set_completer(self.Completer.rlcomplete)
1750 self.readline.set_completer(self.Completer.rlcomplete)
1746
1751
1747 def set_completer_frame(self, frame=None):
1752 def set_completer_frame(self, frame=None):
1748 """Set the frame of the completer."""
1753 """Set the frame of the completer."""
1749 if frame:
1754 if frame:
1750 self.Completer.namespace = frame.f_locals
1755 self.Completer.namespace = frame.f_locals
1751 self.Completer.global_namespace = frame.f_globals
1756 self.Completer.global_namespace = frame.f_globals
1752 else:
1757 else:
1753 self.Completer.namespace = self.user_ns
1758 self.Completer.namespace = self.user_ns
1754 self.Completer.global_namespace = self.user_global_ns
1759 self.Completer.global_namespace = self.user_global_ns
1755
1760
1756 #-------------------------------------------------------------------------
1761 #-------------------------------------------------------------------------
1757 # Things related to magics
1762 # Things related to magics
1758 #-------------------------------------------------------------------------
1763 #-------------------------------------------------------------------------
1759
1764
1760 def init_magics(self):
1765 def init_magics(self):
1761 # FIXME: Move the color initialization to the DisplayHook, which
1766 # FIXME: Move the color initialization to the DisplayHook, which
1762 # should be split into a prompt manager and displayhook. We probably
1767 # should be split into a prompt manager and displayhook. We probably
1763 # even need a centralize colors management object.
1768 # even need a centralize colors management object.
1764 self.magic_colors(self.colors)
1769 self.magic_colors(self.colors)
1765 # History was moved to a separate module
1770 # History was moved to a separate module
1766 from . import history
1771 from . import history
1767 history.init_ipython(self)
1772 history.init_ipython(self)
1768
1773
1769 def magic(self,arg_s):
1774 def magic(self,arg_s):
1770 """Call a magic function by name.
1775 """Call a magic function by name.
1771
1776
1772 Input: a string containing the name of the magic function to call and
1777 Input: a string containing the name of the magic function to call and
1773 any additional arguments to be passed to the magic.
1778 any additional arguments to be passed to the magic.
1774
1779
1775 magic('name -opt foo bar') is equivalent to typing at the ipython
1780 magic('name -opt foo bar') is equivalent to typing at the ipython
1776 prompt:
1781 prompt:
1777
1782
1778 In[1]: %name -opt foo bar
1783 In[1]: %name -opt foo bar
1779
1784
1780 To call a magic without arguments, simply use magic('name').
1785 To call a magic without arguments, simply use magic('name').
1781
1786
1782 This provides a proper Python function to call IPython's magics in any
1787 This provides a proper Python function to call IPython's magics in any
1783 valid Python code you can type at the interpreter, including loops and
1788 valid Python code you can type at the interpreter, including loops and
1784 compound statements.
1789 compound statements.
1785 """
1790 """
1786 args = arg_s.split(' ',1)
1791 args = arg_s.split(' ',1)
1787 magic_name = args[0]
1792 magic_name = args[0]
1788 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1793 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1789
1794
1790 try:
1795 try:
1791 magic_args = args[1]
1796 magic_args = args[1]
1792 except IndexError:
1797 except IndexError:
1793 magic_args = ''
1798 magic_args = ''
1794 fn = getattr(self,'magic_'+magic_name,None)
1799 fn = getattr(self,'magic_'+magic_name,None)
1795 if fn is None:
1800 if fn is None:
1796 error("Magic function `%s` not found." % magic_name)
1801 error("Magic function `%s` not found." % magic_name)
1797 else:
1802 else:
1798 magic_args = self.var_expand(magic_args,1)
1803 magic_args = self.var_expand(magic_args,1)
1799 with nested(self.builtin_trap,):
1804 with nested(self.builtin_trap,):
1800 result = fn(magic_args)
1805 result = fn(magic_args)
1801 return result
1806 return result
1802
1807
1803 def define_magic(self, magicname, func):
1808 def define_magic(self, magicname, func):
1804 """Expose own function as magic function for ipython
1809 """Expose own function as magic function for ipython
1805
1810
1806 def foo_impl(self,parameter_s=''):
1811 def foo_impl(self,parameter_s=''):
1807 'My very own magic!. (Use docstrings, IPython reads them).'
1812 'My very own magic!. (Use docstrings, IPython reads them).'
1808 print 'Magic function. Passed parameter is between < >:'
1813 print 'Magic function. Passed parameter is between < >:'
1809 print '<%s>' % parameter_s
1814 print '<%s>' % parameter_s
1810 print 'The self object is:',self
1815 print 'The self object is:',self
1811
1816
1812 self.define_magic('foo',foo_impl)
1817 self.define_magic('foo',foo_impl)
1813 """
1818 """
1814
1819
1815 import new
1820 import new
1816 im = new.instancemethod(func,self, self.__class__)
1821 im = new.instancemethod(func,self, self.__class__)
1817 old = getattr(self, "magic_" + magicname, None)
1822 old = getattr(self, "magic_" + magicname, None)
1818 setattr(self, "magic_" + magicname, im)
1823 setattr(self, "magic_" + magicname, im)
1819 return old
1824 return old
1820
1825
1821 #-------------------------------------------------------------------------
1826 #-------------------------------------------------------------------------
1822 # Things related to macros
1827 # Things related to macros
1823 #-------------------------------------------------------------------------
1828 #-------------------------------------------------------------------------
1824
1829
1825 def define_macro(self, name, themacro):
1830 def define_macro(self, name, themacro):
1826 """Define a new macro
1831 """Define a new macro
1827
1832
1828 Parameters
1833 Parameters
1829 ----------
1834 ----------
1830 name : str
1835 name : str
1831 The name of the macro.
1836 The name of the macro.
1832 themacro : str or Macro
1837 themacro : str or Macro
1833 The action to do upon invoking the macro. If a string, a new
1838 The action to do upon invoking the macro. If a string, a new
1834 Macro object is created by passing the string to it.
1839 Macro object is created by passing the string to it.
1835 """
1840 """
1836
1841
1837 from IPython.core import macro
1842 from IPython.core import macro
1838
1843
1839 if isinstance(themacro, basestring):
1844 if isinstance(themacro, basestring):
1840 themacro = macro.Macro(themacro)
1845 themacro = macro.Macro(themacro)
1841 if not isinstance(themacro, macro.Macro):
1846 if not isinstance(themacro, macro.Macro):
1842 raise ValueError('A macro must be a string or a Macro instance.')
1847 raise ValueError('A macro must be a string or a Macro instance.')
1843 self.user_ns[name] = themacro
1848 self.user_ns[name] = themacro
1844
1849
1845 #-------------------------------------------------------------------------
1850 #-------------------------------------------------------------------------
1846 # Things related to the running of system commands
1851 # Things related to the running of system commands
1847 #-------------------------------------------------------------------------
1852 #-------------------------------------------------------------------------
1848
1853
1849 def system(self, cmd):
1854 def system(self, cmd):
1850 """Call the given cmd in a subprocess.
1855 """Call the given cmd in a subprocess.
1851
1856
1852 Parameters
1857 Parameters
1853 ----------
1858 ----------
1854 cmd : str
1859 cmd : str
1855 Command to execute (can not end in '&', as bacground processes are
1860 Command to execute (can not end in '&', as bacground processes are
1856 not supported.
1861 not supported.
1857 """
1862 """
1858 # We do not support backgrounding processes because we either use
1863 # We do not support backgrounding processes because we either use
1859 # pexpect or pipes to read from. Users can always just call
1864 # pexpect or pipes to read from. Users can always just call
1860 # os.system() if they really want a background process.
1865 # os.system() if they really want a background process.
1861 if cmd.endswith('&'):
1866 if cmd.endswith('&'):
1862 raise OSError("Background processes not supported.")
1867 raise OSError("Background processes not supported.")
1863
1868
1864 return system(self.var_expand(cmd, depth=2))
1869 return system(self.var_expand(cmd, depth=2))
1865
1870
1866 def getoutput(self, cmd, split=True):
1871 def getoutput(self, cmd, split=True):
1867 """Get output (possibly including stderr) from a subprocess.
1872 """Get output (possibly including stderr) from a subprocess.
1868
1873
1869 Parameters
1874 Parameters
1870 ----------
1875 ----------
1871 cmd : str
1876 cmd : str
1872 Command to execute (can not end in '&', as bacground processes are
1877 Command to execute (can not end in '&', as background processes are
1873 not supported.
1878 not supported.
1874 split : bool, optional
1879 split : bool, optional
1875
1880
1876 If True, split the output into an IPython SList. Otherwise, an
1881 If True, split the output into an IPython SList. Otherwise, an
1877 IPython LSString is returned. These are objects similar to normal
1882 IPython LSString is returned. These are objects similar to normal
1878 lists and strings, with a few convenience attributes for easier
1883 lists and strings, with a few convenience attributes for easier
1879 manipulation of line-based output. You can use '?' on them for
1884 manipulation of line-based output. You can use '?' on them for
1880 details.
1885 details.
1881 """
1886 """
1882 if cmd.endswith('&'):
1887 if cmd.endswith('&'):
1883 raise OSError("Background processes not supported.")
1888 raise OSError("Background processes not supported.")
1884 out = getoutput(self.var_expand(cmd, depth=2))
1889 out = getoutput(self.var_expand(cmd, depth=2))
1885 if split:
1890 if split:
1886 out = SList(out.splitlines())
1891 out = SList(out.splitlines())
1887 else:
1892 else:
1888 out = LSString(out)
1893 out = LSString(out)
1889 return out
1894 return out
1890
1895
1891 #-------------------------------------------------------------------------
1896 #-------------------------------------------------------------------------
1892 # Things related to aliases
1897 # Things related to aliases
1893 #-------------------------------------------------------------------------
1898 #-------------------------------------------------------------------------
1894
1899
1895 def init_alias(self):
1900 def init_alias(self):
1896 self.alias_manager = AliasManager(shell=self, config=self.config)
1901 self.alias_manager = AliasManager(shell=self, config=self.config)
1897 self.ns_table['alias'] = self.alias_manager.alias_table,
1902 self.ns_table['alias'] = self.alias_manager.alias_table,
1898
1903
1899 #-------------------------------------------------------------------------
1904 #-------------------------------------------------------------------------
1900 # Things related to extensions and plugins
1905 # Things related to extensions and plugins
1901 #-------------------------------------------------------------------------
1906 #-------------------------------------------------------------------------
1902
1907
1903 def init_extension_manager(self):
1908 def init_extension_manager(self):
1904 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1909 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1905
1910
1906 def init_plugin_manager(self):
1911 def init_plugin_manager(self):
1907 self.plugin_manager = PluginManager(config=self.config)
1912 self.plugin_manager = PluginManager(config=self.config)
1908
1913
1909 #-------------------------------------------------------------------------
1914 #-------------------------------------------------------------------------
1910 # Things related to payloads
1915 # Things related to payloads
1911 #-------------------------------------------------------------------------
1916 #-------------------------------------------------------------------------
1912
1917
1913 def init_payload(self):
1918 def init_payload(self):
1914 self.payload_manager = PayloadManager(config=self.config)
1919 self.payload_manager = PayloadManager(config=self.config)
1915
1920
1916 #-------------------------------------------------------------------------
1921 #-------------------------------------------------------------------------
1917 # Things related to the prefilter
1922 # Things related to the prefilter
1918 #-------------------------------------------------------------------------
1923 #-------------------------------------------------------------------------
1919
1924
1920 def init_prefilter(self):
1925 def init_prefilter(self):
1921 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1926 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1922 # Ultimately this will be refactored in the new interpreter code, but
1927 # Ultimately this will be refactored in the new interpreter code, but
1923 # for now, we should expose the main prefilter method (there's legacy
1928 # for now, we should expose the main prefilter method (there's legacy
1924 # code out there that may rely on this).
1929 # code out there that may rely on this).
1925 self.prefilter = self.prefilter_manager.prefilter_lines
1930 self.prefilter = self.prefilter_manager.prefilter_lines
1926
1931
1927
1932
1928 def auto_rewrite_input(self, cmd):
1933 def auto_rewrite_input(self, cmd):
1929 """Print to the screen the rewritten form of the user's command.
1934 """Print to the screen the rewritten form of the user's command.
1930
1935
1931 This shows visual feedback by rewriting input lines that cause
1936 This shows visual feedback by rewriting input lines that cause
1932 automatic calling to kick in, like::
1937 automatic calling to kick in, like::
1933
1938
1934 /f x
1939 /f x
1935
1940
1936 into::
1941 into::
1937
1942
1938 ------> f(x)
1943 ------> f(x)
1939
1944
1940 after the user's input prompt. This helps the user understand that the
1945 after the user's input prompt. This helps the user understand that the
1941 input line was transformed automatically by IPython.
1946 input line was transformed automatically by IPython.
1942 """
1947 """
1943 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1948 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1944
1949
1945 try:
1950 try:
1946 # plain ascii works better w/ pyreadline, on some machines, so
1951 # plain ascii works better w/ pyreadline, on some machines, so
1947 # we use it and only print uncolored rewrite if we have unicode
1952 # we use it and only print uncolored rewrite if we have unicode
1948 rw = str(rw)
1953 rw = str(rw)
1949 print >> IPython.utils.io.Term.cout, rw
1954 print >> IPython.utils.io.Term.cout, rw
1950 except UnicodeEncodeError:
1955 except UnicodeEncodeError:
1951 print "------> " + cmd
1956 print "------> " + cmd
1952
1957
1953 #-------------------------------------------------------------------------
1958 #-------------------------------------------------------------------------
1954 # Things related to extracting values/expressions from kernel and user_ns
1959 # Things related to extracting values/expressions from kernel and user_ns
1955 #-------------------------------------------------------------------------
1960 #-------------------------------------------------------------------------
1956
1961
1957 def _simple_error(self):
1962 def _simple_error(self):
1958 etype, value = sys.exc_info()[:2]
1963 etype, value = sys.exc_info()[:2]
1959 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1964 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1960
1965
1961 def get_user_variables(self, names):
1966 def get_user_variables(self, names):
1962 """Get a list of variable names from the user's namespace.
1967 """Get a list of variable names from the user's namespace.
1963
1968
1964 The return value is a dict with the repr() of each value.
1969 The return value is a dict with the repr() of each value.
1965 """
1970 """
1966 out = {}
1971 out = {}
1967 user_ns = self.user_ns
1972 user_ns = self.user_ns
1968 for varname in names:
1973 for varname in names:
1969 try:
1974 try:
1970 value = repr(user_ns[varname])
1975 value = repr(user_ns[varname])
1971 except:
1976 except:
1972 value = self._simple_error()
1977 value = self._simple_error()
1973 out[varname] = value
1978 out[varname] = value
1974 return out
1979 return out
1975
1980
1976 def eval_expressions(self, expressions):
1981 def eval_expressions(self, expressions):
1977 """Evaluate a dict of expressions in the user's namespace.
1982 """Evaluate a dict of expressions in the user's namespace.
1978
1983
1979 The return value is a dict with the repr() of each value.
1984 The return value is a dict with the repr() of each value.
1980 """
1985 """
1981 out = {}
1986 out = {}
1982 user_ns = self.user_ns
1987 user_ns = self.user_ns
1983 global_ns = self.user_global_ns
1988 global_ns = self.user_global_ns
1984 for key, expr in expressions.iteritems():
1989 for key, expr in expressions.iteritems():
1985 try:
1990 try:
1986 value = repr(eval(expr, global_ns, user_ns))
1991 value = repr(eval(expr, global_ns, user_ns))
1987 except:
1992 except:
1988 value = self._simple_error()
1993 value = self._simple_error()
1989 out[key] = value
1994 out[key] = value
1990 return out
1995 return out
1991
1996
1992 #-------------------------------------------------------------------------
1997 #-------------------------------------------------------------------------
1993 # Things related to the running of code
1998 # Things related to the running of code
1994 #-------------------------------------------------------------------------
1999 #-------------------------------------------------------------------------
1995
2000
1996 def ex(self, cmd):
2001 def ex(self, cmd):
1997 """Execute a normal python statement in user namespace."""
2002 """Execute a normal python statement in user namespace."""
1998 with nested(self.builtin_trap,):
2003 with nested(self.builtin_trap,):
1999 exec cmd in self.user_global_ns, self.user_ns
2004 exec cmd in self.user_global_ns, self.user_ns
2000
2005
2001 def ev(self, expr):
2006 def ev(self, expr):
2002 """Evaluate python expression expr in user namespace.
2007 """Evaluate python expression expr in user namespace.
2003
2008
2004 Returns the result of evaluation
2009 Returns the result of evaluation
2005 """
2010 """
2006 with nested(self.builtin_trap,):
2011 with nested(self.builtin_trap,):
2007 return eval(expr, self.user_global_ns, self.user_ns)
2012 return eval(expr, self.user_global_ns, self.user_ns)
2008
2013
2009 def safe_execfile(self, fname, *where, **kw):
2014 def safe_execfile(self, fname, *where, **kw):
2010 """A safe version of the builtin execfile().
2015 """A safe version of the builtin execfile().
2011
2016
2012 This version will never throw an exception, but instead print
2017 This version will never throw an exception, but instead print
2013 helpful error messages to the screen. This only works on pure
2018 helpful error messages to the screen. This only works on pure
2014 Python files with the .py extension.
2019 Python files with the .py extension.
2015
2020
2016 Parameters
2021 Parameters
2017 ----------
2022 ----------
2018 fname : string
2023 fname : string
2019 The name of the file to be executed.
2024 The name of the file to be executed.
2020 where : tuple
2025 where : tuple
2021 One or two namespaces, passed to execfile() as (globals,locals).
2026 One or two namespaces, passed to execfile() as (globals,locals).
2022 If only one is given, it is passed as both.
2027 If only one is given, it is passed as both.
2023 exit_ignore : bool (False)
2028 exit_ignore : bool (False)
2024 If True, then silence SystemExit for non-zero status (it is always
2029 If True, then silence SystemExit for non-zero status (it is always
2025 silenced for zero status, as it is so common).
2030 silenced for zero status, as it is so common).
2026 """
2031 """
2027 kw.setdefault('exit_ignore', False)
2032 kw.setdefault('exit_ignore', False)
2028
2033
2029 fname = os.path.abspath(os.path.expanduser(fname))
2034 fname = os.path.abspath(os.path.expanduser(fname))
2030
2035
2031 # Make sure we have a .py file
2036 # Make sure we have a .py file
2032 if not fname.endswith('.py'):
2037 if not fname.endswith('.py'):
2033 warn('File must end with .py to be run using execfile: <%s>' % fname)
2038 warn('File must end with .py to be run using execfile: <%s>' % fname)
2034
2039
2035 # Make sure we can open the file
2040 # Make sure we can open the file
2036 try:
2041 try:
2037 with open(fname) as thefile:
2042 with open(fname) as thefile:
2038 pass
2043 pass
2039 except:
2044 except:
2040 warn('Could not open file <%s> for safe execution.' % fname)
2045 warn('Could not open file <%s> for safe execution.' % fname)
2041 return
2046 return
2042
2047
2043 # Find things also in current directory. This is needed to mimic the
2048 # Find things also in current directory. This is needed to mimic the
2044 # behavior of running a script from the system command line, where
2049 # behavior of running a script from the system command line, where
2045 # Python inserts the script's directory into sys.path
2050 # Python inserts the script's directory into sys.path
2046 dname = os.path.dirname(fname)
2051 dname = os.path.dirname(fname)
2047
2052
2048 with prepended_to_syspath(dname):
2053 with prepended_to_syspath(dname):
2049 try:
2054 try:
2050 execfile(fname,*where)
2055 execfile(fname,*where)
2051 except SystemExit, status:
2056 except SystemExit, status:
2052 # If the call was made with 0 or None exit status (sys.exit(0)
2057 # If the call was made with 0 or None exit status (sys.exit(0)
2053 # or sys.exit() ), don't bother showing a traceback, as both of
2058 # or sys.exit() ), don't bother showing a traceback, as both of
2054 # these are considered normal by the OS:
2059 # these are considered normal by the OS:
2055 # > python -c'import sys;sys.exit(0)'; echo $?
2060 # > python -c'import sys;sys.exit(0)'; echo $?
2056 # 0
2061 # 0
2057 # > python -c'import sys;sys.exit()'; echo $?
2062 # > python -c'import sys;sys.exit()'; echo $?
2058 # 0
2063 # 0
2059 # For other exit status, we show the exception unless
2064 # For other exit status, we show the exception unless
2060 # explicitly silenced, but only in short form.
2065 # explicitly silenced, but only in short form.
2061 if status.code not in (0, None) and not kw['exit_ignore']:
2066 if status.code not in (0, None) and not kw['exit_ignore']:
2062 self.showtraceback(exception_only=True)
2067 self.showtraceback(exception_only=True)
2063 except:
2068 except:
2064 self.showtraceback()
2069 self.showtraceback()
2065
2070
2066 def safe_execfile_ipy(self, fname):
2071 def safe_execfile_ipy(self, fname):
2067 """Like safe_execfile, but for .ipy files with IPython syntax.
2072 """Like safe_execfile, but for .ipy files with IPython syntax.
2068
2073
2069 Parameters
2074 Parameters
2070 ----------
2075 ----------
2071 fname : str
2076 fname : str
2072 The name of the file to execute. The filename must have a
2077 The name of the file to execute. The filename must have a
2073 .ipy extension.
2078 .ipy extension.
2074 """
2079 """
2075 fname = os.path.abspath(os.path.expanduser(fname))
2080 fname = os.path.abspath(os.path.expanduser(fname))
2076
2081
2077 # Make sure we have a .py file
2082 # Make sure we have a .py file
2078 if not fname.endswith('.ipy'):
2083 if not fname.endswith('.ipy'):
2079 warn('File must end with .py to be run using execfile: <%s>' % fname)
2084 warn('File must end with .py to be run using execfile: <%s>' % fname)
2080
2085
2081 # Make sure we can open the file
2086 # Make sure we can open the file
2082 try:
2087 try:
2083 with open(fname) as thefile:
2088 with open(fname) as thefile:
2084 pass
2089 pass
2085 except:
2090 except:
2086 warn('Could not open file <%s> for safe execution.' % fname)
2091 warn('Could not open file <%s> for safe execution.' % fname)
2087 return
2092 return
2088
2093
2089 # Find things also in current directory. This is needed to mimic the
2094 # Find things also in current directory. This is needed to mimic the
2090 # behavior of running a script from the system command line, where
2095 # behavior of running a script from the system command line, where
2091 # Python inserts the script's directory into sys.path
2096 # Python inserts the script's directory into sys.path
2092 dname = os.path.dirname(fname)
2097 dname = os.path.dirname(fname)
2093
2098
2094 with prepended_to_syspath(dname):
2099 with prepended_to_syspath(dname):
2095 try:
2100 try:
2096 with open(fname) as thefile:
2101 with open(fname) as thefile:
2097 script = thefile.read()
2102 script = thefile.read()
2098 # self.runlines currently captures all exceptions
2103 # self.runlines currently captures all exceptions
2099 # raise in user code. It would be nice if there were
2104 # raise in user code. It would be nice if there were
2100 # versions of runlines, execfile that did raise, so
2105 # versions of runlines, execfile that did raise, so
2101 # we could catch the errors.
2106 # we could catch the errors.
2102 self.runlines(script, clean=True)
2107 self.runlines(script, clean=True)
2103 except:
2108 except:
2104 self.showtraceback()
2109 self.showtraceback()
2105 warn('Unknown failure executing file: <%s>' % fname)
2110 warn('Unknown failure executing file: <%s>' % fname)
2106
2111
2107 def run_cell(self, cell):
2112 def run_cell(self, cell):
2108 """Run the contents of an entire multiline 'cell' of code.
2113 """Run the contents of an entire multiline 'cell' of code.
2109
2114
2110 The cell is split into separate blocks which can be executed
2115 The cell is split into separate blocks which can be executed
2111 individually. Then, based on how many blocks there are, they are
2116 individually. Then, based on how many blocks there are, they are
2112 executed as follows:
2117 executed as follows:
2113
2118
2114 - A single block: 'single' mode.
2119 - A single block: 'single' mode.
2115
2120
2116 If there's more than one block, it depends:
2121 If there's more than one block, it depends:
2117
2122
2118 - if the last one is a single line long, run all but the last in
2123 - if the last one is a single line long, run all but the last in
2119 'exec' mode and the very last one in 'single' mode. This makes it
2124 'exec' mode and the very last one in 'single' mode. This makes it
2120 easy to type simple expressions at the end to see computed values.
2125 easy to type simple expressions at the end to see computed values.
2121 - otherwise (last one is also multiline), run all in 'exec' mode
2126 - otherwise (last one is also multiline), run all in 'exec' mode
2122
2127
2123 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2128 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2124 results are displayed and output prompts are computed. In 'exec' mode,
2129 results are displayed and output prompts are computed. In 'exec' mode,
2125 no results are displayed unless :func:`print` is called explicitly;
2130 no results are displayed unless :func:`print` is called explicitly;
2126 this mode is more akin to running a script.
2131 this mode is more akin to running a script.
2127
2132
2128 Parameters
2133 Parameters
2129 ----------
2134 ----------
2130 cell : str
2135 cell : str
2131 A single or multiline string.
2136 A single or multiline string.
2132 """
2137 """
2133 # We need to break up the input into executable blocks that can be run
2138 # We need to break up the input into executable blocks that can be run
2134 # in 'single' mode, to provide comfortable user behavior.
2139 # in 'single' mode, to provide comfortable user behavior.
2135 blocks = self.input_splitter.split_blocks(cell)
2140 blocks = self.input_splitter.split_blocks(cell)
2136
2141
2137 if not blocks:
2142 if not blocks:
2138 return
2143 return
2139
2144
2140 # Single-block input should behave like an interactive prompt
2145 # Single-block input should behave like an interactive prompt
2141 if len(blocks) == 1:
2146 if len(blocks) == 1:
2142 self.runlines(blocks[0])
2147 self.runlines(blocks[0])
2143 return
2148 return
2144
2149
2145 # In multi-block input, if the last block is a simple (one-two lines)
2150 # In multi-block input, if the last block is a simple (one-two lines)
2146 # expression, run it in single mode so it produces output. Otherwise
2151 # expression, run it in single mode so it produces output. Otherwise
2147 # just feed the whole thing to runcode.
2152 # just feed the whole thing to runcode.
2148 # This seems like a reasonable usability design.
2153 # This seems like a reasonable usability design.
2149 last = blocks[-1]
2154 last = blocks[-1]
2150
2155
2151 # Note: below, whenever we call runcode, we must sync history
2156 # Note: below, whenever we call runcode, we must sync history
2152 # ourselves, because runcode is NOT meant to manage history at all.
2157 # ourselves, because runcode is NOT meant to manage history at all.
2153 if len(last.splitlines()) < 2:
2158 if len(last.splitlines()) < 2:
2154 # Get the main body to run as a cell
2159 # Get the main body to run as a cell
2155 body = ''.join(blocks[:-1])
2160 body = ''.join(blocks[:-1])
2156 self.input_hist.append(body)
2161 self.input_hist.append(body)
2157 self.input_hist_raw.append(body)
2162 self.input_hist_raw.append(body)
2158 self.runcode(body, post_execute=False)
2163 self.runcode(body, post_execute=False)
2159 # And the last expression via runlines so it produces output
2164 # And the last expression via runlines so it produces output
2160 self.runlines(last)
2165 self.runlines(last)
2161 else:
2166 else:
2162 # Run the whole cell as one entity
2167 # Run the whole cell as one entity
2163 self.input_hist.append(cell)
2168 self.input_hist.append(cell)
2164 self.input_hist_raw.append(cell)
2169 self.input_hist_raw.append(cell)
2165 self.runcode(cell)
2170 self.runcode(cell)
2166
2171
2167 def runlines(self, lines, clean=False):
2172 def runlines(self, lines, clean=False):
2168 """Run a string of one or more lines of source.
2173 """Run a string of one or more lines of source.
2169
2174
2170 This method is capable of running a string containing multiple source
2175 This method is capable of running a string containing multiple source
2171 lines, as if they had been entered at the IPython prompt. Since it
2176 lines, as if they had been entered at the IPython prompt. Since it
2172 exposes IPython's processing machinery, the given strings can contain
2177 exposes IPython's processing machinery, the given strings can contain
2173 magic calls (%magic), special shell access (!cmd), etc.
2178 magic calls (%magic), special shell access (!cmd), etc.
2174 """
2179 """
2175
2180
2176 if isinstance(lines, (list, tuple)):
2181 if isinstance(lines, (list, tuple)):
2177 lines = '\n'.join(lines)
2182 lines = '\n'.join(lines)
2178
2183
2179 if clean:
2184 if clean:
2180 lines = self._cleanup_ipy_script(lines)
2185 lines = self._cleanup_ipy_script(lines)
2181
2186
2182 # We must start with a clean buffer, in case this is run from an
2187 # We must start with a clean buffer, in case this is run from an
2183 # interactive IPython session (via a magic, for example).
2188 # interactive IPython session (via a magic, for example).
2184 self.resetbuffer()
2189 self.resetbuffer()
2185 lines = lines.splitlines()
2190 lines = lines.splitlines()
2186 more = 0
2191 more = 0
2187 with nested(self.builtin_trap, self.display_trap):
2192 with nested(self.builtin_trap, self.display_trap):
2188 for line in lines:
2193 for line in lines:
2189 # skip blank lines so we don't mess up the prompt counter, but
2194 # skip blank lines so we don't mess up the prompt counter, but
2190 # do NOT skip even a blank line if we are in a code block (more
2195 # do NOT skip even a blank line if we are in a code block (more
2191 # is true)
2196 # is true)
2192
2197
2193 if line or more:
2198 if line or more:
2194 # push to raw history, so hist line numbers stay in sync
2199 # push to raw history, so hist line numbers stay in sync
2195 self.input_hist_raw.append(line + '\n')
2200 self.input_hist_raw.append(line + '\n')
2196 prefiltered = self.prefilter_manager.prefilter_lines(line,
2201 prefiltered = self.prefilter_manager.prefilter_lines(line,
2197 more)
2202 more)
2198 more = self.push_line(prefiltered)
2203 more = self.push_line(prefiltered)
2199 # IPython's runsource returns None if there was an error
2204 # IPython's runsource returns None if there was an error
2200 # compiling the code. This allows us to stop processing
2205 # compiling the code. This allows us to stop processing
2201 # right away, so the user gets the error message at the
2206 # right away, so the user gets the error message at the
2202 # right place.
2207 # right place.
2203 if more is None:
2208 if more is None:
2204 break
2209 break
2205 else:
2210 else:
2206 self.input_hist_raw.append("\n")
2211 self.input_hist_raw.append("\n")
2207 # final newline in case the input didn't have it, so that the code
2212 # final newline in case the input didn't have it, so that the code
2208 # actually does get executed
2213 # actually does get executed
2209 if more:
2214 if more:
2210 self.push_line('\n')
2215 self.push_line('\n')
2211
2216
2212 def runsource(self, source, filename='<input>', symbol='single'):
2217 def runsource(self, source, filename='<input>', symbol='single'):
2213 """Compile and run some source in the interpreter.
2218 """Compile and run some source in the interpreter.
2214
2219
2215 Arguments are as for compile_command().
2220 Arguments are as for compile_command().
2216
2221
2217 One several things can happen:
2222 One several things can happen:
2218
2223
2219 1) The input is incorrect; compile_command() raised an
2224 1) The input is incorrect; compile_command() raised an
2220 exception (SyntaxError or OverflowError). A syntax traceback
2225 exception (SyntaxError or OverflowError). A syntax traceback
2221 will be printed by calling the showsyntaxerror() method.
2226 will be printed by calling the showsyntaxerror() method.
2222
2227
2223 2) The input is incomplete, and more input is required;
2228 2) The input is incomplete, and more input is required;
2224 compile_command() returned None. Nothing happens.
2229 compile_command() returned None. Nothing happens.
2225
2230
2226 3) The input is complete; compile_command() returned a code
2231 3) The input is complete; compile_command() returned a code
2227 object. The code is executed by calling self.runcode() (which
2232 object. The code is executed by calling self.runcode() (which
2228 also handles run-time exceptions, except for SystemExit).
2233 also handles run-time exceptions, except for SystemExit).
2229
2234
2230 The return value is:
2235 The return value is:
2231
2236
2232 - True in case 2
2237 - True in case 2
2233
2238
2234 - False in the other cases, unless an exception is raised, where
2239 - False in the other cases, unless an exception is raised, where
2235 None is returned instead. This can be used by external callers to
2240 None is returned instead. This can be used by external callers to
2236 know whether to continue feeding input or not.
2241 know whether to continue feeding input or not.
2237
2242
2238 The return value can be used to decide whether to use sys.ps1 or
2243 The return value can be used to decide whether to use sys.ps1 or
2239 sys.ps2 to prompt the next line."""
2244 sys.ps2 to prompt the next line."""
2240
2245
2241 # if the source code has leading blanks, add 'if 1:\n' to it
2246 # if the source code has leading blanks, add 'if 1:\n' to it
2242 # this allows execution of indented pasted code. It is tempting
2247 # this allows execution of indented pasted code. It is tempting
2243 # to add '\n' at the end of source to run commands like ' a=1'
2248 # to add '\n' at the end of source to run commands like ' a=1'
2244 # directly, but this fails for more complicated scenarios
2249 # directly, but this fails for more complicated scenarios
2245 source=source.encode(self.stdin_encoding)
2250 source=source.encode(self.stdin_encoding)
2246 if source[:1] in [' ', '\t']:
2251 if source[:1] in [' ', '\t']:
2247 source = 'if 1:\n%s' % source
2252 source = 'if 1:\n%s' % source
2248
2253
2249 try:
2254 try:
2250 code = self.compile(source,filename,symbol)
2255 code = self.compile(source,filename,symbol)
2251 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2256 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2252 # Case 1
2257 # Case 1
2253 self.showsyntaxerror(filename)
2258 self.showsyntaxerror(filename)
2254 return None
2259 return None
2255
2260
2256 if code is None:
2261 if code is None:
2257 # Case 2
2262 # Case 2
2258 return True
2263 return True
2259
2264
2260 # Case 3
2265 # Case 3
2261 # We store the code object so that threaded shells and
2266 # We store the code object so that threaded shells and
2262 # custom exception handlers can access all this info if needed.
2267 # custom exception handlers can access all this info if needed.
2263 # The source corresponding to this can be obtained from the
2268 # The source corresponding to this can be obtained from the
2264 # buffer attribute as '\n'.join(self.buffer).
2269 # buffer attribute as '\n'.join(self.buffer).
2265 self.code_to_run = code
2270 self.code_to_run = code
2266 # now actually execute the code object
2271 # now actually execute the code object
2267 if self.runcode(code) == 0:
2272 if self.runcode(code) == 0:
2268 return False
2273 return False
2269 else:
2274 else:
2270 return None
2275 return None
2271
2276
2272 def runcode(self, code_obj, post_execute=True):
2277 def runcode(self, code_obj, post_execute=True):
2273 """Execute a code object.
2278 """Execute a code object.
2274
2279
2275 When an exception occurs, self.showtraceback() is called to display a
2280 When an exception occurs, self.showtraceback() is called to display a
2276 traceback.
2281 traceback.
2277
2282
2278 Return value: a flag indicating whether the code to be run completed
2283 Return value: a flag indicating whether the code to be run completed
2279 successfully:
2284 successfully:
2280
2285
2281 - 0: successful execution.
2286 - 0: successful execution.
2282 - 1: an error occurred.
2287 - 1: an error occurred.
2283 """
2288 """
2284
2289
2285 # Set our own excepthook in case the user code tries to call it
2290 # Set our own excepthook in case the user code tries to call it
2286 # directly, so that the IPython crash handler doesn't get triggered
2291 # directly, so that the IPython crash handler doesn't get triggered
2287 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2292 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2288
2293
2289 # we save the original sys.excepthook in the instance, in case config
2294 # we save the original sys.excepthook in the instance, in case config
2290 # code (such as magics) needs access to it.
2295 # code (such as magics) needs access to it.
2291 self.sys_excepthook = old_excepthook
2296 self.sys_excepthook = old_excepthook
2292 outflag = 1 # happens in more places, so it's easier as default
2297 outflag = 1 # happens in more places, so it's easier as default
2293 try:
2298 try:
2294 try:
2299 try:
2295 self.hooks.pre_runcode_hook()
2300 self.hooks.pre_runcode_hook()
2296 #rprint('Running code') # dbg
2301 #rprint('Running code') # dbg
2297 exec code_obj in self.user_global_ns, self.user_ns
2302 exec code_obj in self.user_global_ns, self.user_ns
2298 finally:
2303 finally:
2299 # Reset our crash handler in place
2304 # Reset our crash handler in place
2300 sys.excepthook = old_excepthook
2305 sys.excepthook = old_excepthook
2301 except SystemExit:
2306 except SystemExit:
2302 self.resetbuffer()
2307 self.resetbuffer()
2303 self.showtraceback(exception_only=True)
2308 self.showtraceback(exception_only=True)
2304 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2309 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2305 except self.custom_exceptions:
2310 except self.custom_exceptions:
2306 etype,value,tb = sys.exc_info()
2311 etype,value,tb = sys.exc_info()
2307 self.CustomTB(etype,value,tb)
2312 self.CustomTB(etype,value,tb)
2308 except:
2313 except:
2309 self.showtraceback()
2314 self.showtraceback()
2310 else:
2315 else:
2311 outflag = 0
2316 outflag = 0
2312 if softspace(sys.stdout, 0):
2317 if softspace(sys.stdout, 0):
2313 print
2318 print
2314
2319
2315 # Execute any registered post-execution functions. Here, any errors
2320 # Execute any registered post-execution functions. Here, any errors
2316 # are reported only minimally and just on the terminal, because the
2321 # are reported only minimally and just on the terminal, because the
2317 # main exception channel may be occupied with a user traceback.
2322 # main exception channel may be occupied with a user traceback.
2318 # FIXME: we need to think this mechanism a little more carefully.
2323 # FIXME: we need to think this mechanism a little more carefully.
2319 if post_execute:
2324 if post_execute:
2320 for func in self._post_execute:
2325 for func in self._post_execute:
2321 try:
2326 try:
2322 func()
2327 func()
2323 except:
2328 except:
2324 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2329 head = '[ ERROR ] Evaluating post_execute function: %s' % \
2325 func
2330 func
2326 print >> io.Term.cout, head
2331 print >> io.Term.cout, head
2327 print >> io.Term.cout, self._simple_error()
2332 print >> io.Term.cout, self._simple_error()
2328 print >> io.Term.cout, 'Removing from post_execute'
2333 print >> io.Term.cout, 'Removing from post_execute'
2329 self._post_execute.remove(func)
2334 self._post_execute.remove(func)
2330
2335
2331 # Flush out code object which has been run (and source)
2336 # Flush out code object which has been run (and source)
2332 self.code_to_run = None
2337 self.code_to_run = None
2333 return outflag
2338 return outflag
2334
2339
2335 def push_line(self, line):
2340 def push_line(self, line):
2336 """Push a line to the interpreter.
2341 """Push a line to the interpreter.
2337
2342
2338 The line should not have a trailing newline; it may have
2343 The line should not have a trailing newline; it may have
2339 internal newlines. The line is appended to a buffer and the
2344 internal newlines. The line is appended to a buffer and the
2340 interpreter's runsource() method is called with the
2345 interpreter's runsource() method is called with the
2341 concatenated contents of the buffer as source. If this
2346 concatenated contents of the buffer as source. If this
2342 indicates that the command was executed or invalid, the buffer
2347 indicates that the command was executed or invalid, the buffer
2343 is reset; otherwise, the command is incomplete, and the buffer
2348 is reset; otherwise, the command is incomplete, and the buffer
2344 is left as it was after the line was appended. The return
2349 is left as it was after the line was appended. The return
2345 value is 1 if more input is required, 0 if the line was dealt
2350 value is 1 if more input is required, 0 if the line was dealt
2346 with in some way (this is the same as runsource()).
2351 with in some way (this is the same as runsource()).
2347 """
2352 """
2348
2353
2349 # autoindent management should be done here, and not in the
2354 # autoindent management should be done here, and not in the
2350 # interactive loop, since that one is only seen by keyboard input. We
2355 # interactive loop, since that one is only seen by keyboard input. We
2351 # need this done correctly even for code run via runlines (which uses
2356 # need this done correctly even for code run via runlines (which uses
2352 # push).
2357 # push).
2353
2358
2354 #print 'push line: <%s>' % line # dbg
2359 #print 'push line: <%s>' % line # dbg
2355 for subline in line.splitlines():
2360 for subline in line.splitlines():
2356 self._autoindent_update(subline)
2361 self._autoindent_update(subline)
2357 self.buffer.append(line)
2362 self.buffer.append(line)
2358 more = self.runsource('\n'.join(self.buffer), self.filename)
2363 more = self.runsource('\n'.join(self.buffer), self.filename)
2359 if not more:
2364 if not more:
2360 self.resetbuffer()
2365 self.resetbuffer()
2361 return more
2366 return more
2362
2367
2363 def resetbuffer(self):
2368 def resetbuffer(self):
2364 """Reset the input buffer."""
2369 """Reset the input buffer."""
2365 self.buffer[:] = []
2370 self.buffer[:] = []
2366
2371
2367 def _is_secondary_block_start(self, s):
2372 def _is_secondary_block_start(self, s):
2368 if not s.endswith(':'):
2373 if not s.endswith(':'):
2369 return False
2374 return False
2370 if (s.startswith('elif') or
2375 if (s.startswith('elif') or
2371 s.startswith('else') or
2376 s.startswith('else') or
2372 s.startswith('except') or
2377 s.startswith('except') or
2373 s.startswith('finally')):
2378 s.startswith('finally')):
2374 return True
2379 return True
2375
2380
2376 def _cleanup_ipy_script(self, script):
2381 def _cleanup_ipy_script(self, script):
2377 """Make a script safe for self.runlines()
2382 """Make a script safe for self.runlines()
2378
2383
2379 Currently, IPython is lines based, with blocks being detected by
2384 Currently, IPython is lines based, with blocks being detected by
2380 empty lines. This is a problem for block based scripts that may
2385 empty lines. This is a problem for block based scripts that may
2381 not have empty lines after blocks. This script adds those empty
2386 not have empty lines after blocks. This script adds those empty
2382 lines to make scripts safe for running in the current line based
2387 lines to make scripts safe for running in the current line based
2383 IPython.
2388 IPython.
2384 """
2389 """
2385 res = []
2390 res = []
2386 lines = script.splitlines()
2391 lines = script.splitlines()
2387 level = 0
2392 level = 0
2388
2393
2389 for l in lines:
2394 for l in lines:
2390 lstripped = l.lstrip()
2395 lstripped = l.lstrip()
2391 stripped = l.strip()
2396 stripped = l.strip()
2392 if not stripped:
2397 if not stripped:
2393 continue
2398 continue
2394 newlevel = len(l) - len(lstripped)
2399 newlevel = len(l) - len(lstripped)
2395 if level > 0 and newlevel == 0 and \
2400 if level > 0 and newlevel == 0 and \
2396 not self._is_secondary_block_start(stripped):
2401 not self._is_secondary_block_start(stripped):
2397 # add empty line
2402 # add empty line
2398 res.append('')
2403 res.append('')
2399 res.append(l)
2404 res.append(l)
2400 level = newlevel
2405 level = newlevel
2401
2406
2402 return '\n'.join(res) + '\n'
2407 return '\n'.join(res) + '\n'
2403
2408
2404 def _autoindent_update(self,line):
2409 def _autoindent_update(self,line):
2405 """Keep track of the indent level."""
2410 """Keep track of the indent level."""
2406
2411
2407 #debugx('line')
2412 #debugx('line')
2408 #debugx('self.indent_current_nsp')
2413 #debugx('self.indent_current_nsp')
2409 if self.autoindent:
2414 if self.autoindent:
2410 if line:
2415 if line:
2411 inisp = num_ini_spaces(line)
2416 inisp = num_ini_spaces(line)
2412 if inisp < self.indent_current_nsp:
2417 if inisp < self.indent_current_nsp:
2413 self.indent_current_nsp = inisp
2418 self.indent_current_nsp = inisp
2414
2419
2415 if line[-1] == ':':
2420 if line[-1] == ':':
2416 self.indent_current_nsp += 4
2421 self.indent_current_nsp += 4
2417 elif dedent_re.match(line):
2422 elif dedent_re.match(line):
2418 self.indent_current_nsp -= 4
2423 self.indent_current_nsp -= 4
2419 else:
2424 else:
2420 self.indent_current_nsp = 0
2425 self.indent_current_nsp = 0
2421
2426
2422 #-------------------------------------------------------------------------
2427 #-------------------------------------------------------------------------
2423 # Things related to GUI support and pylab
2428 # Things related to GUI support and pylab
2424 #-------------------------------------------------------------------------
2429 #-------------------------------------------------------------------------
2425
2430
2426 def enable_pylab(self, gui=None):
2431 def enable_pylab(self, gui=None):
2427 raise NotImplementedError('Implement enable_pylab in a subclass')
2432 raise NotImplementedError('Implement enable_pylab in a subclass')
2428
2433
2429 #-------------------------------------------------------------------------
2434 #-------------------------------------------------------------------------
2430 # Utilities
2435 # Utilities
2431 #-------------------------------------------------------------------------
2436 #-------------------------------------------------------------------------
2432
2437
2433 def var_expand(self,cmd,depth=0):
2438 def var_expand(self,cmd,depth=0):
2434 """Expand python variables in a string.
2439 """Expand python variables in a string.
2435
2440
2436 The depth argument indicates how many frames above the caller should
2441 The depth argument indicates how many frames above the caller should
2437 be walked to look for the local namespace where to expand variables.
2442 be walked to look for the local namespace where to expand variables.
2438
2443
2439 The global namespace for expansion is always the user's interactive
2444 The global namespace for expansion is always the user's interactive
2440 namespace.
2445 namespace.
2441 """
2446 """
2442
2447
2443 return str(ItplNS(cmd,
2448 return str(ItplNS(cmd,
2444 self.user_ns, # globals
2449 self.user_ns, # globals
2445 # Skip our own frame in searching for locals:
2450 # Skip our own frame in searching for locals:
2446 sys._getframe(depth+1).f_locals # locals
2451 sys._getframe(depth+1).f_locals # locals
2447 ))
2452 ))
2448
2453
2449 def mktempfile(self,data=None):
2454 def mktempfile(self,data=None):
2450 """Make a new tempfile and return its filename.
2455 """Make a new tempfile and return its filename.
2451
2456
2452 This makes a call to tempfile.mktemp, but it registers the created
2457 This makes a call to tempfile.mktemp, but it registers the created
2453 filename internally so ipython cleans it up at exit time.
2458 filename internally so ipython cleans it up at exit time.
2454
2459
2455 Optional inputs:
2460 Optional inputs:
2456
2461
2457 - data(None): if data is given, it gets written out to the temp file
2462 - data(None): if data is given, it gets written out to the temp file
2458 immediately, and the file is closed again."""
2463 immediately, and the file is closed again."""
2459
2464
2460 filename = tempfile.mktemp('.py','ipython_edit_')
2465 filename = tempfile.mktemp('.py','ipython_edit_')
2461 self.tempfiles.append(filename)
2466 self.tempfiles.append(filename)
2462
2467
2463 if data:
2468 if data:
2464 tmp_file = open(filename,'w')
2469 tmp_file = open(filename,'w')
2465 tmp_file.write(data)
2470 tmp_file.write(data)
2466 tmp_file.close()
2471 tmp_file.close()
2467 return filename
2472 return filename
2468
2473
2469 # TODO: This should be removed when Term is refactored.
2474 # TODO: This should be removed when Term is refactored.
2470 def write(self,data):
2475 def write(self,data):
2471 """Write a string to the default output"""
2476 """Write a string to the default output"""
2472 io.Term.cout.write(data)
2477 io.Term.cout.write(data)
2473
2478
2474 # TODO: This should be removed when Term is refactored.
2479 # TODO: This should be removed when Term is refactored.
2475 def write_err(self,data):
2480 def write_err(self,data):
2476 """Write a string to the default error output"""
2481 """Write a string to the default error output"""
2477 io.Term.cerr.write(data)
2482 io.Term.cerr.write(data)
2478
2483
2479 def ask_yes_no(self,prompt,default=True):
2484 def ask_yes_no(self,prompt,default=True):
2480 if self.quiet:
2485 if self.quiet:
2481 return True
2486 return True
2482 return ask_yes_no(prompt,default)
2487 return ask_yes_no(prompt,default)
2483
2488
2484 def show_usage(self):
2489 def show_usage(self):
2485 """Show a usage message"""
2490 """Show a usage message"""
2486 page.page(IPython.core.usage.interactive_usage)
2491 page.page(IPython.core.usage.interactive_usage)
2487
2492
2488 #-------------------------------------------------------------------------
2493 #-------------------------------------------------------------------------
2489 # Things related to IPython exiting
2494 # Things related to IPython exiting
2490 #-------------------------------------------------------------------------
2495 #-------------------------------------------------------------------------
2491 def atexit_operations(self):
2496 def atexit_operations(self):
2492 """This will be executed at the time of exit.
2497 """This will be executed at the time of exit.
2493
2498
2494 Cleanup operations and saving of persistent data that is done
2499 Cleanup operations and saving of persistent data that is done
2495 unconditionally by IPython should be performed here.
2500 unconditionally by IPython should be performed here.
2496
2501
2497 For things that may depend on startup flags or platform specifics (such
2502 For things that may depend on startup flags or platform specifics (such
2498 as having readline or not), register a separate atexit function in the
2503 as having readline or not), register a separate atexit function in the
2499 code that has the appropriate information, rather than trying to
2504 code that has the appropriate information, rather than trying to
2500 clutter
2505 clutter
2501 """
2506 """
2502 # Cleanup all tempfiles left around
2507 # Cleanup all tempfiles left around
2503 for tfile in self.tempfiles:
2508 for tfile in self.tempfiles:
2504 try:
2509 try:
2505 os.unlink(tfile)
2510 os.unlink(tfile)
2506 except OSError:
2511 except OSError:
2507 pass
2512 pass
2508
2513
2509 # Clear all user namespaces to release all references cleanly.
2514 # Clear all user namespaces to release all references cleanly.
2510 self.reset()
2515 self.reset()
2511
2516
2512 # Run user hooks
2517 # Run user hooks
2513 self.hooks.shutdown_hook()
2518 self.hooks.shutdown_hook()
2514
2519
2515 def cleanup(self):
2520 def cleanup(self):
2516 self.restore_sys_module_state()
2521 self.restore_sys_module_state()
2517
2522
2518
2523
2519 class InteractiveShellABC(object):
2524 class InteractiveShellABC(object):
2520 """An abstract base class for InteractiveShell."""
2525 """An abstract base class for InteractiveShell."""
2521 __metaclass__ = abc.ABCMeta
2526 __metaclass__ = abc.ABCMeta
2522
2527
2523 InteractiveShellABC.register(InteractiveShell)
2528 InteractiveShellABC.register(InteractiveShell)
@@ -1,3377 +1,3372 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 import page
55 from IPython.core 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.external.Itpl import itpl, printpl
58 from IPython.external.Itpl import itpl, printpl
59 from IPython.testing import decorators as testdec
59 from IPython.testing import decorators as testdec
60 from IPython.utils.io import file_read, nlprint
60 from IPython.utils.io import file_read, nlprint
61 import IPython.utils.io
61 import IPython.utils.io
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, format_screen
65 from IPython.utils.text import LSString, SList, StringTypes, format_screen
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, Configurable and the MRO... For now leave it as-is, but
100 # on with super() calls, Configurable 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 # Configurable. This messes up the MRO in some way. The fix is that we need to
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a configurable that InteractiveShell does not subclass.
104 # make Magic a configurable 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 arg_err(self,func):
211 def arg_err(self,func):
212 """Print docstring if incorrect arguments were passed"""
212 """Print docstring if incorrect arguments were passed"""
213 print 'Error in arguments:'
213 print 'Error in arguments:'
214 print oinspect.getdoc(func)
214 print oinspect.getdoc(func)
215
215
216 def format_latex(self,strng):
216 def format_latex(self,strng):
217 """Format a string for latex inclusion."""
217 """Format a string for latex inclusion."""
218
218
219 # Characters that need to be escaped for latex:
219 # Characters that need to be escaped for latex:
220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
220 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
221 # Magic command names as headers:
221 # Magic command names as headers:
222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
222 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
223 re.MULTILINE)
223 re.MULTILINE)
224 # Magic commands
224 # Magic commands
225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
225 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
226 re.MULTILINE)
226 re.MULTILINE)
227 # Paragraph continue
227 # Paragraph continue
228 par_re = re.compile(r'\\$',re.MULTILINE)
228 par_re = re.compile(r'\\$',re.MULTILINE)
229
229
230 # The "\n" symbol
230 # The "\n" symbol
231 newline_re = re.compile(r'\\n')
231 newline_re = re.compile(r'\\n')
232
232
233 # Now build the string for output:
233 # Now build the string for output:
234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
234 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
235 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
236 strng)
236 strng)
237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
237 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
238 strng = par_re.sub(r'\\\\',strng)
238 strng = par_re.sub(r'\\\\',strng)
239 strng = escape_re.sub(r'\\\1',strng)
239 strng = escape_re.sub(r'\\\1',strng)
240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
240 strng = newline_re.sub(r'\\textbackslash{}n',strng)
241 return strng
241 return strng
242
242
243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
243 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
244 """Parse options passed to an argument string.
244 """Parse options passed to an argument string.
245
245
246 The interface is similar to that of getopt(), but it returns back a
246 The interface is similar to that of getopt(), but it returns back a
247 Struct with the options as keys and the stripped argument string still
247 Struct with the options as keys and the stripped argument string still
248 as a string.
248 as a string.
249
249
250 arg_str is quoted as a true sys.argv vector by using shlex.split.
250 arg_str is quoted as a true sys.argv vector by using shlex.split.
251 This allows us to easily expand variables, glob files, quote
251 This allows us to easily expand variables, glob files, quote
252 arguments, etc.
252 arguments, etc.
253
253
254 Options:
254 Options:
255 -mode: default 'string'. If given as 'list', the argument string is
255 -mode: default 'string'. If given as 'list', the argument string is
256 returned as a list (split on whitespace) instead of a string.
256 returned as a list (split on whitespace) instead of a string.
257
257
258 -list_all: put all option values in lists. Normally only options
258 -list_all: put all option values in lists. Normally only options
259 appearing more than once are put in a list.
259 appearing more than once are put in a list.
260
260
261 -posix (True): whether to split the input line in POSIX mode or not,
261 -posix (True): whether to split the input line in POSIX mode or not,
262 as per the conventions outlined in the shlex module from the
262 as per the conventions outlined in the shlex module from the
263 standard library."""
263 standard library."""
264
264
265 # inject default options at the beginning of the input line
265 # inject default options at the beginning of the input line
266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
266 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
267 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
268
268
269 mode = kw.get('mode','string')
269 mode = kw.get('mode','string')
270 if mode not in ['string','list']:
270 if mode not in ['string','list']:
271 raise ValueError,'incorrect mode given: %s' % mode
271 raise ValueError,'incorrect mode given: %s' % mode
272 # Get options
272 # Get options
273 list_all = kw.get('list_all',0)
273 list_all = kw.get('list_all',0)
274 posix = kw.get('posix', os.name == 'posix')
274 posix = kw.get('posix', os.name == 'posix')
275
275
276 # Check if we have more than one argument to warrant extra processing:
276 # Check if we have more than one argument to warrant extra processing:
277 odict = {} # Dictionary with options
277 odict = {} # Dictionary with options
278 args = arg_str.split()
278 args = arg_str.split()
279 if len(args) >= 1:
279 if len(args) >= 1:
280 # If the list of inputs only has 0 or 1 thing in it, there's no
280 # If the list of inputs only has 0 or 1 thing in it, there's no
281 # need to look for options
281 # need to look for options
282 argv = arg_split(arg_str,posix)
282 argv = arg_split(arg_str,posix)
283 # Do regular option processing
283 # Do regular option processing
284 try:
284 try:
285 opts,args = getopt(argv,opt_str,*long_opts)
285 opts,args = getopt(argv,opt_str,*long_opts)
286 except GetoptError,e:
286 except GetoptError,e:
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
287 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
288 " ".join(long_opts)))
288 " ".join(long_opts)))
289 for o,a in opts:
289 for o,a in opts:
290 if o.startswith('--'):
290 if o.startswith('--'):
291 o = o[2:]
291 o = o[2:]
292 else:
292 else:
293 o = o[1:]
293 o = o[1:]
294 try:
294 try:
295 odict[o].append(a)
295 odict[o].append(a)
296 except AttributeError:
296 except AttributeError:
297 odict[o] = [odict[o],a]
297 odict[o] = [odict[o],a]
298 except KeyError:
298 except KeyError:
299 if list_all:
299 if list_all:
300 odict[o] = [a]
300 odict[o] = [a]
301 else:
301 else:
302 odict[o] = a
302 odict[o] = a
303
303
304 # Prepare opts,args for return
304 # Prepare opts,args for return
305 opts = Struct(odict)
305 opts = Struct(odict)
306 if mode == 'string':
306 if mode == 'string':
307 args = ' '.join(args)
307 args = ' '.join(args)
308
308
309 return opts,args
309 return opts,args
310
310
311 #......................................................................
311 #......................................................................
312 # And now the actual magic functions
312 # And now the actual magic functions
313
313
314 # Functions for IPython shell work (vars,funcs, config, etc)
314 # Functions for IPython shell work (vars,funcs, config, etc)
315 def magic_lsmagic(self, parameter_s = ''):
315 def magic_lsmagic(self, parameter_s = ''):
316 """List currently available magic functions."""
316 """List currently available magic functions."""
317 mesc = ESC_MAGIC
317 mesc = ESC_MAGIC
318 print 'Available magic functions:\n'+mesc+\
318 print 'Available magic functions:\n'+mesc+\
319 (' '+mesc).join(self.lsmagic())
319 (' '+mesc).join(self.lsmagic())
320 print '\n' + Magic.auto_status[self.shell.automagic]
320 print '\n' + Magic.auto_status[self.shell.automagic]
321 return None
321 return None
322
322
323 def magic_magic(self, parameter_s = ''):
323 def magic_magic(self, parameter_s = ''):
324 """Print information about the magic function system.
324 """Print information about the magic function system.
325
325
326 Supported formats: -latex, -brief, -rest
326 Supported formats: -latex, -brief, -rest
327 """
327 """
328
328
329 mode = ''
329 mode = ''
330 try:
330 try:
331 if parameter_s.split()[0] == '-latex':
331 if parameter_s.split()[0] == '-latex':
332 mode = 'latex'
332 mode = 'latex'
333 if parameter_s.split()[0] == '-brief':
333 if parameter_s.split()[0] == '-brief':
334 mode = 'brief'
334 mode = 'brief'
335 if parameter_s.split()[0] == '-rest':
335 if parameter_s.split()[0] == '-rest':
336 mode = 'rest'
336 mode = 'rest'
337 rest_docs = []
337 rest_docs = []
338 except:
338 except:
339 pass
339 pass
340
340
341 magic_docs = []
341 magic_docs = []
342 for fname in self.lsmagic():
342 for fname in self.lsmagic():
343 mname = 'magic_' + fname
343 mname = 'magic_' + fname
344 for space in (Magic,self,self.__class__):
344 for space in (Magic,self,self.__class__):
345 try:
345 try:
346 fn = space.__dict__[mname]
346 fn = space.__dict__[mname]
347 except KeyError:
347 except KeyError:
348 pass
348 pass
349 else:
349 else:
350 break
350 break
351 if mode == 'brief':
351 if mode == 'brief':
352 # only first line
352 # only first line
353 if fn.__doc__:
353 if fn.__doc__:
354 fndoc = fn.__doc__.split('\n',1)[0]
354 fndoc = fn.__doc__.split('\n',1)[0]
355 else:
355 else:
356 fndoc = 'No documentation'
356 fndoc = 'No documentation'
357 else:
357 else:
358 if fn.__doc__:
358 if fn.__doc__:
359 fndoc = fn.__doc__.rstrip()
359 fndoc = fn.__doc__.rstrip()
360 else:
360 else:
361 fndoc = 'No documentation'
361 fndoc = 'No documentation'
362
362
363
363
364 if mode == 'rest':
364 if mode == 'rest':
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
365 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
366 fname,fndoc))
366 fname,fndoc))
367
367
368 else:
368 else:
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
369 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
370 fname,fndoc))
370 fname,fndoc))
371
371
372 magic_docs = ''.join(magic_docs)
372 magic_docs = ''.join(magic_docs)
373
373
374 if mode == 'rest':
374 if mode == 'rest':
375 return "".join(rest_docs)
375 return "".join(rest_docs)
376
376
377 if mode == 'latex':
377 if mode == 'latex':
378 print self.format_latex(magic_docs)
378 print self.format_latex(magic_docs)
379 return
379 return
380 else:
380 else:
381 magic_docs = format_screen(magic_docs)
381 magic_docs = format_screen(magic_docs)
382 if mode == 'brief':
382 if mode == 'brief':
383 return magic_docs
383 return magic_docs
384
384
385 outmsg = """
385 outmsg = """
386 IPython's 'magic' functions
386 IPython's 'magic' functions
387 ===========================
387 ===========================
388
388
389 The magic function system provides a series of functions which allow you to
389 The magic function system provides a series of functions which allow you to
390 control the behavior of IPython itself, plus a lot of system-type
390 control the behavior of IPython itself, plus a lot of system-type
391 features. All these functions are prefixed with a % character, but parameters
391 features. All these functions are prefixed with a % character, but parameters
392 are given without parentheses or quotes.
392 are given without parentheses or quotes.
393
393
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
394 NOTE: If you have 'automagic' enabled (via the command line option or with the
395 %automagic function), you don't need to type in the % explicitly. By default,
395 %automagic function), you don't need to type in the % explicitly. By default,
396 IPython ships with automagic on, so you should only rarely need the % escape.
396 IPython ships with automagic on, so you should only rarely need the % escape.
397
397
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
398 Example: typing '%cd mydir' (without the quotes) changes you working directory
399 to 'mydir', if it exists.
399 to 'mydir', if it exists.
400
400
401 You can define your own magic functions to extend the system. See the supplied
401 You can define your own magic functions to extend the system. See the supplied
402 ipythonrc and example-magic.py files for details (in your ipython
402 ipythonrc and example-magic.py files for details (in your ipython
403 configuration directory, typically $HOME/.ipython/).
403 configuration directory, typically $HOME/.ipython/).
404
404
405 You can also define your own aliased names for magic functions. In your
405 You can also define your own aliased names for magic functions. In your
406 ipythonrc file, placing a line like:
406 ipythonrc file, placing a line like:
407
407
408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
408 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
409
409
410 will define %pf as a new name for %profile.
410 will define %pf as a new name for %profile.
411
411
412 You can also call magics in code using the magic() function, which IPython
412 You can also call magics in code using the magic() function, which IPython
413 automatically adds to the builtin namespace. Type 'magic?' for details.
413 automatically adds to the builtin namespace. Type 'magic?' for details.
414
414
415 For a list of the available magic functions, use %lsmagic. For a description
415 For a list of the available magic functions, use %lsmagic. For a description
416 of any of them, type %magic_name?, e.g. '%cd?'.
416 of any of them, type %magic_name?, e.g. '%cd?'.
417
417
418 Currently the magic system has the following functions:\n"""
418 Currently the magic system has the following functions:\n"""
419
419
420 mesc = ESC_MAGIC
420 mesc = ESC_MAGIC
421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
421 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
422 "\n\n%s%s\n\n%s" % (outmsg,
422 "\n\n%s%s\n\n%s" % (outmsg,
423 magic_docs,mesc,mesc,
423 magic_docs,mesc,mesc,
424 (' '+mesc).join(self.lsmagic()),
424 (' '+mesc).join(self.lsmagic()),
425 Magic.auto_status[self.shell.automagic] ) )
425 Magic.auto_status[self.shell.automagic] ) )
426 page.page(outmsg)
426 page.page(outmsg)
427
427
428 def magic_automagic(self, parameter_s = ''):
428 def magic_automagic(self, parameter_s = ''):
429 """Make magic functions callable without having to type the initial %.
429 """Make magic functions callable without having to type the initial %.
430
430
431 Without argumentsl toggles on/off (when off, you must call it as
431 Without argumentsl toggles on/off (when off, you must call it as
432 %automagic, of course). With arguments it sets the value, and you can
432 %automagic, of course). With arguments it sets the value, and you can
433 use any of (case insensitive):
433 use any of (case insensitive):
434
434
435 - on,1,True: to activate
435 - on,1,True: to activate
436
436
437 - off,0,False: to deactivate.
437 - off,0,False: to deactivate.
438
438
439 Note that magic functions have lowest priority, so if there's a
439 Note that magic functions have lowest priority, so if there's a
440 variable whose name collides with that of a magic fn, automagic won't
440 variable whose name collides with that of a magic fn, automagic won't
441 work for that function (you get the variable instead). However, if you
441 work for that function (you get the variable instead). However, if you
442 delete the variable (del var), the previously shadowed magic function
442 delete the variable (del var), the previously shadowed magic function
443 becomes visible to automagic again."""
443 becomes visible to automagic again."""
444
444
445 arg = parameter_s.lower()
445 arg = parameter_s.lower()
446 if parameter_s in ('on','1','true'):
446 if parameter_s in ('on','1','true'):
447 self.shell.automagic = True
447 self.shell.automagic = True
448 elif parameter_s in ('off','0','false'):
448 elif parameter_s in ('off','0','false'):
449 self.shell.automagic = False
449 self.shell.automagic = False
450 else:
450 else:
451 self.shell.automagic = not self.shell.automagic
451 self.shell.automagic = not self.shell.automagic
452 print '\n' + Magic.auto_status[self.shell.automagic]
452 print '\n' + Magic.auto_status[self.shell.automagic]
453
453
454 @testdec.skip_doctest
454 @testdec.skip_doctest
455 def magic_autocall(self, parameter_s = ''):
455 def magic_autocall(self, parameter_s = ''):
456 """Make functions callable without having to type parentheses.
456 """Make functions callable without having to type parentheses.
457
457
458 Usage:
458 Usage:
459
459
460 %autocall [mode]
460 %autocall [mode]
461
461
462 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
462 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
463 value is toggled on and off (remembering the previous state).
463 value is toggled on and off (remembering the previous state).
464
464
465 In more detail, these values mean:
465 In more detail, these values mean:
466
466
467 0 -> fully disabled
467 0 -> fully disabled
468
468
469 1 -> active, but do not apply if there are no arguments on the line.
469 1 -> active, but do not apply if there are no arguments on the line.
470
470
471 In this mode, you get:
471 In this mode, you get:
472
472
473 In [1]: callable
473 In [1]: callable
474 Out[1]: <built-in function callable>
474 Out[1]: <built-in function callable>
475
475
476 In [2]: callable 'hello'
476 In [2]: callable 'hello'
477 ------> callable('hello')
477 ------> callable('hello')
478 Out[2]: False
478 Out[2]: False
479
479
480 2 -> Active always. Even if no arguments are present, the callable
480 2 -> Active always. Even if no arguments are present, the callable
481 object is called:
481 object is called:
482
482
483 In [2]: float
483 In [2]: float
484 ------> float()
484 ------> float()
485 Out[2]: 0.0
485 Out[2]: 0.0
486
486
487 Note that even with autocall off, you can still use '/' at the start of
487 Note that even with autocall off, you can still use '/' at the start of
488 a line to treat the first argument on the command line as a function
488 a line to treat the first argument on the command line as a function
489 and add parentheses to it:
489 and add parentheses to it:
490
490
491 In [8]: /str 43
491 In [8]: /str 43
492 ------> str(43)
492 ------> str(43)
493 Out[8]: '43'
493 Out[8]: '43'
494
494
495 # all-random (note for auto-testing)
495 # all-random (note for auto-testing)
496 """
496 """
497
497
498 if parameter_s:
498 if parameter_s:
499 arg = int(parameter_s)
499 arg = int(parameter_s)
500 else:
500 else:
501 arg = 'toggle'
501 arg = 'toggle'
502
502
503 if not arg in (0,1,2,'toggle'):
503 if not arg in (0,1,2,'toggle'):
504 error('Valid modes: (0->Off, 1->Smart, 2->Full')
504 error('Valid modes: (0->Off, 1->Smart, 2->Full')
505 return
505 return
506
506
507 if arg in (0,1,2):
507 if arg in (0,1,2):
508 self.shell.autocall = arg
508 self.shell.autocall = arg
509 else: # toggle
509 else: # toggle
510 if self.shell.autocall:
510 if self.shell.autocall:
511 self._magic_state.autocall_save = self.shell.autocall
511 self._magic_state.autocall_save = self.shell.autocall
512 self.shell.autocall = 0
512 self.shell.autocall = 0
513 else:
513 else:
514 try:
514 try:
515 self.shell.autocall = self._magic_state.autocall_save
515 self.shell.autocall = self._magic_state.autocall_save
516 except AttributeError:
516 except AttributeError:
517 self.shell.autocall = self._magic_state.autocall_save = 1
517 self.shell.autocall = self._magic_state.autocall_save = 1
518
518
519 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
519 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
520
520
521
521
522 def magic_page(self, parameter_s=''):
522 def magic_page(self, parameter_s=''):
523 """Pretty print the object and display it through a pager.
523 """Pretty print the object and display it through a pager.
524
524
525 %page [options] OBJECT
525 %page [options] OBJECT
526
526
527 If no object is given, use _ (last output).
527 If no object is given, use _ (last output).
528
528
529 Options:
529 Options:
530
530
531 -r: page str(object), don't pretty-print it."""
531 -r: page str(object), don't pretty-print it."""
532
532
533 # After a function contributed by Olivier Aubert, slightly modified.
533 # After a function contributed by Olivier Aubert, slightly modified.
534
534
535 # Process options/args
535 # Process options/args
536 opts,args = self.parse_options(parameter_s,'r')
536 opts,args = self.parse_options(parameter_s,'r')
537 raw = 'r' in opts
537 raw = 'r' in opts
538
538
539 oname = args and args or '_'
539 oname = args and args or '_'
540 info = self._ofind(oname)
540 info = self._ofind(oname)
541 if info['found']:
541 if info['found']:
542 txt = (raw and str or pformat)( info['obj'] )
542 txt = (raw and str or pformat)( info['obj'] )
543 page.page(txt)
543 page.page(txt)
544 else:
544 else:
545 print 'Object `%s` not found' % oname
545 print 'Object `%s` not found' % oname
546
546
547 def magic_profile(self, parameter_s=''):
547 def magic_profile(self, parameter_s=''):
548 """Print your currently active IPython profile."""
548 """Print your currently active IPython profile."""
549 if self.shell.profile:
549 if self.shell.profile:
550 printpl('Current IPython profile: $self.shell.profile.')
550 printpl('Current IPython profile: $self.shell.profile.')
551 else:
551 else:
552 print 'No profile active.'
552 print 'No profile active.'
553
553
554 def magic_pinfo(self, parameter_s='', namespaces=None):
554 def magic_pinfo(self, parameter_s='', namespaces=None):
555 """Provide detailed information about an object.
555 """Provide detailed information about an object.
556
556
557 '%pinfo object' is just a synonym for object? or ?object."""
557 '%pinfo object' is just a synonym for object? or ?object."""
558
558
559 #print 'pinfo par: <%s>' % parameter_s # dbg
559 #print 'pinfo par: <%s>' % parameter_s # dbg
560
560
561
561
562 # detail_level: 0 -> obj? , 1 -> obj??
562 # detail_level: 0 -> obj? , 1 -> obj??
563 detail_level = 0
563 detail_level = 0
564 # We need to detect if we got called as 'pinfo pinfo foo', which can
564 # We need to detect if we got called as 'pinfo pinfo foo', which can
565 # happen if the user types 'pinfo foo?' at the cmd line.
565 # happen if the user types 'pinfo foo?' at the cmd line.
566 pinfo,qmark1,oname,qmark2 = \
566 pinfo,qmark1,oname,qmark2 = \
567 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
567 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
568 if pinfo or qmark1 or qmark2:
568 if pinfo or qmark1 or qmark2:
569 detail_level = 1
569 detail_level = 1
570 if "*" in oname:
570 if "*" in oname:
571 self.magic_psearch(oname)
571 self.magic_psearch(oname)
572 else:
572 else:
573 self.shell._inspect('pinfo', oname, detail_level=detail_level,
573 self.shell._inspect('pinfo', oname, detail_level=detail_level,
574 namespaces=namespaces)
574 namespaces=namespaces)
575
575
576 def magic_pinfo2(self, parameter_s='', namespaces=None):
576 def magic_pinfo2(self, parameter_s='', namespaces=None):
577 """Provide extra detailed information about an object.
577 """Provide extra detailed information about an object.
578
578
579 '%pinfo2 object' is just a synonym for object?? or ??object."""
579 '%pinfo2 object' is just a synonym for object?? or ??object."""
580 print 'pinfo2 par: <%s>' % parameter_s # dbg
581 self.shell._inspect('pinfo', parameter_s, detail_level=1,
580 self.shell._inspect('pinfo', parameter_s, detail_level=1,
582 namespaces=namespaces)
581 namespaces=namespaces)
583
582
584 def magic_pdef(self, parameter_s='', namespaces=None):
583 def magic_pdef(self, parameter_s='', namespaces=None):
585 """Print the definition header for any callable object.
584 """Print the definition header for any callable object.
586
585
587 If the object is a class, print the constructor information."""
586 If the object is a class, print the constructor information."""
588 self._inspect('pdef',parameter_s, namespaces)
587 self._inspect('pdef',parameter_s, namespaces)
589
588
590 def magic_pdoc(self, parameter_s='', namespaces=None):
589 def magic_pdoc(self, parameter_s='', namespaces=None):
591 """Print the docstring for an object.
590 """Print the docstring for an object.
592
591
593 If the given object is a class, it will print both the class and the
592 If the given object is a class, it will print both the class and the
594 constructor docstrings."""
593 constructor docstrings."""
595 self._inspect('pdoc',parameter_s, namespaces)
594 self._inspect('pdoc',parameter_s, namespaces)
596
595
597 def magic_psource(self, parameter_s='', namespaces=None):
596 def magic_psource(self, parameter_s='', namespaces=None):
598 """Print (or run through pager) the source code for an object."""
597 """Print (or run through pager) the source code for an object."""
599 self._inspect('psource',parameter_s, namespaces)
598 self._inspect('psource',parameter_s, namespaces)
600
599
601 def magic_pfile(self, parameter_s=''):
600 def magic_pfile(self, parameter_s=''):
602 """Print (or run through pager) the file where an object is defined.
601 """Print (or run through pager) the file where an object is defined.
603
602
604 The file opens at the line where the object definition begins. IPython
603 The file opens at the line where the object definition begins. IPython
605 will honor the environment variable PAGER if set, and otherwise will
604 will honor the environment variable PAGER if set, and otherwise will
606 do its best to print the file in a convenient form.
605 do its best to print the file in a convenient form.
607
606
608 If the given argument is not an object currently defined, IPython will
607 If the given argument is not an object currently defined, IPython will
609 try to interpret it as a filename (automatically adding a .py extension
608 try to interpret it as a filename (automatically adding a .py extension
610 if needed). You can thus use %pfile as a syntax highlighting code
609 if needed). You can thus use %pfile as a syntax highlighting code
611 viewer."""
610 viewer."""
612
611
613 # first interpret argument as an object name
612 # first interpret argument as an object name
614 out = self._inspect('pfile',parameter_s)
613 out = self._inspect('pfile',parameter_s)
615 # if not, try the input as a filename
614 # if not, try the input as a filename
616 if out == 'not found':
615 if out == 'not found':
617 try:
616 try:
618 filename = get_py_filename(parameter_s)
617 filename = get_py_filename(parameter_s)
619 except IOError,msg:
618 except IOError,msg:
620 print msg
619 print msg
621 return
620 return
622 page.page(self.shell.inspector.format(file(filename).read()))
621 page.page(self.shell.inspector.format(file(filename).read()))
623
622
624 def magic_psearch(self, parameter_s=''):
623 def magic_psearch(self, parameter_s=''):
625 """Search for object in namespaces by wildcard.
624 """Search for object in namespaces by wildcard.
626
625
627 %psearch [options] PATTERN [OBJECT TYPE]
626 %psearch [options] PATTERN [OBJECT TYPE]
628
627
629 Note: ? can be used as a synonym for %psearch, at the beginning or at
628 Note: ? can be used as a synonym for %psearch, at the beginning or at
630 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
629 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
631 rest of the command line must be unchanged (options come first), so
630 rest of the command line must be unchanged (options come first), so
632 for example the following forms are equivalent
631 for example the following forms are equivalent
633
632
634 %psearch -i a* function
633 %psearch -i a* function
635 -i a* function?
634 -i a* function?
636 ?-i a* function
635 ?-i a* function
637
636
638 Arguments:
637 Arguments:
639
638
640 PATTERN
639 PATTERN
641
640
642 where PATTERN is a string containing * as a wildcard similar to its
641 where PATTERN is a string containing * as a wildcard similar to its
643 use in a shell. The pattern is matched in all namespaces on the
642 use in a shell. The pattern is matched in all namespaces on the
644 search path. By default objects starting with a single _ are not
643 search path. By default objects starting with a single _ are not
645 matched, many IPython generated objects have a single
644 matched, many IPython generated objects have a single
646 underscore. The default is case insensitive matching. Matching is
645 underscore. The default is case insensitive matching. Matching is
647 also done on the attributes of objects and not only on the objects
646 also done on the attributes of objects and not only on the objects
648 in a module.
647 in a module.
649
648
650 [OBJECT TYPE]
649 [OBJECT TYPE]
651
650
652 Is the name of a python type from the types module. The name is
651 Is the name of a python type from the types module. The name is
653 given in lowercase without the ending type, ex. StringType is
652 given in lowercase without the ending type, ex. StringType is
654 written string. By adding a type here only objects matching the
653 written string. By adding a type here only objects matching the
655 given type are matched. Using all here makes the pattern match all
654 given type are matched. Using all here makes the pattern match all
656 types (this is the default).
655 types (this is the default).
657
656
658 Options:
657 Options:
659
658
660 -a: makes the pattern match even objects whose names start with a
659 -a: makes the pattern match even objects whose names start with a
661 single underscore. These names are normally ommitted from the
660 single underscore. These names are normally ommitted from the
662 search.
661 search.
663
662
664 -i/-c: make the pattern case insensitive/sensitive. If neither of
663 -i/-c: make the pattern case insensitive/sensitive. If neither of
665 these options is given, the default is read from your ipythonrc
664 these options is given, the default is read from your ipythonrc
666 file. The option name which sets this value is
665 file. The option name which sets this value is
667 'wildcards_case_sensitive'. If this option is not specified in your
666 'wildcards_case_sensitive'. If this option is not specified in your
668 ipythonrc file, IPython's internal default is to do a case sensitive
667 ipythonrc file, IPython's internal default is to do a case sensitive
669 search.
668 search.
670
669
671 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
670 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
672 specifiy can be searched in any of the following namespaces:
671 specifiy can be searched in any of the following namespaces:
673 'builtin', 'user', 'user_global','internal', 'alias', where
672 'builtin', 'user', 'user_global','internal', 'alias', where
674 'builtin' and 'user' are the search defaults. Note that you should
673 'builtin' and 'user' are the search defaults. Note that you should
675 not use quotes when specifying namespaces.
674 not use quotes when specifying namespaces.
676
675
677 'Builtin' contains the python module builtin, 'user' contains all
676 'Builtin' contains the python module builtin, 'user' contains all
678 user data, 'alias' only contain the shell aliases and no python
677 user data, 'alias' only contain the shell aliases and no python
679 objects, 'internal' contains objects used by IPython. The
678 objects, 'internal' contains objects used by IPython. The
680 'user_global' namespace is only used by embedded IPython instances,
679 'user_global' namespace is only used by embedded IPython instances,
681 and it contains module-level globals. You can add namespaces to the
680 and it contains module-level globals. You can add namespaces to the
682 search with -s or exclude them with -e (these options can be given
681 search with -s or exclude them with -e (these options can be given
683 more than once).
682 more than once).
684
683
685 Examples:
684 Examples:
686
685
687 %psearch a* -> objects beginning with an a
686 %psearch a* -> objects beginning with an a
688 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
687 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
689 %psearch a* function -> all functions beginning with an a
688 %psearch a* function -> all functions beginning with an a
690 %psearch re.e* -> objects beginning with an e in module re
689 %psearch re.e* -> objects beginning with an e in module re
691 %psearch r*.e* -> objects that start with e in modules starting in r
690 %psearch r*.e* -> objects that start with e in modules starting in r
692 %psearch r*.* string -> all strings in modules beginning with r
691 %psearch r*.* string -> all strings in modules beginning with r
693
692
694 Case sensitve search:
693 Case sensitve search:
695
694
696 %psearch -c a* list all object beginning with lower case a
695 %psearch -c a* list all object beginning with lower case a
697
696
698 Show objects beginning with a single _:
697 Show objects beginning with a single _:
699
698
700 %psearch -a _* list objects beginning with a single underscore"""
699 %psearch -a _* list objects beginning with a single underscore"""
701 try:
700 try:
702 parameter_s = parameter_s.encode('ascii')
701 parameter_s = parameter_s.encode('ascii')
703 except UnicodeEncodeError:
702 except UnicodeEncodeError:
704 print 'Python identifiers can only contain ascii characters.'
703 print 'Python identifiers can only contain ascii characters.'
705 return
704 return
706
705
707 # default namespaces to be searched
706 # default namespaces to be searched
708 def_search = ['user','builtin']
707 def_search = ['user','builtin']
709
708
710 # Process options/args
709 # Process options/args
711 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
710 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
712 opt = opts.get
711 opt = opts.get
713 shell = self.shell
712 shell = self.shell
714 psearch = shell.inspector.psearch
713 psearch = shell.inspector.psearch
715
714
716 # select case options
715 # select case options
717 if opts.has_key('i'):
716 if opts.has_key('i'):
718 ignore_case = True
717 ignore_case = True
719 elif opts.has_key('c'):
718 elif opts.has_key('c'):
720 ignore_case = False
719 ignore_case = False
721 else:
720 else:
722 ignore_case = not shell.wildcards_case_sensitive
721 ignore_case = not shell.wildcards_case_sensitive
723
722
724 # Build list of namespaces to search from user options
723 # Build list of namespaces to search from user options
725 def_search.extend(opt('s',[]))
724 def_search.extend(opt('s',[]))
726 ns_exclude = ns_exclude=opt('e',[])
725 ns_exclude = ns_exclude=opt('e',[])
727 ns_search = [nm for nm in def_search if nm not in ns_exclude]
726 ns_search = [nm for nm in def_search if nm not in ns_exclude]
728
727
729 # Call the actual search
728 # Call the actual search
730 try:
729 try:
731 psearch(args,shell.ns_table,ns_search,
730 psearch(args,shell.ns_table,ns_search,
732 show_all=opt('a'),ignore_case=ignore_case)
731 show_all=opt('a'),ignore_case=ignore_case)
733 except:
732 except:
734 shell.showtraceback()
733 shell.showtraceback()
735
734
736 def magic_who_ls(self, parameter_s=''):
735 def magic_who_ls(self, parameter_s=''):
737 """Return a sorted list of all interactive variables.
736 """Return a sorted list of all interactive variables.
738
737
739 If arguments are given, only variables of types matching these
738 If arguments are given, only variables of types matching these
740 arguments are returned."""
739 arguments are returned."""
741
740
742 user_ns = self.shell.user_ns
741 user_ns = self.shell.user_ns
743 internal_ns = self.shell.internal_ns
742 internal_ns = self.shell.internal_ns
744 user_ns_hidden = self.shell.user_ns_hidden
743 user_ns_hidden = self.shell.user_ns_hidden
745 out = [ i for i in user_ns
744 out = [ i for i in user_ns
746 if not i.startswith('_') \
745 if not i.startswith('_') \
747 and not (i in internal_ns or i in user_ns_hidden) ]
746 and not (i in internal_ns or i in user_ns_hidden) ]
748
747
749 typelist = parameter_s.split()
748 typelist = parameter_s.split()
750 if typelist:
749 if typelist:
751 typeset = set(typelist)
750 typeset = set(typelist)
752 out = [i for i in out if type(i).__name__ in typeset]
751 out = [i for i in out if type(i).__name__ in typeset]
753
752
754 out.sort()
753 out.sort()
755 return out
754 return out
756
755
757 def magic_who(self, parameter_s=''):
756 def magic_who(self, parameter_s=''):
758 """Print all interactive variables, with some minimal formatting.
757 """Print all interactive variables, with some minimal formatting.
759
758
760 If any arguments are given, only variables whose type matches one of
759 If any arguments are given, only variables whose type matches one of
761 these are printed. For example:
760 these are printed. For example:
762
761
763 %who function str
762 %who function str
764
763
765 will only list functions and strings, excluding all other types of
764 will only list functions and strings, excluding all other types of
766 variables. To find the proper type names, simply use type(var) at a
765 variables. To find the proper type names, simply use type(var) at a
767 command line to see how python prints type names. For example:
766 command line to see how python prints type names. For example:
768
767
769 In [1]: type('hello')\\
768 In [1]: type('hello')\\
770 Out[1]: <type 'str'>
769 Out[1]: <type 'str'>
771
770
772 indicates that the type name for strings is 'str'.
771 indicates that the type name for strings is 'str'.
773
772
774 %who always excludes executed names loaded through your configuration
773 %who always excludes executed names loaded through your configuration
775 file and things which are internal to IPython.
774 file and things which are internal to IPython.
776
775
777 This is deliberate, as typically you may load many modules and the
776 This is deliberate, as typically you may load many modules and the
778 purpose of %who is to show you only what you've manually defined."""
777 purpose of %who is to show you only what you've manually defined."""
779
778
780 varlist = self.magic_who_ls(parameter_s)
779 varlist = self.magic_who_ls(parameter_s)
781 if not varlist:
780 if not varlist:
782 if parameter_s:
781 if parameter_s:
783 print 'No variables match your requested type.'
782 print 'No variables match your requested type.'
784 else:
783 else:
785 print 'Interactive namespace is empty.'
784 print 'Interactive namespace is empty.'
786 return
785 return
787
786
788 # if we have variables, move on...
787 # if we have variables, move on...
789 count = 0
788 count = 0
790 for i in varlist:
789 for i in varlist:
791 print i+'\t',
790 print i+'\t',
792 count += 1
791 count += 1
793 if count > 8:
792 if count > 8:
794 count = 0
793 count = 0
795 print
794 print
796 print
795 print
797
796
798 def magic_whos(self, parameter_s=''):
797 def magic_whos(self, parameter_s=''):
799 """Like %who, but gives some extra information about each variable.
798 """Like %who, but gives some extra information about each variable.
800
799
801 The same type filtering of %who can be applied here.
800 The same type filtering of %who can be applied here.
802
801
803 For all variables, the type is printed. Additionally it prints:
802 For all variables, the type is printed. Additionally it prints:
804
803
805 - For {},[],(): their length.
804 - For {},[],(): their length.
806
805
807 - For numpy and Numeric arrays, a summary with shape, number of
806 - For numpy and Numeric arrays, a summary with shape, number of
808 elements, typecode and size in memory.
807 elements, typecode and size in memory.
809
808
810 - Everything else: a string representation, snipping their middle if
809 - Everything else: a string representation, snipping their middle if
811 too long."""
810 too long."""
812
811
813 varnames = self.magic_who_ls(parameter_s)
812 varnames = self.magic_who_ls(parameter_s)
814 if not varnames:
813 if not varnames:
815 if parameter_s:
814 if parameter_s:
816 print 'No variables match your requested type.'
815 print 'No variables match your requested type.'
817 else:
816 else:
818 print 'Interactive namespace is empty.'
817 print 'Interactive namespace is empty.'
819 return
818 return
820
819
821 # if we have variables, move on...
820 # if we have variables, move on...
822
821
823 # for these types, show len() instead of data:
822 # for these types, show len() instead of data:
824 seq_types = [types.DictType,types.ListType,types.TupleType]
823 seq_types = [types.DictType,types.ListType,types.TupleType]
825
824
826 # for numpy/Numeric arrays, display summary info
825 # for numpy/Numeric arrays, display summary info
827 try:
826 try:
828 import numpy
827 import numpy
829 except ImportError:
828 except ImportError:
830 ndarray_type = None
829 ndarray_type = None
831 else:
830 else:
832 ndarray_type = numpy.ndarray.__name__
831 ndarray_type = numpy.ndarray.__name__
833 try:
832 try:
834 import Numeric
833 import Numeric
835 except ImportError:
834 except ImportError:
836 array_type = None
835 array_type = None
837 else:
836 else:
838 array_type = Numeric.ArrayType.__name__
837 array_type = Numeric.ArrayType.__name__
839
838
840 # Find all variable names and types so we can figure out column sizes
839 # Find all variable names and types so we can figure out column sizes
841 def get_vars(i):
840 def get_vars(i):
842 return self.shell.user_ns[i]
841 return self.shell.user_ns[i]
843
842
844 # some types are well known and can be shorter
843 # some types are well known and can be shorter
845 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
844 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
846 def type_name(v):
845 def type_name(v):
847 tn = type(v).__name__
846 tn = type(v).__name__
848 return abbrevs.get(tn,tn)
847 return abbrevs.get(tn,tn)
849
848
850 varlist = map(get_vars,varnames)
849 varlist = map(get_vars,varnames)
851
850
852 typelist = []
851 typelist = []
853 for vv in varlist:
852 for vv in varlist:
854 tt = type_name(vv)
853 tt = type_name(vv)
855
854
856 if tt=='instance':
855 if tt=='instance':
857 typelist.append( abbrevs.get(str(vv.__class__),
856 typelist.append( abbrevs.get(str(vv.__class__),
858 str(vv.__class__)))
857 str(vv.__class__)))
859 else:
858 else:
860 typelist.append(tt)
859 typelist.append(tt)
861
860
862 # column labels and # of spaces as separator
861 # column labels and # of spaces as separator
863 varlabel = 'Variable'
862 varlabel = 'Variable'
864 typelabel = 'Type'
863 typelabel = 'Type'
865 datalabel = 'Data/Info'
864 datalabel = 'Data/Info'
866 colsep = 3
865 colsep = 3
867 # variable format strings
866 # variable format strings
868 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
867 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
869 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
868 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
870 aformat = "%s: %s elems, type `%s`, %s bytes"
869 aformat = "%s: %s elems, type `%s`, %s bytes"
871 # find the size of the columns to format the output nicely
870 # find the size of the columns to format the output nicely
872 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
871 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
873 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
872 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
874 # table header
873 # table header
875 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
874 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
876 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
875 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
877 # and the table itself
876 # and the table itself
878 kb = 1024
877 kb = 1024
879 Mb = 1048576 # kb**2
878 Mb = 1048576 # kb**2
880 for vname,var,vtype in zip(varnames,varlist,typelist):
879 for vname,var,vtype in zip(varnames,varlist,typelist):
881 print itpl(vformat),
880 print itpl(vformat),
882 if vtype in seq_types:
881 if vtype in seq_types:
883 print len(var)
882 print len(var)
884 elif vtype in [array_type,ndarray_type]:
883 elif vtype in [array_type,ndarray_type]:
885 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
884 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
886 if vtype==ndarray_type:
885 if vtype==ndarray_type:
887 # numpy
886 # numpy
888 vsize = var.size
887 vsize = var.size
889 vbytes = vsize*var.itemsize
888 vbytes = vsize*var.itemsize
890 vdtype = var.dtype
889 vdtype = var.dtype
891 else:
890 else:
892 # Numeric
891 # Numeric
893 vsize = Numeric.size(var)
892 vsize = Numeric.size(var)
894 vbytes = vsize*var.itemsize()
893 vbytes = vsize*var.itemsize()
895 vdtype = var.typecode()
894 vdtype = var.typecode()
896
895
897 if vbytes < 100000:
896 if vbytes < 100000:
898 print aformat % (vshape,vsize,vdtype,vbytes)
897 print aformat % (vshape,vsize,vdtype,vbytes)
899 else:
898 else:
900 print aformat % (vshape,vsize,vdtype,vbytes),
899 print aformat % (vshape,vsize,vdtype,vbytes),
901 if vbytes < Mb:
900 if vbytes < Mb:
902 print '(%s kb)' % (vbytes/kb,)
901 print '(%s kb)' % (vbytes/kb,)
903 else:
902 else:
904 print '(%s Mb)' % (vbytes/Mb,)
903 print '(%s Mb)' % (vbytes/Mb,)
905 else:
904 else:
906 try:
905 try:
907 vstr = str(var)
906 vstr = str(var)
908 except UnicodeEncodeError:
907 except UnicodeEncodeError:
909 vstr = unicode(var).encode(sys.getdefaultencoding(),
908 vstr = unicode(var).encode(sys.getdefaultencoding(),
910 'backslashreplace')
909 'backslashreplace')
911 vstr = vstr.replace('\n','\\n')
910 vstr = vstr.replace('\n','\\n')
912 if len(vstr) < 50:
911 if len(vstr) < 50:
913 print vstr
912 print vstr
914 else:
913 else:
915 printpl(vfmt_short)
914 printpl(vfmt_short)
916
915
917 def magic_reset(self, parameter_s=''):
916 def magic_reset(self, parameter_s=''):
918 """Resets the namespace by removing all names defined by the user.
917 """Resets the namespace by removing all names defined by the user.
919
918
920 Input/Output history are left around in case you need them.
919 Input/Output history are left around in case you need them.
921
920
922 Parameters
921 Parameters
923 ----------
922 ----------
924 -y : force reset without asking for confirmation.
923 -y : force reset without asking for confirmation.
925
924
926 Examples
925 Examples
927 --------
926 --------
928 In [6]: a = 1
927 In [6]: a = 1
929
928
930 In [7]: a
929 In [7]: a
931 Out[7]: 1
930 Out[7]: 1
932
931
933 In [8]: 'a' in _ip.user_ns
932 In [8]: 'a' in _ip.user_ns
934 Out[8]: True
933 Out[8]: True
935
934
936 In [9]: %reset -f
935 In [9]: %reset -f
937
936
938 In [10]: 'a' in _ip.user_ns
937 In [10]: 'a' in _ip.user_ns
939 Out[10]: False
938 Out[10]: False
940 """
939 """
941
940
942 if parameter_s == '-f':
941 if parameter_s == '-f':
943 ans = True
942 ans = True
944 else:
943 else:
945 ans = self.shell.ask_yes_no(
944 ans = self.shell.ask_yes_no(
946 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
945 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
947 if not ans:
946 if not ans:
948 print 'Nothing done.'
947 print 'Nothing done.'
949 return
948 return
950 user_ns = self.shell.user_ns
949 user_ns = self.shell.user_ns
951 for i in self.magic_who_ls():
950 for i in self.magic_who_ls():
952 del(user_ns[i])
951 del(user_ns[i])
953
952
954 # Also flush the private list of module references kept for script
953 # Also flush the private list of module references kept for script
955 # execution protection
954 # execution protection
956 self.shell.clear_main_mod_cache()
955 self.shell.clear_main_mod_cache()
957
956
958 def magic_reset_selective(self, parameter_s=''):
957 def magic_reset_selective(self, parameter_s=''):
959 """Resets the namespace by removing names defined by the user.
958 """Resets the namespace by removing names defined by the user.
960
959
961 Input/Output history are left around in case you need them.
960 Input/Output history are left around in case you need them.
962
961
963 %reset_selective [-f] regex
962 %reset_selective [-f] regex
964
963
965 No action is taken if regex is not included
964 No action is taken if regex is not included
966
965
967 Options
966 Options
968 -f : force reset without asking for confirmation.
967 -f : force reset without asking for confirmation.
969
968
970 Examples
969 Examples
971 --------
970 --------
972
971
973 We first fully reset the namespace so your output looks identical to
972 We first fully reset the namespace so your output looks identical to
974 this example for pedagogical reasons; in practice you do not need a
973 this example for pedagogical reasons; in practice you do not need a
975 full reset.
974 full reset.
976
975
977 In [1]: %reset -f
976 In [1]: %reset -f
978
977
979 Now, with a clean namespace we can make a few variables and use
978 Now, with a clean namespace we can make a few variables and use
980 %reset_selective to only delete names that match our regexp:
979 %reset_selective to only delete names that match our regexp:
981
980
982 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
981 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
983
982
984 In [3]: who_ls
983 In [3]: who_ls
985 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
984 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
986
985
987 In [4]: %reset_selective -f b[2-3]m
986 In [4]: %reset_selective -f b[2-3]m
988
987
989 In [5]: who_ls
988 In [5]: who_ls
990 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
989 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
991
990
992 In [6]: %reset_selective -f d
991 In [6]: %reset_selective -f d
993
992
994 In [7]: who_ls
993 In [7]: who_ls
995 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
994 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
996
995
997 In [8]: %reset_selective -f c
996 In [8]: %reset_selective -f c
998
997
999 In [9]: who_ls
998 In [9]: who_ls
1000 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
999 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1001
1000
1002 In [10]: %reset_selective -f b
1001 In [10]: %reset_selective -f b
1003
1002
1004 In [11]: who_ls
1003 In [11]: who_ls
1005 Out[11]: ['a']
1004 Out[11]: ['a']
1006 """
1005 """
1007
1006
1008 opts, regex = self.parse_options(parameter_s,'f')
1007 opts, regex = self.parse_options(parameter_s,'f')
1009
1008
1010 if opts.has_key('f'):
1009 if opts.has_key('f'):
1011 ans = True
1010 ans = True
1012 else:
1011 else:
1013 ans = self.shell.ask_yes_no(
1012 ans = self.shell.ask_yes_no(
1014 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1013 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1015 if not ans:
1014 if not ans:
1016 print 'Nothing done.'
1015 print 'Nothing done.'
1017 return
1016 return
1018 user_ns = self.shell.user_ns
1017 user_ns = self.shell.user_ns
1019 if not regex:
1018 if not regex:
1020 print 'No regex pattern specified. Nothing done.'
1019 print 'No regex pattern specified. Nothing done.'
1021 return
1020 return
1022 else:
1021 else:
1023 try:
1022 try:
1024 m = re.compile(regex)
1023 m = re.compile(regex)
1025 except TypeError:
1024 except TypeError:
1026 raise TypeError('regex must be a string or compiled pattern')
1025 raise TypeError('regex must be a string or compiled pattern')
1027 for i in self.magic_who_ls():
1026 for i in self.magic_who_ls():
1028 if m.search(i):
1027 if m.search(i):
1029 del(user_ns[i])
1028 del(user_ns[i])
1030
1029
1031 def magic_logstart(self,parameter_s=''):
1030 def magic_logstart(self,parameter_s=''):
1032 """Start logging anywhere in a session.
1031 """Start logging anywhere in a session.
1033
1032
1034 %logstart [-o|-r|-t] [log_name [log_mode]]
1033 %logstart [-o|-r|-t] [log_name [log_mode]]
1035
1034
1036 If no name is given, it defaults to a file named 'ipython_log.py' in your
1035 If no name is given, it defaults to a file named 'ipython_log.py' in your
1037 current directory, in 'rotate' mode (see below).
1036 current directory, in 'rotate' mode (see below).
1038
1037
1039 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1038 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1040 history up to that point and then continues logging.
1039 history up to that point and then continues logging.
1041
1040
1042 %logstart takes a second optional parameter: logging mode. This can be one
1041 %logstart takes a second optional parameter: logging mode. This can be one
1043 of (note that the modes are given unquoted):\\
1042 of (note that the modes are given unquoted):\\
1044 append: well, that says it.\\
1043 append: well, that says it.\\
1045 backup: rename (if exists) to name~ and start name.\\
1044 backup: rename (if exists) to name~ and start name.\\
1046 global: single logfile in your home dir, appended to.\\
1045 global: single logfile in your home dir, appended to.\\
1047 over : overwrite existing log.\\
1046 over : overwrite existing log.\\
1048 rotate: create rotating logs name.1~, name.2~, etc.
1047 rotate: create rotating logs name.1~, name.2~, etc.
1049
1048
1050 Options:
1049 Options:
1051
1050
1052 -o: log also IPython's output. In this mode, all commands which
1051 -o: log also IPython's output. In this mode, all commands which
1053 generate an Out[NN] prompt are recorded to the logfile, right after
1052 generate an Out[NN] prompt are recorded to the logfile, right after
1054 their corresponding input line. The output lines are always
1053 their corresponding input line. The output lines are always
1055 prepended with a '#[Out]# ' marker, so that the log remains valid
1054 prepended with a '#[Out]# ' marker, so that the log remains valid
1056 Python code.
1055 Python code.
1057
1056
1058 Since this marker is always the same, filtering only the output from
1057 Since this marker is always the same, filtering only the output from
1059 a log is very easy, using for example a simple awk call:
1058 a log is very easy, using for example a simple awk call:
1060
1059
1061 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1060 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1062
1061
1063 -r: log 'raw' input. Normally, IPython's logs contain the processed
1062 -r: log 'raw' input. Normally, IPython's logs contain the processed
1064 input, so that user lines are logged in their final form, converted
1063 input, so that user lines are logged in their final form, converted
1065 into valid Python. For example, %Exit is logged as
1064 into valid Python. For example, %Exit is logged as
1066 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1065 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1067 exactly as typed, with no transformations applied.
1066 exactly as typed, with no transformations applied.
1068
1067
1069 -t: put timestamps before each input line logged (these are put in
1068 -t: put timestamps before each input line logged (these are put in
1070 comments)."""
1069 comments)."""
1071
1070
1072 opts,par = self.parse_options(parameter_s,'ort')
1071 opts,par = self.parse_options(parameter_s,'ort')
1073 log_output = 'o' in opts
1072 log_output = 'o' in opts
1074 log_raw_input = 'r' in opts
1073 log_raw_input = 'r' in opts
1075 timestamp = 't' in opts
1074 timestamp = 't' in opts
1076
1075
1077 logger = self.shell.logger
1076 logger = self.shell.logger
1078
1077
1079 # if no args are given, the defaults set in the logger constructor by
1078 # if no args are given, the defaults set in the logger constructor by
1080 # ipytohn remain valid
1079 # ipytohn remain valid
1081 if par:
1080 if par:
1082 try:
1081 try:
1083 logfname,logmode = par.split()
1082 logfname,logmode = par.split()
1084 except:
1083 except:
1085 logfname = par
1084 logfname = par
1086 logmode = 'backup'
1085 logmode = 'backup'
1087 else:
1086 else:
1088 logfname = logger.logfname
1087 logfname = logger.logfname
1089 logmode = logger.logmode
1088 logmode = logger.logmode
1090 # put logfname into rc struct as if it had been called on the command
1089 # put logfname into rc struct as if it had been called on the command
1091 # line, so it ends up saved in the log header Save it in case we need
1090 # line, so it ends up saved in the log header Save it in case we need
1092 # to restore it...
1091 # to restore it...
1093 old_logfile = self.shell.logfile
1092 old_logfile = self.shell.logfile
1094 if logfname:
1093 if logfname:
1095 logfname = os.path.expanduser(logfname)
1094 logfname = os.path.expanduser(logfname)
1096 self.shell.logfile = logfname
1095 self.shell.logfile = logfname
1097
1096
1098 loghead = '# IPython log file\n\n'
1097 loghead = '# IPython log file\n\n'
1099 try:
1098 try:
1100 started = logger.logstart(logfname,loghead,logmode,
1099 started = logger.logstart(logfname,loghead,logmode,
1101 log_output,timestamp,log_raw_input)
1100 log_output,timestamp,log_raw_input)
1102 except:
1101 except:
1103 self.shell.logfile = old_logfile
1102 self.shell.logfile = old_logfile
1104 warn("Couldn't start log: %s" % sys.exc_info()[1])
1103 warn("Couldn't start log: %s" % sys.exc_info()[1])
1105 else:
1104 else:
1106 # log input history up to this point, optionally interleaving
1105 # log input history up to this point, optionally interleaving
1107 # output if requested
1106 # output if requested
1108
1107
1109 if timestamp:
1108 if timestamp:
1110 # disable timestamping for the previous history, since we've
1109 # disable timestamping for the previous history, since we've
1111 # lost those already (no time machine here).
1110 # lost those already (no time machine here).
1112 logger.timestamp = False
1111 logger.timestamp = False
1113
1112
1114 if log_raw_input:
1113 if log_raw_input:
1115 input_hist = self.shell.input_hist_raw
1114 input_hist = self.shell.input_hist_raw
1116 else:
1115 else:
1117 input_hist = self.shell.input_hist
1116 input_hist = self.shell.input_hist
1118
1117
1119 if log_output:
1118 if log_output:
1120 log_write = logger.log_write
1119 log_write = logger.log_write
1121 output_hist = self.shell.output_hist
1120 output_hist = self.shell.output_hist
1122 for n in range(1,len(input_hist)-1):
1121 for n in range(1,len(input_hist)-1):
1123 log_write(input_hist[n].rstrip())
1122 log_write(input_hist[n].rstrip())
1124 if n in output_hist:
1123 if n in output_hist:
1125 log_write(repr(output_hist[n]),'output')
1124 log_write(repr(output_hist[n]),'output')
1126 else:
1125 else:
1127 logger.log_write(input_hist[1:])
1126 logger.log_write(input_hist[1:])
1128 if timestamp:
1127 if timestamp:
1129 # re-enable timestamping
1128 # re-enable timestamping
1130 logger.timestamp = True
1129 logger.timestamp = True
1131
1130
1132 print ('Activating auto-logging. '
1131 print ('Activating auto-logging. '
1133 'Current session state plus future input saved.')
1132 'Current session state plus future input saved.')
1134 logger.logstate()
1133 logger.logstate()
1135
1134
1136 def magic_logstop(self,parameter_s=''):
1135 def magic_logstop(self,parameter_s=''):
1137 """Fully stop logging and close log file.
1136 """Fully stop logging and close log file.
1138
1137
1139 In order to start logging again, a new %logstart call needs to be made,
1138 In order to start logging again, a new %logstart call needs to be made,
1140 possibly (though not necessarily) with a new filename, mode and other
1139 possibly (though not necessarily) with a new filename, mode and other
1141 options."""
1140 options."""
1142 self.logger.logstop()
1141 self.logger.logstop()
1143
1142
1144 def magic_logoff(self,parameter_s=''):
1143 def magic_logoff(self,parameter_s=''):
1145 """Temporarily stop logging.
1144 """Temporarily stop logging.
1146
1145
1147 You must have previously started logging."""
1146 You must have previously started logging."""
1148 self.shell.logger.switch_log(0)
1147 self.shell.logger.switch_log(0)
1149
1148
1150 def magic_logon(self,parameter_s=''):
1149 def magic_logon(self,parameter_s=''):
1151 """Restart logging.
1150 """Restart logging.
1152
1151
1153 This function is for restarting logging which you've temporarily
1152 This function is for restarting logging which you've temporarily
1154 stopped with %logoff. For starting logging for the first time, you
1153 stopped with %logoff. For starting logging for the first time, you
1155 must use the %logstart function, which allows you to specify an
1154 must use the %logstart function, which allows you to specify an
1156 optional log filename."""
1155 optional log filename."""
1157
1156
1158 self.shell.logger.switch_log(1)
1157 self.shell.logger.switch_log(1)
1159
1158
1160 def magic_logstate(self,parameter_s=''):
1159 def magic_logstate(self,parameter_s=''):
1161 """Print the status of the logging system."""
1160 """Print the status of the logging system."""
1162
1161
1163 self.shell.logger.logstate()
1162 self.shell.logger.logstate()
1164
1163
1165 def magic_pdb(self, parameter_s=''):
1164 def magic_pdb(self, parameter_s=''):
1166 """Control the automatic calling of the pdb interactive debugger.
1165 """Control the automatic calling of the pdb interactive debugger.
1167
1166
1168 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1167 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1169 argument it works as a toggle.
1168 argument it works as a toggle.
1170
1169
1171 When an exception is triggered, IPython can optionally call the
1170 When an exception is triggered, IPython can optionally call the
1172 interactive pdb debugger after the traceback printout. %pdb toggles
1171 interactive pdb debugger after the traceback printout. %pdb toggles
1173 this feature on and off.
1172 this feature on and off.
1174
1173
1175 The initial state of this feature is set in your ipythonrc
1174 The initial state of this feature is set in your ipythonrc
1176 configuration file (the variable is called 'pdb').
1175 configuration file (the variable is called 'pdb').
1177
1176
1178 If you want to just activate the debugger AFTER an exception has fired,
1177 If you want to just activate the debugger AFTER an exception has fired,
1179 without having to type '%pdb on' and rerunning your code, you can use
1178 without having to type '%pdb on' and rerunning your code, you can use
1180 the %debug magic."""
1179 the %debug magic."""
1181
1180
1182 par = parameter_s.strip().lower()
1181 par = parameter_s.strip().lower()
1183
1182
1184 if par:
1183 if par:
1185 try:
1184 try:
1186 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1185 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1187 except KeyError:
1186 except KeyError:
1188 print ('Incorrect argument. Use on/1, off/0, '
1187 print ('Incorrect argument. Use on/1, off/0, '
1189 'or nothing for a toggle.')
1188 'or nothing for a toggle.')
1190 return
1189 return
1191 else:
1190 else:
1192 # toggle
1191 # toggle
1193 new_pdb = not self.shell.call_pdb
1192 new_pdb = not self.shell.call_pdb
1194
1193
1195 # set on the shell
1194 # set on the shell
1196 self.shell.call_pdb = new_pdb
1195 self.shell.call_pdb = new_pdb
1197 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1196 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1198
1197
1199 def magic_debug(self, parameter_s=''):
1198 def magic_debug(self, parameter_s=''):
1200 """Activate the interactive debugger in post-mortem mode.
1199 """Activate the interactive debugger in post-mortem mode.
1201
1200
1202 If an exception has just occurred, this lets you inspect its stack
1201 If an exception has just occurred, this lets you inspect its stack
1203 frames interactively. Note that this will always work only on the last
1202 frames interactively. Note that this will always work only on the last
1204 traceback that occurred, so you must call this quickly after an
1203 traceback that occurred, so you must call this quickly after an
1205 exception that you wish to inspect has fired, because if another one
1204 exception that you wish to inspect has fired, because if another one
1206 occurs, it clobbers the previous one.
1205 occurs, it clobbers the previous one.
1207
1206
1208 If you want IPython to automatically do this on every exception, see
1207 If you want IPython to automatically do this on every exception, see
1209 the %pdb magic for more details.
1208 the %pdb magic for more details.
1210 """
1209 """
1211 self.shell.debugger(force=True)
1210 self.shell.debugger(force=True)
1212
1211
1213 @testdec.skip_doctest
1212 @testdec.skip_doctest
1214 def magic_prun(self, parameter_s ='',user_mode=1,
1213 def magic_prun(self, parameter_s ='',user_mode=1,
1215 opts=None,arg_lst=None,prog_ns=None):
1214 opts=None,arg_lst=None,prog_ns=None):
1216
1215
1217 """Run a statement through the python code profiler.
1216 """Run a statement through the python code profiler.
1218
1217
1219 Usage:
1218 Usage:
1220 %prun [options] statement
1219 %prun [options] statement
1221
1220
1222 The given statement (which doesn't require quote marks) is run via the
1221 The given statement (which doesn't require quote marks) is run via the
1223 python profiler in a manner similar to the profile.run() function.
1222 python profiler in a manner similar to the profile.run() function.
1224 Namespaces are internally managed to work correctly; profile.run
1223 Namespaces are internally managed to work correctly; profile.run
1225 cannot be used in IPython because it makes certain assumptions about
1224 cannot be used in IPython because it makes certain assumptions about
1226 namespaces which do not hold under IPython.
1225 namespaces which do not hold under IPython.
1227
1226
1228 Options:
1227 Options:
1229
1228
1230 -l <limit>: you can place restrictions on what or how much of the
1229 -l <limit>: you can place restrictions on what or how much of the
1231 profile gets printed. The limit value can be:
1230 profile gets printed. The limit value can be:
1232
1231
1233 * A string: only information for function names containing this string
1232 * A string: only information for function names containing this string
1234 is printed.
1233 is printed.
1235
1234
1236 * An integer: only these many lines are printed.
1235 * An integer: only these many lines are printed.
1237
1236
1238 * A float (between 0 and 1): this fraction of the report is printed
1237 * A float (between 0 and 1): this fraction of the report is printed
1239 (for example, use a limit of 0.4 to see the topmost 40% only).
1238 (for example, use a limit of 0.4 to see the topmost 40% only).
1240
1239
1241 You can combine several limits with repeated use of the option. For
1240 You can combine several limits with repeated use of the option. For
1242 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1241 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1243 information about class constructors.
1242 information about class constructors.
1244
1243
1245 -r: return the pstats.Stats object generated by the profiling. This
1244 -r: return the pstats.Stats object generated by the profiling. This
1246 object has all the information about the profile in it, and you can
1245 object has all the information about the profile in it, and you can
1247 later use it for further analysis or in other functions.
1246 later use it for further analysis or in other functions.
1248
1247
1249 -s <key>: sort profile by given key. You can provide more than one key
1248 -s <key>: sort profile by given key. You can provide more than one key
1250 by using the option several times: '-s key1 -s key2 -s key3...'. The
1249 by using the option several times: '-s key1 -s key2 -s key3...'. The
1251 default sorting key is 'time'.
1250 default sorting key is 'time'.
1252
1251
1253 The following is copied verbatim from the profile documentation
1252 The following is copied verbatim from the profile documentation
1254 referenced below:
1253 referenced below:
1255
1254
1256 When more than one key is provided, additional keys are used as
1255 When more than one key is provided, additional keys are used as
1257 secondary criteria when the there is equality in all keys selected
1256 secondary criteria when the there is equality in all keys selected
1258 before them.
1257 before them.
1259
1258
1260 Abbreviations can be used for any key names, as long as the
1259 Abbreviations can be used for any key names, as long as the
1261 abbreviation is unambiguous. The following are the keys currently
1260 abbreviation is unambiguous. The following are the keys currently
1262 defined:
1261 defined:
1263
1262
1264 Valid Arg Meaning
1263 Valid Arg Meaning
1265 "calls" call count
1264 "calls" call count
1266 "cumulative" cumulative time
1265 "cumulative" cumulative time
1267 "file" file name
1266 "file" file name
1268 "module" file name
1267 "module" file name
1269 "pcalls" primitive call count
1268 "pcalls" primitive call count
1270 "line" line number
1269 "line" line number
1271 "name" function name
1270 "name" function name
1272 "nfl" name/file/line
1271 "nfl" name/file/line
1273 "stdname" standard name
1272 "stdname" standard name
1274 "time" internal time
1273 "time" internal time
1275
1274
1276 Note that all sorts on statistics are in descending order (placing
1275 Note that all sorts on statistics are in descending order (placing
1277 most time consuming items first), where as name, file, and line number
1276 most time consuming items first), where as name, file, and line number
1278 searches are in ascending order (i.e., alphabetical). The subtle
1277 searches are in ascending order (i.e., alphabetical). The subtle
1279 distinction between "nfl" and "stdname" is that the standard name is a
1278 distinction between "nfl" and "stdname" is that the standard name is a
1280 sort of the name as printed, which means that the embedded line
1279 sort of the name as printed, which means that the embedded line
1281 numbers get compared in an odd way. For example, lines 3, 20, and 40
1280 numbers get compared in an odd way. For example, lines 3, 20, and 40
1282 would (if the file names were the same) appear in the string order
1281 would (if the file names were the same) appear in the string order
1283 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1282 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1284 line numbers. In fact, sort_stats("nfl") is the same as
1283 line numbers. In fact, sort_stats("nfl") is the same as
1285 sort_stats("name", "file", "line").
1284 sort_stats("name", "file", "line").
1286
1285
1287 -T <filename>: save profile results as shown on screen to a text
1286 -T <filename>: save profile results as shown on screen to a text
1288 file. The profile is still shown on screen.
1287 file. The profile is still shown on screen.
1289
1288
1290 -D <filename>: save (via dump_stats) profile statistics to given
1289 -D <filename>: save (via dump_stats) profile statistics to given
1291 filename. This data is in a format understod by the pstats module, and
1290 filename. This data is in a format understod by the pstats module, and
1292 is generated by a call to the dump_stats() method of profile
1291 is generated by a call to the dump_stats() method of profile
1293 objects. The profile is still shown on screen.
1292 objects. The profile is still shown on screen.
1294
1293
1295 If you want to run complete programs under the profiler's control, use
1294 If you want to run complete programs under the profiler's control, use
1296 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1295 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1297 contains profiler specific options as described here.
1296 contains profiler specific options as described here.
1298
1297
1299 You can read the complete documentation for the profile module with::
1298 You can read the complete documentation for the profile module with::
1300
1299
1301 In [1]: import profile; profile.help()
1300 In [1]: import profile; profile.help()
1302 """
1301 """
1303
1302
1304 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1303 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1305 # protect user quote marks
1304 # protect user quote marks
1306 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1305 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1307
1306
1308 if user_mode: # regular user call
1307 if user_mode: # regular user call
1309 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1308 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1310 list_all=1)
1309 list_all=1)
1311 namespace = self.shell.user_ns
1310 namespace = self.shell.user_ns
1312 else: # called to run a program by %run -p
1311 else: # called to run a program by %run -p
1313 try:
1312 try:
1314 filename = get_py_filename(arg_lst[0])
1313 filename = get_py_filename(arg_lst[0])
1315 except IOError,msg:
1314 except IOError,msg:
1316 error(msg)
1315 error(msg)
1317 return
1316 return
1318
1317
1319 arg_str = 'execfile(filename,prog_ns)'
1318 arg_str = 'execfile(filename,prog_ns)'
1320 namespace = locals()
1319 namespace = locals()
1321
1320
1322 opts.merge(opts_def)
1321 opts.merge(opts_def)
1323
1322
1324 prof = profile.Profile()
1323 prof = profile.Profile()
1325 try:
1324 try:
1326 prof = prof.runctx(arg_str,namespace,namespace)
1325 prof = prof.runctx(arg_str,namespace,namespace)
1327 sys_exit = ''
1326 sys_exit = ''
1328 except SystemExit:
1327 except SystemExit:
1329 sys_exit = """*** SystemExit exception caught in code being profiled."""
1328 sys_exit = """*** SystemExit exception caught in code being profiled."""
1330
1329
1331 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1330 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1332
1331
1333 lims = opts.l
1332 lims = opts.l
1334 if lims:
1333 if lims:
1335 lims = [] # rebuild lims with ints/floats/strings
1334 lims = [] # rebuild lims with ints/floats/strings
1336 for lim in opts.l:
1335 for lim in opts.l:
1337 try:
1336 try:
1338 lims.append(int(lim))
1337 lims.append(int(lim))
1339 except ValueError:
1338 except ValueError:
1340 try:
1339 try:
1341 lims.append(float(lim))
1340 lims.append(float(lim))
1342 except ValueError:
1341 except ValueError:
1343 lims.append(lim)
1342 lims.append(lim)
1344
1343
1345 # Trap output.
1344 # Trap output.
1346 stdout_trap = StringIO()
1345 stdout_trap = StringIO()
1347
1346
1348 if hasattr(stats,'stream'):
1347 if hasattr(stats,'stream'):
1349 # In newer versions of python, the stats object has a 'stream'
1348 # In newer versions of python, the stats object has a 'stream'
1350 # attribute to write into.
1349 # attribute to write into.
1351 stats.stream = stdout_trap
1350 stats.stream = stdout_trap
1352 stats.print_stats(*lims)
1351 stats.print_stats(*lims)
1353 else:
1352 else:
1354 # For older versions, we manually redirect stdout during printing
1353 # For older versions, we manually redirect stdout during printing
1355 sys_stdout = sys.stdout
1354 sys_stdout = sys.stdout
1356 try:
1355 try:
1357 sys.stdout = stdout_trap
1356 sys.stdout = stdout_trap
1358 stats.print_stats(*lims)
1357 stats.print_stats(*lims)
1359 finally:
1358 finally:
1360 sys.stdout = sys_stdout
1359 sys.stdout = sys_stdout
1361
1360
1362 output = stdout_trap.getvalue()
1361 output = stdout_trap.getvalue()
1363 output = output.rstrip()
1362 output = output.rstrip()
1364
1363
1365 page.page(output)
1364 page.page(output)
1366 print sys_exit,
1365 print sys_exit,
1367
1366
1368 dump_file = opts.D[0]
1367 dump_file = opts.D[0]
1369 text_file = opts.T[0]
1368 text_file = opts.T[0]
1370 if dump_file:
1369 if dump_file:
1371 prof.dump_stats(dump_file)
1370 prof.dump_stats(dump_file)
1372 print '\n*** Profile stats marshalled to file',\
1371 print '\n*** Profile stats marshalled to file',\
1373 `dump_file`+'.',sys_exit
1372 `dump_file`+'.',sys_exit
1374 if text_file:
1373 if text_file:
1375 pfile = file(text_file,'w')
1374 pfile = file(text_file,'w')
1376 pfile.write(output)
1375 pfile.write(output)
1377 pfile.close()
1376 pfile.close()
1378 print '\n*** Profile printout saved to text file',\
1377 print '\n*** Profile printout saved to text file',\
1379 `text_file`+'.',sys_exit
1378 `text_file`+'.',sys_exit
1380
1379
1381 if opts.has_key('r'):
1380 if opts.has_key('r'):
1382 return stats
1381 return stats
1383 else:
1382 else:
1384 return None
1383 return None
1385
1384
1386 @testdec.skip_doctest
1385 @testdec.skip_doctest
1387 def magic_run(self, parameter_s ='',runner=None,
1386 def magic_run(self, parameter_s ='',runner=None,
1388 file_finder=get_py_filename):
1387 file_finder=get_py_filename):
1389 """Run the named file inside IPython as a program.
1388 """Run the named file inside IPython as a program.
1390
1389
1391 Usage:\\
1390 Usage:\\
1392 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1391 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1393
1392
1394 Parameters after the filename are passed as command-line arguments to
1393 Parameters after the filename are passed as command-line arguments to
1395 the program (put in sys.argv). Then, control returns to IPython's
1394 the program (put in sys.argv). Then, control returns to IPython's
1396 prompt.
1395 prompt.
1397
1396
1398 This is similar to running at a system prompt:\\
1397 This is similar to running at a system prompt:\\
1399 $ python file args\\
1398 $ python file args\\
1400 but with the advantage of giving you IPython's tracebacks, and of
1399 but with the advantage of giving you IPython's tracebacks, and of
1401 loading all variables into your interactive namespace for further use
1400 loading all variables into your interactive namespace for further use
1402 (unless -p is used, see below).
1401 (unless -p is used, see below).
1403
1402
1404 The file is executed in a namespace initially consisting only of
1403 The file is executed in a namespace initially consisting only of
1405 __name__=='__main__' and sys.argv constructed as indicated. It thus
1404 __name__=='__main__' and sys.argv constructed as indicated. It thus
1406 sees its environment as if it were being run as a stand-alone program
1405 sees its environment as if it were being run as a stand-alone program
1407 (except for sharing global objects such as previously imported
1406 (except for sharing global objects such as previously imported
1408 modules). But after execution, the IPython interactive namespace gets
1407 modules). But after execution, the IPython interactive namespace gets
1409 updated with all variables defined in the program (except for __name__
1408 updated with all variables defined in the program (except for __name__
1410 and sys.argv). This allows for very convenient loading of code for
1409 and sys.argv). This allows for very convenient loading of code for
1411 interactive work, while giving each program a 'clean sheet' to run in.
1410 interactive work, while giving each program a 'clean sheet' to run in.
1412
1411
1413 Options:
1412 Options:
1414
1413
1415 -n: __name__ is NOT set to '__main__', but to the running file's name
1414 -n: __name__ is NOT set to '__main__', but to the running file's name
1416 without extension (as python does under import). This allows running
1415 without extension (as python does under import). This allows running
1417 scripts and reloading the definitions in them without calling code
1416 scripts and reloading the definitions in them without calling code
1418 protected by an ' if __name__ == "__main__" ' clause.
1417 protected by an ' if __name__ == "__main__" ' clause.
1419
1418
1420 -i: run the file in IPython's namespace instead of an empty one. This
1419 -i: run the file in IPython's namespace instead of an empty one. This
1421 is useful if you are experimenting with code written in a text editor
1420 is useful if you are experimenting with code written in a text editor
1422 which depends on variables defined interactively.
1421 which depends on variables defined interactively.
1423
1422
1424 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1423 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1425 being run. This is particularly useful if IPython is being used to
1424 being run. This is particularly useful if IPython is being used to
1426 run unittests, which always exit with a sys.exit() call. In such
1425 run unittests, which always exit with a sys.exit() call. In such
1427 cases you are interested in the output of the test results, not in
1426 cases you are interested in the output of the test results, not in
1428 seeing a traceback of the unittest module.
1427 seeing a traceback of the unittest module.
1429
1428
1430 -t: print timing information at the end of the run. IPython will give
1429 -t: print timing information at the end of the run. IPython will give
1431 you an estimated CPU time consumption for your script, which under
1430 you an estimated CPU time consumption for your script, which under
1432 Unix uses the resource module to avoid the wraparound problems of
1431 Unix uses the resource module to avoid the wraparound problems of
1433 time.clock(). Under Unix, an estimate of time spent on system tasks
1432 time.clock(). Under Unix, an estimate of time spent on system tasks
1434 is also given (for Windows platforms this is reported as 0.0).
1433 is also given (for Windows platforms this is reported as 0.0).
1435
1434
1436 If -t is given, an additional -N<N> option can be given, where <N>
1435 If -t is given, an additional -N<N> option can be given, where <N>
1437 must be an integer indicating how many times you want the script to
1436 must be an integer indicating how many times you want the script to
1438 run. The final timing report will include total and per run results.
1437 run. The final timing report will include total and per run results.
1439
1438
1440 For example (testing the script uniq_stable.py):
1439 For example (testing the script uniq_stable.py):
1441
1440
1442 In [1]: run -t uniq_stable
1441 In [1]: run -t uniq_stable
1443
1442
1444 IPython CPU timings (estimated):\\
1443 IPython CPU timings (estimated):\\
1445 User : 0.19597 s.\\
1444 User : 0.19597 s.\\
1446 System: 0.0 s.\\
1445 System: 0.0 s.\\
1447
1446
1448 In [2]: run -t -N5 uniq_stable
1447 In [2]: run -t -N5 uniq_stable
1449
1448
1450 IPython CPU timings (estimated):\\
1449 IPython CPU timings (estimated):\\
1451 Total runs performed: 5\\
1450 Total runs performed: 5\\
1452 Times : Total Per run\\
1451 Times : Total Per run\\
1453 User : 0.910862 s, 0.1821724 s.\\
1452 User : 0.910862 s, 0.1821724 s.\\
1454 System: 0.0 s, 0.0 s.
1453 System: 0.0 s, 0.0 s.
1455
1454
1456 -d: run your program under the control of pdb, the Python debugger.
1455 -d: run your program under the control of pdb, the Python debugger.
1457 This allows you to execute your program step by step, watch variables,
1456 This allows you to execute your program step by step, watch variables,
1458 etc. Internally, what IPython does is similar to calling:
1457 etc. Internally, what IPython does is similar to calling:
1459
1458
1460 pdb.run('execfile("YOURFILENAME")')
1459 pdb.run('execfile("YOURFILENAME")')
1461
1460
1462 with a breakpoint set on line 1 of your file. You can change the line
1461 with a breakpoint set on line 1 of your file. You can change the line
1463 number for this automatic breakpoint to be <N> by using the -bN option
1462 number for this automatic breakpoint to be <N> by using the -bN option
1464 (where N must be an integer). For example:
1463 (where N must be an integer). For example:
1465
1464
1466 %run -d -b40 myscript
1465 %run -d -b40 myscript
1467
1466
1468 will set the first breakpoint at line 40 in myscript.py. Note that
1467 will set the first breakpoint at line 40 in myscript.py. Note that
1469 the first breakpoint must be set on a line which actually does
1468 the first breakpoint must be set on a line which actually does
1470 something (not a comment or docstring) for it to stop execution.
1469 something (not a comment or docstring) for it to stop execution.
1471
1470
1472 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1471 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1473 first enter 'c' (without qoutes) to start execution up to the first
1472 first enter 'c' (without qoutes) to start execution up to the first
1474 breakpoint.
1473 breakpoint.
1475
1474
1476 Entering 'help' gives information about the use of the debugger. You
1475 Entering 'help' gives information about the use of the debugger. You
1477 can easily see pdb's full documentation with "import pdb;pdb.help()"
1476 can easily see pdb's full documentation with "import pdb;pdb.help()"
1478 at a prompt.
1477 at a prompt.
1479
1478
1480 -p: run program under the control of the Python profiler module (which
1479 -p: run program under the control of the Python profiler module (which
1481 prints a detailed report of execution times, function calls, etc).
1480 prints a detailed report of execution times, function calls, etc).
1482
1481
1483 You can pass other options after -p which affect the behavior of the
1482 You can pass other options after -p which affect the behavior of the
1484 profiler itself. See the docs for %prun for details.
1483 profiler itself. See the docs for %prun for details.
1485
1484
1486 In this mode, the program's variables do NOT propagate back to the
1485 In this mode, the program's variables do NOT propagate back to the
1487 IPython interactive namespace (because they remain in the namespace
1486 IPython interactive namespace (because they remain in the namespace
1488 where the profiler executes them).
1487 where the profiler executes them).
1489
1488
1490 Internally this triggers a call to %prun, see its documentation for
1489 Internally this triggers a call to %prun, see its documentation for
1491 details on the options available specifically for profiling.
1490 details on the options available specifically for profiling.
1492
1491
1493 There is one special usage for which the text above doesn't apply:
1492 There is one special usage for which the text above doesn't apply:
1494 if the filename ends with .ipy, the file is run as ipython script,
1493 if the filename ends with .ipy, the file is run as ipython script,
1495 just as if the commands were written on IPython prompt.
1494 just as if the commands were written on IPython prompt.
1496 """
1495 """
1497
1496
1498 # get arguments and set sys.argv for program to be run.
1497 # get arguments and set sys.argv for program to be run.
1499 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1498 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1500 mode='list',list_all=1)
1499 mode='list',list_all=1)
1501
1500
1502 try:
1501 try:
1503 filename = file_finder(arg_lst[0])
1502 filename = file_finder(arg_lst[0])
1504 except IndexError:
1503 except IndexError:
1505 warn('you must provide at least a filename.')
1504 warn('you must provide at least a filename.')
1506 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1505 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1507 return
1506 return
1508 except IOError,msg:
1507 except IOError,msg:
1509 error(msg)
1508 error(msg)
1510 return
1509 return
1511
1510
1512 if filename.lower().endswith('.ipy'):
1511 if filename.lower().endswith('.ipy'):
1513 self.shell.safe_execfile_ipy(filename)
1512 self.shell.safe_execfile_ipy(filename)
1514 return
1513 return
1515
1514
1516 # Control the response to exit() calls made by the script being run
1515 # Control the response to exit() calls made by the script being run
1517 exit_ignore = opts.has_key('e')
1516 exit_ignore = opts.has_key('e')
1518
1517
1519 # Make sure that the running script gets a proper sys.argv as if it
1518 # Make sure that the running script gets a proper sys.argv as if it
1520 # were run from a system shell.
1519 # were run from a system shell.
1521 save_argv = sys.argv # save it for later restoring
1520 save_argv = sys.argv # save it for later restoring
1522 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1521 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1523
1522
1524 if opts.has_key('i'):
1523 if opts.has_key('i'):
1525 # Run in user's interactive namespace
1524 # Run in user's interactive namespace
1526 prog_ns = self.shell.user_ns
1525 prog_ns = self.shell.user_ns
1527 __name__save = self.shell.user_ns['__name__']
1526 __name__save = self.shell.user_ns['__name__']
1528 prog_ns['__name__'] = '__main__'
1527 prog_ns['__name__'] = '__main__'
1529 main_mod = self.shell.new_main_mod(prog_ns)
1528 main_mod = self.shell.new_main_mod(prog_ns)
1530 else:
1529 else:
1531 # Run in a fresh, empty namespace
1530 # Run in a fresh, empty namespace
1532 if opts.has_key('n'):
1531 if opts.has_key('n'):
1533 name = os.path.splitext(os.path.basename(filename))[0]
1532 name = os.path.splitext(os.path.basename(filename))[0]
1534 else:
1533 else:
1535 name = '__main__'
1534 name = '__main__'
1536
1535
1537 main_mod = self.shell.new_main_mod()
1536 main_mod = self.shell.new_main_mod()
1538 prog_ns = main_mod.__dict__
1537 prog_ns = main_mod.__dict__
1539 prog_ns['__name__'] = name
1538 prog_ns['__name__'] = name
1540
1539
1541 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1540 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1542 # set the __file__ global in the script's namespace
1541 # set the __file__ global in the script's namespace
1543 prog_ns['__file__'] = filename
1542 prog_ns['__file__'] = filename
1544
1543
1545 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1544 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1546 # that, if we overwrite __main__, we replace it at the end
1545 # that, if we overwrite __main__, we replace it at the end
1547 main_mod_name = prog_ns['__name__']
1546 main_mod_name = prog_ns['__name__']
1548
1547
1549 if main_mod_name == '__main__':
1548 if main_mod_name == '__main__':
1550 restore_main = sys.modules['__main__']
1549 restore_main = sys.modules['__main__']
1551 else:
1550 else:
1552 restore_main = False
1551 restore_main = False
1553
1552
1554 # This needs to be undone at the end to prevent holding references to
1553 # This needs to be undone at the end to prevent holding references to
1555 # every single object ever created.
1554 # every single object ever created.
1556 sys.modules[main_mod_name] = main_mod
1555 sys.modules[main_mod_name] = main_mod
1557
1556
1558 stats = None
1557 stats = None
1559 try:
1558 try:
1560 self.shell.savehist()
1559 self.shell.savehist()
1561
1560
1562 if opts.has_key('p'):
1561 if opts.has_key('p'):
1563 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1562 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1564 else:
1563 else:
1565 if opts.has_key('d'):
1564 if opts.has_key('d'):
1566 deb = debugger.Pdb(self.shell.colors)
1565 deb = debugger.Pdb(self.shell.colors)
1567 # reset Breakpoint state, which is moronically kept
1566 # reset Breakpoint state, which is moronically kept
1568 # in a class
1567 # in a class
1569 bdb.Breakpoint.next = 1
1568 bdb.Breakpoint.next = 1
1570 bdb.Breakpoint.bplist = {}
1569 bdb.Breakpoint.bplist = {}
1571 bdb.Breakpoint.bpbynumber = [None]
1570 bdb.Breakpoint.bpbynumber = [None]
1572 # Set an initial breakpoint to stop execution
1571 # Set an initial breakpoint to stop execution
1573 maxtries = 10
1572 maxtries = 10
1574 bp = int(opts.get('b',[1])[0])
1573 bp = int(opts.get('b',[1])[0])
1575 checkline = deb.checkline(filename,bp)
1574 checkline = deb.checkline(filename,bp)
1576 if not checkline:
1575 if not checkline:
1577 for bp in range(bp+1,bp+maxtries+1):
1576 for bp in range(bp+1,bp+maxtries+1):
1578 if deb.checkline(filename,bp):
1577 if deb.checkline(filename,bp):
1579 break
1578 break
1580 else:
1579 else:
1581 msg = ("\nI failed to find a valid line to set "
1580 msg = ("\nI failed to find a valid line to set "
1582 "a breakpoint\n"
1581 "a breakpoint\n"
1583 "after trying up to line: %s.\n"
1582 "after trying up to line: %s.\n"
1584 "Please set a valid breakpoint manually "
1583 "Please set a valid breakpoint manually "
1585 "with the -b option." % bp)
1584 "with the -b option." % bp)
1586 error(msg)
1585 error(msg)
1587 return
1586 return
1588 # if we find a good linenumber, set the breakpoint
1587 # if we find a good linenumber, set the breakpoint
1589 deb.do_break('%s:%s' % (filename,bp))
1588 deb.do_break('%s:%s' % (filename,bp))
1590 # Start file run
1589 # Start file run
1591 print "NOTE: Enter 'c' at the",
1590 print "NOTE: Enter 'c' at the",
1592 print "%s prompt to start your script." % deb.prompt
1591 print "%s prompt to start your script." % deb.prompt
1593 try:
1592 try:
1594 deb.run('execfile("%s")' % filename,prog_ns)
1593 deb.run('execfile("%s")' % filename,prog_ns)
1595
1594
1596 except:
1595 except:
1597 etype, value, tb = sys.exc_info()
1596 etype, value, tb = sys.exc_info()
1598 # Skip three frames in the traceback: the %run one,
1597 # Skip three frames in the traceback: the %run one,
1599 # one inside bdb.py, and the command-line typed by the
1598 # one inside bdb.py, and the command-line typed by the
1600 # user (run by exec in pdb itself).
1599 # user (run by exec in pdb itself).
1601 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1600 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1602 else:
1601 else:
1603 if runner is None:
1602 if runner is None:
1604 runner = self.shell.safe_execfile
1603 runner = self.shell.safe_execfile
1605 if opts.has_key('t'):
1604 if opts.has_key('t'):
1606 # timed execution
1605 # timed execution
1607 try:
1606 try:
1608 nruns = int(opts['N'][0])
1607 nruns = int(opts['N'][0])
1609 if nruns < 1:
1608 if nruns < 1:
1610 error('Number of runs must be >=1')
1609 error('Number of runs must be >=1')
1611 return
1610 return
1612 except (KeyError):
1611 except (KeyError):
1613 nruns = 1
1612 nruns = 1
1614 if nruns == 1:
1613 if nruns == 1:
1615 t0 = clock2()
1614 t0 = clock2()
1616 runner(filename,prog_ns,prog_ns,
1615 runner(filename,prog_ns,prog_ns,
1617 exit_ignore=exit_ignore)
1616 exit_ignore=exit_ignore)
1618 t1 = clock2()
1617 t1 = clock2()
1619 t_usr = t1[0]-t0[0]
1618 t_usr = t1[0]-t0[0]
1620 t_sys = t1[1]-t0[1]
1619 t_sys = t1[1]-t0[1]
1621 print "\nIPython CPU timings (estimated):"
1620 print "\nIPython CPU timings (estimated):"
1622 print " User : %10s s." % t_usr
1621 print " User : %10s s." % t_usr
1623 print " System: %10s s." % t_sys
1622 print " System: %10s s." % t_sys
1624 else:
1623 else:
1625 runs = range(nruns)
1624 runs = range(nruns)
1626 t0 = clock2()
1625 t0 = clock2()
1627 for nr in runs:
1626 for nr in runs:
1628 runner(filename,prog_ns,prog_ns,
1627 runner(filename,prog_ns,prog_ns,
1629 exit_ignore=exit_ignore)
1628 exit_ignore=exit_ignore)
1630 t1 = clock2()
1629 t1 = clock2()
1631 t_usr = t1[0]-t0[0]
1630 t_usr = t1[0]-t0[0]
1632 t_sys = t1[1]-t0[1]
1631 t_sys = t1[1]-t0[1]
1633 print "\nIPython CPU timings (estimated):"
1632 print "\nIPython CPU timings (estimated):"
1634 print "Total runs performed:",nruns
1633 print "Total runs performed:",nruns
1635 print " Times : %10s %10s" % ('Total','Per run')
1634 print " Times : %10s %10s" % ('Total','Per run')
1636 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1635 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1637 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1636 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1638
1637
1639 else:
1638 else:
1640 # regular execution
1639 # regular execution
1641 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1640 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1642
1641
1643 if opts.has_key('i'):
1642 if opts.has_key('i'):
1644 self.shell.user_ns['__name__'] = __name__save
1643 self.shell.user_ns['__name__'] = __name__save
1645 else:
1644 else:
1646 # The shell MUST hold a reference to prog_ns so after %run
1645 # The shell MUST hold a reference to prog_ns so after %run
1647 # exits, the python deletion mechanism doesn't zero it out
1646 # exits, the python deletion mechanism doesn't zero it out
1648 # (leaving dangling references).
1647 # (leaving dangling references).
1649 self.shell.cache_main_mod(prog_ns,filename)
1648 self.shell.cache_main_mod(prog_ns,filename)
1650 # update IPython interactive namespace
1649 # update IPython interactive namespace
1651
1650
1652 # Some forms of read errors on the file may mean the
1651 # Some forms of read errors on the file may mean the
1653 # __name__ key was never set; using pop we don't have to
1652 # __name__ key was never set; using pop we don't have to
1654 # worry about a possible KeyError.
1653 # worry about a possible KeyError.
1655 prog_ns.pop('__name__', None)
1654 prog_ns.pop('__name__', None)
1656
1655
1657 self.shell.user_ns.update(prog_ns)
1656 self.shell.user_ns.update(prog_ns)
1658 finally:
1657 finally:
1659 # It's a bit of a mystery why, but __builtins__ can change from
1658 # It's a bit of a mystery why, but __builtins__ can change from
1660 # being a module to becoming a dict missing some key data after
1659 # being a module to becoming a dict missing some key data after
1661 # %run. As best I can see, this is NOT something IPython is doing
1660 # %run. As best I can see, this is NOT something IPython is doing
1662 # at all, and similar problems have been reported before:
1661 # at all, and similar problems have been reported before:
1663 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1662 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1664 # Since this seems to be done by the interpreter itself, the best
1663 # Since this seems to be done by the interpreter itself, the best
1665 # we can do is to at least restore __builtins__ for the user on
1664 # we can do is to at least restore __builtins__ for the user on
1666 # exit.
1665 # exit.
1667 self.shell.user_ns['__builtins__'] = __builtin__
1666 self.shell.user_ns['__builtins__'] = __builtin__
1668
1667
1669 # Ensure key global structures are restored
1668 # Ensure key global structures are restored
1670 sys.argv = save_argv
1669 sys.argv = save_argv
1671 if restore_main:
1670 if restore_main:
1672 sys.modules['__main__'] = restore_main
1671 sys.modules['__main__'] = restore_main
1673 else:
1672 else:
1674 # Remove from sys.modules the reference to main_mod we'd
1673 # Remove from sys.modules the reference to main_mod we'd
1675 # added. Otherwise it will trap references to objects
1674 # added. Otherwise it will trap references to objects
1676 # contained therein.
1675 # contained therein.
1677 del sys.modules[main_mod_name]
1676 del sys.modules[main_mod_name]
1678
1677
1679 self.shell.reloadhist()
1678 self.shell.reloadhist()
1680
1679
1681 return stats
1680 return stats
1682
1681
1683 @testdec.skip_doctest
1682 @testdec.skip_doctest
1684 def magic_timeit(self, parameter_s =''):
1683 def magic_timeit(self, parameter_s =''):
1685 """Time execution of a Python statement or expression
1684 """Time execution of a Python statement or expression
1686
1685
1687 Usage:\\
1686 Usage:\\
1688 %timeit [-n<N> -r<R> [-t|-c]] statement
1687 %timeit [-n<N> -r<R> [-t|-c]] statement
1689
1688
1690 Time execution of a Python statement or expression using the timeit
1689 Time execution of a Python statement or expression using the timeit
1691 module.
1690 module.
1692
1691
1693 Options:
1692 Options:
1694 -n<N>: execute the given statement <N> times in a loop. If this value
1693 -n<N>: execute the given statement <N> times in a loop. If this value
1695 is not given, a fitting value is chosen.
1694 is not given, a fitting value is chosen.
1696
1695
1697 -r<R>: repeat the loop iteration <R> times and take the best result.
1696 -r<R>: repeat the loop iteration <R> times and take the best result.
1698 Default: 3
1697 Default: 3
1699
1698
1700 -t: use time.time to measure the time, which is the default on Unix.
1699 -t: use time.time to measure the time, which is the default on Unix.
1701 This function measures wall time.
1700 This function measures wall time.
1702
1701
1703 -c: use time.clock to measure the time, which is the default on
1702 -c: use time.clock to measure the time, which is the default on
1704 Windows and measures wall time. On Unix, resource.getrusage is used
1703 Windows and measures wall time. On Unix, resource.getrusage is used
1705 instead and returns the CPU user time.
1704 instead and returns the CPU user time.
1706
1705
1707 -p<P>: use a precision of <P> digits to display the timing result.
1706 -p<P>: use a precision of <P> digits to display the timing result.
1708 Default: 3
1707 Default: 3
1709
1708
1710
1709
1711 Examples:
1710 Examples:
1712
1711
1713 In [1]: %timeit pass
1712 In [1]: %timeit pass
1714 10000000 loops, best of 3: 53.3 ns per loop
1713 10000000 loops, best of 3: 53.3 ns per loop
1715
1714
1716 In [2]: u = None
1715 In [2]: u = None
1717
1716
1718 In [3]: %timeit u is None
1717 In [3]: %timeit u is None
1719 10000000 loops, best of 3: 184 ns per loop
1718 10000000 loops, best of 3: 184 ns per loop
1720
1719
1721 In [4]: %timeit -r 4 u == None
1720 In [4]: %timeit -r 4 u == None
1722 1000000 loops, best of 4: 242 ns per loop
1721 1000000 loops, best of 4: 242 ns per loop
1723
1722
1724 In [5]: import time
1723 In [5]: import time
1725
1724
1726 In [6]: %timeit -n1 time.sleep(2)
1725 In [6]: %timeit -n1 time.sleep(2)
1727 1 loops, best of 3: 2 s per loop
1726 1 loops, best of 3: 2 s per loop
1728
1727
1729
1728
1730 The times reported by %timeit will be slightly higher than those
1729 The times reported by %timeit will be slightly higher than those
1731 reported by the timeit.py script when variables are accessed. This is
1730 reported by the timeit.py script when variables are accessed. This is
1732 due to the fact that %timeit executes the statement in the namespace
1731 due to the fact that %timeit executes the statement in the namespace
1733 of the shell, compared with timeit.py, which uses a single setup
1732 of the shell, compared with timeit.py, which uses a single setup
1734 statement to import function or create variables. Generally, the bias
1733 statement to import function or create variables. Generally, the bias
1735 does not matter as long as results from timeit.py are not mixed with
1734 does not matter as long as results from timeit.py are not mixed with
1736 those from %timeit."""
1735 those from %timeit."""
1737
1736
1738 import timeit
1737 import timeit
1739 import math
1738 import math
1740
1739
1741 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1740 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1742 # certain terminals. Until we figure out a robust way of
1741 # certain terminals. Until we figure out a robust way of
1743 # auto-detecting if the terminal can deal with it, use plain 'us' for
1742 # auto-detecting if the terminal can deal with it, use plain 'us' for
1744 # microseconds. I am really NOT happy about disabling the proper
1743 # microseconds. I am really NOT happy about disabling the proper
1745 # 'micro' prefix, but crashing is worse... If anyone knows what the
1744 # 'micro' prefix, but crashing is worse... If anyone knows what the
1746 # right solution for this is, I'm all ears...
1745 # right solution for this is, I'm all ears...
1747 #
1746 #
1748 # Note: using
1747 # Note: using
1749 #
1748 #
1750 # s = u'\xb5'
1749 # s = u'\xb5'
1751 # s.encode(sys.getdefaultencoding())
1750 # s.encode(sys.getdefaultencoding())
1752 #
1751 #
1753 # is not sufficient, as I've seen terminals where that fails but
1752 # is not sufficient, as I've seen terminals where that fails but
1754 # print s
1753 # print s
1755 #
1754 #
1756 # succeeds
1755 # succeeds
1757 #
1756 #
1758 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1757 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1759
1758
1760 #units = [u"s", u"ms",u'\xb5',"ns"]
1759 #units = [u"s", u"ms",u'\xb5',"ns"]
1761 units = [u"s", u"ms",u'us',"ns"]
1760 units = [u"s", u"ms",u'us',"ns"]
1762
1761
1763 scaling = [1, 1e3, 1e6, 1e9]
1762 scaling = [1, 1e3, 1e6, 1e9]
1764
1763
1765 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1764 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1766 posix=False)
1765 posix=False)
1767 if stmt == "":
1766 if stmt == "":
1768 return
1767 return
1769 timefunc = timeit.default_timer
1768 timefunc = timeit.default_timer
1770 number = int(getattr(opts, "n", 0))
1769 number = int(getattr(opts, "n", 0))
1771 repeat = int(getattr(opts, "r", timeit.default_repeat))
1770 repeat = int(getattr(opts, "r", timeit.default_repeat))
1772 precision = int(getattr(opts, "p", 3))
1771 precision = int(getattr(opts, "p", 3))
1773 if hasattr(opts, "t"):
1772 if hasattr(opts, "t"):
1774 timefunc = time.time
1773 timefunc = time.time
1775 if hasattr(opts, "c"):
1774 if hasattr(opts, "c"):
1776 timefunc = clock
1775 timefunc = clock
1777
1776
1778 timer = timeit.Timer(timer=timefunc)
1777 timer = timeit.Timer(timer=timefunc)
1779 # this code has tight coupling to the inner workings of timeit.Timer,
1778 # this code has tight coupling to the inner workings of timeit.Timer,
1780 # but is there a better way to achieve that the code stmt has access
1779 # but is there a better way to achieve that the code stmt has access
1781 # to the shell namespace?
1780 # to the shell namespace?
1782
1781
1783 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1782 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1784 'setup': "pass"}
1783 'setup': "pass"}
1785 # Track compilation time so it can be reported if too long
1784 # Track compilation time so it can be reported if too long
1786 # Minimum time above which compilation time will be reported
1785 # Minimum time above which compilation time will be reported
1787 tc_min = 0.1
1786 tc_min = 0.1
1788
1787
1789 t0 = clock()
1788 t0 = clock()
1790 code = compile(src, "<magic-timeit>", "exec")
1789 code = compile(src, "<magic-timeit>", "exec")
1791 tc = clock()-t0
1790 tc = clock()-t0
1792
1791
1793 ns = {}
1792 ns = {}
1794 exec code in self.shell.user_ns, ns
1793 exec code in self.shell.user_ns, ns
1795 timer.inner = ns["inner"]
1794 timer.inner = ns["inner"]
1796
1795
1797 if number == 0:
1796 if number == 0:
1798 # determine number so that 0.2 <= total time < 2.0
1797 # determine number so that 0.2 <= total time < 2.0
1799 number = 1
1798 number = 1
1800 for i in range(1, 10):
1799 for i in range(1, 10):
1801 if timer.timeit(number) >= 0.2:
1800 if timer.timeit(number) >= 0.2:
1802 break
1801 break
1803 number *= 10
1802 number *= 10
1804
1803
1805 best = min(timer.repeat(repeat, number)) / number
1804 best = min(timer.repeat(repeat, number)) / number
1806
1805
1807 if best > 0.0 and best < 1000.0:
1806 if best > 0.0 and best < 1000.0:
1808 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1807 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1809 elif best >= 1000.0:
1808 elif best >= 1000.0:
1810 order = 0
1809 order = 0
1811 else:
1810 else:
1812 order = 3
1811 order = 3
1813 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1812 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1814 precision,
1813 precision,
1815 best * scaling[order],
1814 best * scaling[order],
1816 units[order])
1815 units[order])
1817 if tc > tc_min:
1816 if tc > tc_min:
1818 print "Compiler time: %.2f s" % tc
1817 print "Compiler time: %.2f s" % tc
1819
1818
1820 @testdec.skip_doctest
1819 @testdec.skip_doctest
1821 def magic_time(self,parameter_s = ''):
1820 def magic_time(self,parameter_s = ''):
1822 """Time execution of a Python statement or expression.
1821 """Time execution of a Python statement or expression.
1823
1822
1824 The CPU and wall clock times are printed, and the value of the
1823 The CPU and wall clock times are printed, and the value of the
1825 expression (if any) is returned. Note that under Win32, system time
1824 expression (if any) is returned. Note that under Win32, system time
1826 is always reported as 0, since it can not be measured.
1825 is always reported as 0, since it can not be measured.
1827
1826
1828 This function provides very basic timing functionality. In Python
1827 This function provides very basic timing functionality. In Python
1829 2.3, the timeit module offers more control and sophistication, so this
1828 2.3, the timeit module offers more control and sophistication, so this
1830 could be rewritten to use it (patches welcome).
1829 could be rewritten to use it (patches welcome).
1831
1830
1832 Some examples:
1831 Some examples:
1833
1832
1834 In [1]: time 2**128
1833 In [1]: time 2**128
1835 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1834 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1836 Wall time: 0.00
1835 Wall time: 0.00
1837 Out[1]: 340282366920938463463374607431768211456L
1836 Out[1]: 340282366920938463463374607431768211456L
1838
1837
1839 In [2]: n = 1000000
1838 In [2]: n = 1000000
1840
1839
1841 In [3]: time sum(range(n))
1840 In [3]: time sum(range(n))
1842 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1841 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1843 Wall time: 1.37
1842 Wall time: 1.37
1844 Out[3]: 499999500000L
1843 Out[3]: 499999500000L
1845
1844
1846 In [4]: time print 'hello world'
1845 In [4]: time print 'hello world'
1847 hello world
1846 hello world
1848 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1847 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1849 Wall time: 0.00
1848 Wall time: 0.00
1850
1849
1851 Note that the time needed by Python to compile the given expression
1850 Note that the time needed by Python to compile the given expression
1852 will be reported if it is more than 0.1s. In this example, the
1851 will be reported if it is more than 0.1s. In this example, the
1853 actual exponentiation is done by Python at compilation time, so while
1852 actual exponentiation is done by Python at compilation time, so while
1854 the expression can take a noticeable amount of time to compute, that
1853 the expression can take a noticeable amount of time to compute, that
1855 time is purely due to the compilation:
1854 time is purely due to the compilation:
1856
1855
1857 In [5]: time 3**9999;
1856 In [5]: time 3**9999;
1858 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1857 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1859 Wall time: 0.00 s
1858 Wall time: 0.00 s
1860
1859
1861 In [6]: time 3**999999;
1860 In [6]: time 3**999999;
1862 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1861 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1863 Wall time: 0.00 s
1862 Wall time: 0.00 s
1864 Compiler : 0.78 s
1863 Compiler : 0.78 s
1865 """
1864 """
1866
1865
1867 # fail immediately if the given expression can't be compiled
1866 # fail immediately if the given expression can't be compiled
1868
1867
1869 expr = self.shell.prefilter(parameter_s,False)
1868 expr = self.shell.prefilter(parameter_s,False)
1870
1869
1871 # Minimum time above which compilation time will be reported
1870 # Minimum time above which compilation time will be reported
1872 tc_min = 0.1
1871 tc_min = 0.1
1873
1872
1874 try:
1873 try:
1875 mode = 'eval'
1874 mode = 'eval'
1876 t0 = clock()
1875 t0 = clock()
1877 code = compile(expr,'<timed eval>',mode)
1876 code = compile(expr,'<timed eval>',mode)
1878 tc = clock()-t0
1877 tc = clock()-t0
1879 except SyntaxError:
1878 except SyntaxError:
1880 mode = 'exec'
1879 mode = 'exec'
1881 t0 = clock()
1880 t0 = clock()
1882 code = compile(expr,'<timed exec>',mode)
1881 code = compile(expr,'<timed exec>',mode)
1883 tc = clock()-t0
1882 tc = clock()-t0
1884 # skew measurement as little as possible
1883 # skew measurement as little as possible
1885 glob = self.shell.user_ns
1884 glob = self.shell.user_ns
1886 clk = clock2
1885 clk = clock2
1887 wtime = time.time
1886 wtime = time.time
1888 # time execution
1887 # time execution
1889 wall_st = wtime()
1888 wall_st = wtime()
1890 if mode=='eval':
1889 if mode=='eval':
1891 st = clk()
1890 st = clk()
1892 out = eval(code,glob)
1891 out = eval(code,glob)
1893 end = clk()
1892 end = clk()
1894 else:
1893 else:
1895 st = clk()
1894 st = clk()
1896 exec code in glob
1895 exec code in glob
1897 end = clk()
1896 end = clk()
1898 out = None
1897 out = None
1899 wall_end = wtime()
1898 wall_end = wtime()
1900 # Compute actual times and report
1899 # Compute actual times and report
1901 wall_time = wall_end-wall_st
1900 wall_time = wall_end-wall_st
1902 cpu_user = end[0]-st[0]
1901 cpu_user = end[0]-st[0]
1903 cpu_sys = end[1]-st[1]
1902 cpu_sys = end[1]-st[1]
1904 cpu_tot = cpu_user+cpu_sys
1903 cpu_tot = cpu_user+cpu_sys
1905 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1904 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1906 (cpu_user,cpu_sys,cpu_tot)
1905 (cpu_user,cpu_sys,cpu_tot)
1907 print "Wall time: %.2f s" % wall_time
1906 print "Wall time: %.2f s" % wall_time
1908 if tc > tc_min:
1907 if tc > tc_min:
1909 print "Compiler : %.2f s" % tc
1908 print "Compiler : %.2f s" % tc
1910 return out
1909 return out
1911
1910
1912 @testdec.skip_doctest
1911 @testdec.skip_doctest
1913 def magic_macro(self,parameter_s = ''):
1912 def magic_macro(self,parameter_s = ''):
1914 """Define a set of input lines as a macro for future re-execution.
1913 """Define a set of input lines as a macro for future re-execution.
1915
1914
1916 Usage:\\
1915 Usage:\\
1917 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1916 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1918
1917
1919 Options:
1918 Options:
1920
1919
1921 -r: use 'raw' input. By default, the 'processed' history is used,
1920 -r: use 'raw' input. By default, the 'processed' history is used,
1922 so that magics are loaded in their transformed version to valid
1921 so that magics are loaded in their transformed version to valid
1923 Python. If this option is given, the raw input as typed as the
1922 Python. If this option is given, the raw input as typed as the
1924 command line is used instead.
1923 command line is used instead.
1925
1924
1926 This will define a global variable called `name` which is a string
1925 This will define a global variable called `name` which is a string
1927 made of joining the slices and lines you specify (n1,n2,... numbers
1926 made of joining the slices and lines you specify (n1,n2,... numbers
1928 above) from your input history into a single string. This variable
1927 above) from your input history into a single string. This variable
1929 acts like an automatic function which re-executes those lines as if
1928 acts like an automatic function which re-executes those lines as if
1930 you had typed them. You just type 'name' at the prompt and the code
1929 you had typed them. You just type 'name' at the prompt and the code
1931 executes.
1930 executes.
1932
1931
1933 The notation for indicating number ranges is: n1-n2 means 'use line
1932 The notation for indicating number ranges is: n1-n2 means 'use line
1934 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1933 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1935 using the lines numbered 5,6 and 7.
1934 using the lines numbered 5,6 and 7.
1936
1935
1937 Note: as a 'hidden' feature, you can also use traditional python slice
1936 Note: as a 'hidden' feature, you can also use traditional python slice
1938 notation, where N:M means numbers N through M-1.
1937 notation, where N:M means numbers N through M-1.
1939
1938
1940 For example, if your history contains (%hist prints it):
1939 For example, if your history contains (%hist prints it):
1941
1940
1942 44: x=1
1941 44: x=1
1943 45: y=3
1942 45: y=3
1944 46: z=x+y
1943 46: z=x+y
1945 47: print x
1944 47: print x
1946 48: a=5
1945 48: a=5
1947 49: print 'x',x,'y',y
1946 49: print 'x',x,'y',y
1948
1947
1949 you can create a macro with lines 44 through 47 (included) and line 49
1948 you can create a macro with lines 44 through 47 (included) and line 49
1950 called my_macro with:
1949 called my_macro with:
1951
1950
1952 In [55]: %macro my_macro 44-47 49
1951 In [55]: %macro my_macro 44-47 49
1953
1952
1954 Now, typing `my_macro` (without quotes) will re-execute all this code
1953 Now, typing `my_macro` (without quotes) will re-execute all this code
1955 in one pass.
1954 in one pass.
1956
1955
1957 You don't need to give the line-numbers in order, and any given line
1956 You don't need to give the line-numbers in order, and any given line
1958 number can appear multiple times. You can assemble macros with any
1957 number can appear multiple times. You can assemble macros with any
1959 lines from your input history in any order.
1958 lines from your input history in any order.
1960
1959
1961 The macro is a simple object which holds its value in an attribute,
1960 The macro is a simple object which holds its value in an attribute,
1962 but IPython's display system checks for macros and executes them as
1961 but IPython's display system checks for macros and executes them as
1963 code instead of printing them when you type their name.
1962 code instead of printing them when you type their name.
1964
1963
1965 You can view a macro's contents by explicitly printing it with:
1964 You can view a macro's contents by explicitly printing it with:
1966
1965
1967 'print macro_name'.
1966 'print macro_name'.
1968
1967
1969 For one-off cases which DON'T contain magic function calls in them you
1968 For one-off cases which DON'T contain magic function calls in them you
1970 can obtain similar results by explicitly executing slices from your
1969 can obtain similar results by explicitly executing slices from your
1971 input history with:
1970 input history with:
1972
1971
1973 In [60]: exec In[44:48]+In[49]"""
1972 In [60]: exec In[44:48]+In[49]"""
1974
1973
1975 opts,args = self.parse_options(parameter_s,'r',mode='list')
1974 opts,args = self.parse_options(parameter_s,'r',mode='list')
1976 if not args:
1975 if not args:
1977 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1976 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1978 macs.sort()
1977 macs.sort()
1979 return macs
1978 return macs
1980 if len(args) == 1:
1979 if len(args) == 1:
1981 raise UsageError(
1980 raise UsageError(
1982 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1981 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1983 name,ranges = args[0], args[1:]
1982 name,ranges = args[0], args[1:]
1984
1983
1985 #print 'rng',ranges # dbg
1984 #print 'rng',ranges # dbg
1986 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1985 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1987 macro = Macro(lines)
1986 macro = Macro(lines)
1988 self.shell.define_macro(name, macro)
1987 self.shell.define_macro(name, macro)
1989 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1988 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1990 print 'Macro contents:'
1989 print 'Macro contents:'
1991 print macro,
1990 print macro,
1992
1991
1993 def magic_save(self,parameter_s = ''):
1992 def magic_save(self,parameter_s = ''):
1994 """Save a set of lines to a given filename.
1993 """Save a set of lines to a given filename.
1995
1994
1996 Usage:\\
1995 Usage:\\
1997 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1996 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1998
1997
1999 Options:
1998 Options:
2000
1999
2001 -r: use 'raw' input. By default, the 'processed' history is used,
2000 -r: use 'raw' input. By default, the 'processed' history is used,
2002 so that magics are loaded in their transformed version to valid
2001 so that magics are loaded in their transformed version to valid
2003 Python. If this option is given, the raw input as typed as the
2002 Python. If this option is given, the raw input as typed as the
2004 command line is used instead.
2003 command line is used instead.
2005
2004
2006 This function uses the same syntax as %macro for line extraction, but
2005 This function uses the same syntax as %macro for line extraction, but
2007 instead of creating a macro it saves the resulting string to the
2006 instead of creating a macro it saves the resulting string to the
2008 filename you specify.
2007 filename you specify.
2009
2008
2010 It adds a '.py' extension to the file if you don't do so yourself, and
2009 It adds a '.py' extension to the file if you don't do so yourself, and
2011 it asks for confirmation before overwriting existing files."""
2010 it asks for confirmation before overwriting existing files."""
2012
2011
2013 opts,args = self.parse_options(parameter_s,'r',mode='list')
2012 opts,args = self.parse_options(parameter_s,'r',mode='list')
2014 fname,ranges = args[0], args[1:]
2013 fname,ranges = args[0], args[1:]
2015 if not fname.endswith('.py'):
2014 if not fname.endswith('.py'):
2016 fname += '.py'
2015 fname += '.py'
2017 if os.path.isfile(fname):
2016 if os.path.isfile(fname):
2018 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2017 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2019 if ans.lower() not in ['y','yes']:
2018 if ans.lower() not in ['y','yes']:
2020 print 'Operation cancelled.'
2019 print 'Operation cancelled.'
2021 return
2020 return
2022 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2021 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2023 f = file(fname,'w')
2022 f = file(fname,'w')
2024 f.write(cmds)
2023 f.write(cmds)
2025 f.close()
2024 f.close()
2026 print 'The following commands were written to file `%s`:' % fname
2025 print 'The following commands were written to file `%s`:' % fname
2027 print cmds
2026 print cmds
2028
2027
2029 def _edit_macro(self,mname,macro):
2028 def _edit_macro(self,mname,macro):
2030 """open an editor with the macro data in a file"""
2029 """open an editor with the macro data in a file"""
2031 filename = self.shell.mktempfile(macro.value)
2030 filename = self.shell.mktempfile(macro.value)
2032 self.shell.hooks.editor(filename)
2031 self.shell.hooks.editor(filename)
2033
2032
2034 # and make a new macro object, to replace the old one
2033 # and make a new macro object, to replace the old one
2035 mfile = open(filename)
2034 mfile = open(filename)
2036 mvalue = mfile.read()
2035 mvalue = mfile.read()
2037 mfile.close()
2036 mfile.close()
2038 self.shell.user_ns[mname] = Macro(mvalue)
2037 self.shell.user_ns[mname] = Macro(mvalue)
2039
2038
2040 def magic_ed(self,parameter_s=''):
2039 def magic_ed(self,parameter_s=''):
2041 """Alias to %edit."""
2040 """Alias to %edit."""
2042 return self.magic_edit(parameter_s)
2041 return self.magic_edit(parameter_s)
2043
2042
2044 @testdec.skip_doctest
2043 @testdec.skip_doctest
2045 def magic_edit(self,parameter_s='',last_call=['','']):
2044 def magic_edit(self,parameter_s='',last_call=['','']):
2046 """Bring up an editor and execute the resulting code.
2045 """Bring up an editor and execute the resulting code.
2047
2046
2048 Usage:
2047 Usage:
2049 %edit [options] [args]
2048 %edit [options] [args]
2050
2049
2051 %edit runs IPython's editor hook. The default version of this hook is
2050 %edit runs IPython's editor hook. The default version of this hook is
2052 set to call the __IPYTHON__.rc.editor command. This is read from your
2051 set to call the __IPYTHON__.rc.editor command. This is read from your
2053 environment variable $EDITOR. If this isn't found, it will default to
2052 environment variable $EDITOR. If this isn't found, it will default to
2054 vi under Linux/Unix and to notepad under Windows. See the end of this
2053 vi under Linux/Unix and to notepad under Windows. See the end of this
2055 docstring for how to change the editor hook.
2054 docstring for how to change the editor hook.
2056
2055
2057 You can also set the value of this editor via the command line option
2056 You can also set the value of this editor via the command line option
2058 '-editor' or in your ipythonrc file. This is useful if you wish to use
2057 '-editor' or in your ipythonrc file. This is useful if you wish to use
2059 specifically for IPython an editor different from your typical default
2058 specifically for IPython an editor different from your typical default
2060 (and for Windows users who typically don't set environment variables).
2059 (and for Windows users who typically don't set environment variables).
2061
2060
2062 This command allows you to conveniently edit multi-line code right in
2061 This command allows you to conveniently edit multi-line code right in
2063 your IPython session.
2062 your IPython session.
2064
2063
2065 If called without arguments, %edit opens up an empty editor with a
2064 If called without arguments, %edit opens up an empty editor with a
2066 temporary file and will execute the contents of this file when you
2065 temporary file and will execute the contents of this file when you
2067 close it (don't forget to save it!).
2066 close it (don't forget to save it!).
2068
2067
2069
2068
2070 Options:
2069 Options:
2071
2070
2072 -n <number>: open the editor at a specified line number. By default,
2071 -n <number>: open the editor at a specified line number. By default,
2073 the IPython editor hook uses the unix syntax 'editor +N filename', but
2072 the IPython editor hook uses the unix syntax 'editor +N filename', but
2074 you can configure this by providing your own modified hook if your
2073 you can configure this by providing your own modified hook if your
2075 favorite editor supports line-number specifications with a different
2074 favorite editor supports line-number specifications with a different
2076 syntax.
2075 syntax.
2077
2076
2078 -p: this will call the editor with the same data as the previous time
2077 -p: this will call the editor with the same data as the previous time
2079 it was used, regardless of how long ago (in your current session) it
2078 it was used, regardless of how long ago (in your current session) it
2080 was.
2079 was.
2081
2080
2082 -r: use 'raw' input. This option only applies to input taken from the
2081 -r: use 'raw' input. This option only applies to input taken from the
2083 user's history. By default, the 'processed' history is used, so that
2082 user's history. By default, the 'processed' history is used, so that
2084 magics are loaded in their transformed version to valid Python. If
2083 magics are loaded in their transformed version to valid Python. If
2085 this option is given, the raw input as typed as the command line is
2084 this option is given, the raw input as typed as the command line is
2086 used instead. When you exit the editor, it will be executed by
2085 used instead. When you exit the editor, it will be executed by
2087 IPython's own processor.
2086 IPython's own processor.
2088
2087
2089 -x: do not execute the edited code immediately upon exit. This is
2088 -x: do not execute the edited code immediately upon exit. This is
2090 mainly useful if you are editing programs which need to be called with
2089 mainly useful if you are editing programs which need to be called with
2091 command line arguments, which you can then do using %run.
2090 command line arguments, which you can then do using %run.
2092
2091
2093
2092
2094 Arguments:
2093 Arguments:
2095
2094
2096 If arguments are given, the following possibilites exist:
2095 If arguments are given, the following possibilites exist:
2097
2096
2098 - The arguments are numbers or pairs of colon-separated numbers (like
2097 - The arguments are numbers or pairs of colon-separated numbers (like
2099 1 4:8 9). These are interpreted as lines of previous input to be
2098 1 4:8 9). These are interpreted as lines of previous input to be
2100 loaded into the editor. The syntax is the same of the %macro command.
2099 loaded into the editor. The syntax is the same of the %macro command.
2101
2100
2102 - If the argument doesn't start with a number, it is evaluated as a
2101 - If the argument doesn't start with a number, it is evaluated as a
2103 variable and its contents loaded into the editor. You can thus edit
2102 variable and its contents loaded into the editor. You can thus edit
2104 any string which contains python code (including the result of
2103 any string which contains python code (including the result of
2105 previous edits).
2104 previous edits).
2106
2105
2107 - If the argument is the name of an object (other than a string),
2106 - If the argument is the name of an object (other than a string),
2108 IPython will try to locate the file where it was defined and open the
2107 IPython will try to locate the file where it was defined and open the
2109 editor at the point where it is defined. You can use `%edit function`
2108 editor at the point where it is defined. You can use `%edit function`
2110 to load an editor exactly at the point where 'function' is defined,
2109 to load an editor exactly at the point where 'function' is defined,
2111 edit it and have the file be executed automatically.
2110 edit it and have the file be executed automatically.
2112
2111
2113 If the object is a macro (see %macro for details), this opens up your
2112 If the object is a macro (see %macro for details), this opens up your
2114 specified editor with a temporary file containing the macro's data.
2113 specified editor with a temporary file containing the macro's data.
2115 Upon exit, the macro is reloaded with the contents of the file.
2114 Upon exit, the macro is reloaded with the contents of the file.
2116
2115
2117 Note: opening at an exact line is only supported under Unix, and some
2116 Note: opening at an exact line is only supported under Unix, and some
2118 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2117 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2119 '+NUMBER' parameter necessary for this feature. Good editors like
2118 '+NUMBER' parameter necessary for this feature. Good editors like
2120 (X)Emacs, vi, jed, pico and joe all do.
2119 (X)Emacs, vi, jed, pico and joe all do.
2121
2120
2122 - If the argument is not found as a variable, IPython will look for a
2121 - If the argument is not found as a variable, IPython will look for a
2123 file with that name (adding .py if necessary) and load it into the
2122 file with that name (adding .py if necessary) and load it into the
2124 editor. It will execute its contents with execfile() when you exit,
2123 editor. It will execute its contents with execfile() when you exit,
2125 loading any code in the file into your interactive namespace.
2124 loading any code in the file into your interactive namespace.
2126
2125
2127 After executing your code, %edit will return as output the code you
2126 After executing your code, %edit will return as output the code you
2128 typed in the editor (except when it was an existing file). This way
2127 typed in the editor (except when it was an existing file). This way
2129 you can reload the code in further invocations of %edit as a variable,
2128 you can reload the code in further invocations of %edit as a variable,
2130 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2129 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2131 the output.
2130 the output.
2132
2131
2133 Note that %edit is also available through the alias %ed.
2132 Note that %edit is also available through the alias %ed.
2134
2133
2135 This is an example of creating a simple function inside the editor and
2134 This is an example of creating a simple function inside the editor and
2136 then modifying it. First, start up the editor:
2135 then modifying it. First, start up the editor:
2137
2136
2138 In [1]: ed
2137 In [1]: ed
2139 Editing... done. Executing edited code...
2138 Editing... done. Executing edited code...
2140 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2139 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2141
2140
2142 We can then call the function foo():
2141 We can then call the function foo():
2143
2142
2144 In [2]: foo()
2143 In [2]: foo()
2145 foo() was defined in an editing session
2144 foo() was defined in an editing session
2146
2145
2147 Now we edit foo. IPython automatically loads the editor with the
2146 Now we edit foo. IPython automatically loads the editor with the
2148 (temporary) file where foo() was previously defined:
2147 (temporary) file where foo() was previously defined:
2149
2148
2150 In [3]: ed foo
2149 In [3]: ed foo
2151 Editing... done. Executing edited code...
2150 Editing... done. Executing edited code...
2152
2151
2153 And if we call foo() again we get the modified version:
2152 And if we call foo() again we get the modified version:
2154
2153
2155 In [4]: foo()
2154 In [4]: foo()
2156 foo() has now been changed!
2155 foo() has now been changed!
2157
2156
2158 Here is an example of how to edit a code snippet successive
2157 Here is an example of how to edit a code snippet successive
2159 times. First we call the editor:
2158 times. First we call the editor:
2160
2159
2161 In [5]: ed
2160 In [5]: ed
2162 Editing... done. Executing edited code...
2161 Editing... done. Executing edited code...
2163 hello
2162 hello
2164 Out[5]: "print 'hello'n"
2163 Out[5]: "print 'hello'n"
2165
2164
2166 Now we call it again with the previous output (stored in _):
2165 Now we call it again with the previous output (stored in _):
2167
2166
2168 In [6]: ed _
2167 In [6]: ed _
2169 Editing... done. Executing edited code...
2168 Editing... done. Executing edited code...
2170 hello world
2169 hello world
2171 Out[6]: "print 'hello world'n"
2170 Out[6]: "print 'hello world'n"
2172
2171
2173 Now we call it with the output #8 (stored in _8, also as Out[8]):
2172 Now we call it with the output #8 (stored in _8, also as Out[8]):
2174
2173
2175 In [7]: ed _8
2174 In [7]: ed _8
2176 Editing... done. Executing edited code...
2175 Editing... done. Executing edited code...
2177 hello again
2176 hello again
2178 Out[7]: "print 'hello again'n"
2177 Out[7]: "print 'hello again'n"
2179
2178
2180
2179
2181 Changing the default editor hook:
2180 Changing the default editor hook:
2182
2181
2183 If you wish to write your own editor hook, you can put it in a
2182 If you wish to write your own editor hook, you can put it in a
2184 configuration file which you load at startup time. The default hook
2183 configuration file which you load at startup time. The default hook
2185 is defined in the IPython.core.hooks module, and you can use that as a
2184 is defined in the IPython.core.hooks module, and you can use that as a
2186 starting example for further modifications. That file also has
2185 starting example for further modifications. That file also has
2187 general instructions on how to set a new hook for use once you've
2186 general instructions on how to set a new hook for use once you've
2188 defined it."""
2187 defined it."""
2189
2188
2190 # FIXME: This function has become a convoluted mess. It needs a
2189 # FIXME: This function has become a convoluted mess. It needs a
2191 # ground-up rewrite with clean, simple logic.
2190 # ground-up rewrite with clean, simple logic.
2192
2191
2193 def make_filename(arg):
2192 def make_filename(arg):
2194 "Make a filename from the given args"
2193 "Make a filename from the given args"
2195 try:
2194 try:
2196 filename = get_py_filename(arg)
2195 filename = get_py_filename(arg)
2197 except IOError:
2196 except IOError:
2198 if args.endswith('.py'):
2197 if args.endswith('.py'):
2199 filename = arg
2198 filename = arg
2200 else:
2199 else:
2201 filename = None
2200 filename = None
2202 return filename
2201 return filename
2203
2202
2204 # custom exceptions
2203 # custom exceptions
2205 class DataIsObject(Exception): pass
2204 class DataIsObject(Exception): pass
2206
2205
2207 opts,args = self.parse_options(parameter_s,'prxn:')
2206 opts,args = self.parse_options(parameter_s,'prxn:')
2208 # Set a few locals from the options for convenience:
2207 # Set a few locals from the options for convenience:
2209 opts_p = opts.has_key('p')
2208 opts_p = opts.has_key('p')
2210 opts_r = opts.has_key('r')
2209 opts_r = opts.has_key('r')
2211
2210
2212 # Default line number value
2211 # Default line number value
2213 lineno = opts.get('n',None)
2212 lineno = opts.get('n',None)
2214
2213
2215 if opts_p:
2214 if opts_p:
2216 args = '_%s' % last_call[0]
2215 args = '_%s' % last_call[0]
2217 if not self.shell.user_ns.has_key(args):
2216 if not self.shell.user_ns.has_key(args):
2218 args = last_call[1]
2217 args = last_call[1]
2219
2218
2220 # use last_call to remember the state of the previous call, but don't
2219 # use last_call to remember the state of the previous call, but don't
2221 # let it be clobbered by successive '-p' calls.
2220 # let it be clobbered by successive '-p' calls.
2222 try:
2221 try:
2223 last_call[0] = self.shell.displayhook.prompt_count
2222 last_call[0] = self.shell.displayhook.prompt_count
2224 if not opts_p:
2223 if not opts_p:
2225 last_call[1] = parameter_s
2224 last_call[1] = parameter_s
2226 except:
2225 except:
2227 pass
2226 pass
2228
2227
2229 # by default this is done with temp files, except when the given
2228 # by default this is done with temp files, except when the given
2230 # arg is a filename
2229 # arg is a filename
2231 use_temp = 1
2230 use_temp = 1
2232
2231
2233 if re.match(r'\d',args):
2232 if re.match(r'\d',args):
2234 # Mode where user specifies ranges of lines, like in %macro.
2233 # Mode where user specifies ranges of lines, like in %macro.
2235 # This means that you can't edit files whose names begin with
2234 # This means that you can't edit files whose names begin with
2236 # numbers this way. Tough.
2235 # numbers this way. Tough.
2237 ranges = args.split()
2236 ranges = args.split()
2238 data = ''.join(self.extract_input_slices(ranges,opts_r))
2237 data = ''.join(self.extract_input_slices(ranges,opts_r))
2239 elif args.endswith('.py'):
2238 elif args.endswith('.py'):
2240 filename = make_filename(args)
2239 filename = make_filename(args)
2241 data = ''
2240 data = ''
2242 use_temp = 0
2241 use_temp = 0
2243 elif args:
2242 elif args:
2244 try:
2243 try:
2245 # Load the parameter given as a variable. If not a string,
2244 # Load the parameter given as a variable. If not a string,
2246 # process it as an object instead (below)
2245 # process it as an object instead (below)
2247
2246
2248 #print '*** args',args,'type',type(args) # dbg
2247 #print '*** args',args,'type',type(args) # dbg
2249 data = eval(args,self.shell.user_ns)
2248 data = eval(args,self.shell.user_ns)
2250 if not type(data) in StringTypes:
2249 if not type(data) in StringTypes:
2251 raise DataIsObject
2250 raise DataIsObject
2252
2251
2253 except (NameError,SyntaxError):
2252 except (NameError,SyntaxError):
2254 # given argument is not a variable, try as a filename
2253 # given argument is not a variable, try as a filename
2255 filename = make_filename(args)
2254 filename = make_filename(args)
2256 if filename is None:
2255 if filename is None:
2257 warn("Argument given (%s) can't be found as a variable "
2256 warn("Argument given (%s) can't be found as a variable "
2258 "or as a filename." % args)
2257 "or as a filename." % args)
2259 return
2258 return
2260
2259
2261 data = ''
2260 data = ''
2262 use_temp = 0
2261 use_temp = 0
2263 except DataIsObject:
2262 except DataIsObject:
2264
2263
2265 # macros have a special edit function
2264 # macros have a special edit function
2266 if isinstance(data,Macro):
2265 if isinstance(data,Macro):
2267 self._edit_macro(args,data)
2266 self._edit_macro(args,data)
2268 return
2267 return
2269
2268
2270 # For objects, try to edit the file where they are defined
2269 # For objects, try to edit the file where they are defined
2271 try:
2270 try:
2272 filename = inspect.getabsfile(data)
2271 filename = inspect.getabsfile(data)
2273 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2272 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2274 # class created by %edit? Try to find source
2273 # class created by %edit? Try to find source
2275 # by looking for method definitions instead, the
2274 # by looking for method definitions instead, the
2276 # __module__ in those classes is FakeModule.
2275 # __module__ in those classes is FakeModule.
2277 attrs = [getattr(data, aname) for aname in dir(data)]
2276 attrs = [getattr(data, aname) for aname in dir(data)]
2278 for attr in attrs:
2277 for attr in attrs:
2279 if not inspect.ismethod(attr):
2278 if not inspect.ismethod(attr):
2280 continue
2279 continue
2281 filename = inspect.getabsfile(attr)
2280 filename = inspect.getabsfile(attr)
2282 if filename and 'fakemodule' not in filename.lower():
2281 if filename and 'fakemodule' not in filename.lower():
2283 # change the attribute to be the edit target instead
2282 # change the attribute to be the edit target instead
2284 data = attr
2283 data = attr
2285 break
2284 break
2286
2285
2287 datafile = 1
2286 datafile = 1
2288 except TypeError:
2287 except TypeError:
2289 filename = make_filename(args)
2288 filename = make_filename(args)
2290 datafile = 1
2289 datafile = 1
2291 warn('Could not find file where `%s` is defined.\n'
2290 warn('Could not find file where `%s` is defined.\n'
2292 'Opening a file named `%s`' % (args,filename))
2291 'Opening a file named `%s`' % (args,filename))
2293 # Now, make sure we can actually read the source (if it was in
2292 # Now, make sure we can actually read the source (if it was in
2294 # a temp file it's gone by now).
2293 # a temp file it's gone by now).
2295 if datafile:
2294 if datafile:
2296 try:
2295 try:
2297 if lineno is None:
2296 if lineno is None:
2298 lineno = inspect.getsourcelines(data)[1]
2297 lineno = inspect.getsourcelines(data)[1]
2299 except IOError:
2298 except IOError:
2300 filename = make_filename(args)
2299 filename = make_filename(args)
2301 if filename is None:
2300 if filename is None:
2302 warn('The file `%s` where `%s` was defined cannot '
2301 warn('The file `%s` where `%s` was defined cannot '
2303 'be read.' % (filename,data))
2302 'be read.' % (filename,data))
2304 return
2303 return
2305 use_temp = 0
2304 use_temp = 0
2306 else:
2305 else:
2307 data = ''
2306 data = ''
2308
2307
2309 if use_temp:
2308 if use_temp:
2310 filename = self.shell.mktempfile(data)
2309 filename = self.shell.mktempfile(data)
2311 print 'IPython will make a temporary file named:',filename
2310 print 'IPython will make a temporary file named:',filename
2312
2311
2313 # do actual editing here
2312 # do actual editing here
2314 print 'Editing...',
2313 print 'Editing...',
2315 sys.stdout.flush()
2314 sys.stdout.flush()
2316 try:
2315 try:
2317 # Quote filenames that may have spaces in them
2316 # Quote filenames that may have spaces in them
2318 if ' ' in filename:
2317 if ' ' in filename:
2319 filename = "%s" % filename
2318 filename = "%s" % filename
2320 self.shell.hooks.editor(filename,lineno)
2319 self.shell.hooks.editor(filename,lineno)
2321 except TryNext:
2320 except TryNext:
2322 warn('Could not open editor')
2321 warn('Could not open editor')
2323 return
2322 return
2324
2323
2325 # XXX TODO: should this be generalized for all string vars?
2324 # XXX TODO: should this be generalized for all string vars?
2326 # For now, this is special-cased to blocks created by cpaste
2325 # For now, this is special-cased to blocks created by cpaste
2327 if args.strip() == 'pasted_block':
2326 if args.strip() == 'pasted_block':
2328 self.shell.user_ns['pasted_block'] = file_read(filename)
2327 self.shell.user_ns['pasted_block'] = file_read(filename)
2329
2328
2330 if opts.has_key('x'): # -x prevents actual execution
2329 if opts.has_key('x'): # -x prevents actual execution
2331 print
2330 print
2332 else:
2331 else:
2333 print 'done. Executing edited code...'
2332 print 'done. Executing edited code...'
2334 if opts_r:
2333 if opts_r:
2335 self.shell.runlines(file_read(filename))
2334 self.shell.runlines(file_read(filename))
2336 else:
2335 else:
2337 self.shell.safe_execfile(filename,self.shell.user_ns,
2336 self.shell.safe_execfile(filename,self.shell.user_ns,
2338 self.shell.user_ns)
2337 self.shell.user_ns)
2339
2338
2340
2339
2341 if use_temp:
2340 if use_temp:
2342 try:
2341 try:
2343 return open(filename).read()
2342 return open(filename).read()
2344 except IOError,msg:
2343 except IOError,msg:
2345 if msg.filename == filename:
2344 if msg.filename == filename:
2346 warn('File not found. Did you forget to save?')
2345 warn('File not found. Did you forget to save?')
2347 return
2346 return
2348 else:
2347 else:
2349 self.shell.showtraceback()
2348 self.shell.showtraceback()
2350
2349
2351 def magic_xmode(self,parameter_s = ''):
2350 def magic_xmode(self,parameter_s = ''):
2352 """Switch modes for the exception handlers.
2351 """Switch modes for the exception handlers.
2353
2352
2354 Valid modes: Plain, Context and Verbose.
2353 Valid modes: Plain, Context and Verbose.
2355
2354
2356 If called without arguments, acts as a toggle."""
2355 If called without arguments, acts as a toggle."""
2357
2356
2358 def xmode_switch_err(name):
2357 def xmode_switch_err(name):
2359 warn('Error changing %s exception modes.\n%s' %
2358 warn('Error changing %s exception modes.\n%s' %
2360 (name,sys.exc_info()[1]))
2359 (name,sys.exc_info()[1]))
2361
2360
2362 shell = self.shell
2361 shell = self.shell
2363 new_mode = parameter_s.strip().capitalize()
2362 new_mode = parameter_s.strip().capitalize()
2364 try:
2363 try:
2365 shell.InteractiveTB.set_mode(mode=new_mode)
2364 shell.InteractiveTB.set_mode(mode=new_mode)
2366 print 'Exception reporting mode:',shell.InteractiveTB.mode
2365 print 'Exception reporting mode:',shell.InteractiveTB.mode
2367 except:
2366 except:
2368 xmode_switch_err('user')
2367 xmode_switch_err('user')
2369
2368
2370 def magic_colors(self,parameter_s = ''):
2369 def magic_colors(self,parameter_s = ''):
2371 """Switch color scheme for prompts, info system and exception handlers.
2370 """Switch color scheme for prompts, info system and exception handlers.
2372
2371
2373 Currently implemented schemes: NoColor, Linux, LightBG.
2372 Currently implemented schemes: NoColor, Linux, LightBG.
2374
2373
2375 Color scheme names are not case-sensitive."""
2374 Color scheme names are not case-sensitive."""
2376
2375
2377 def color_switch_err(name):
2376 def color_switch_err(name):
2378 warn('Error changing %s color schemes.\n%s' %
2377 warn('Error changing %s color schemes.\n%s' %
2379 (name,sys.exc_info()[1]))
2378 (name,sys.exc_info()[1]))
2380
2379
2381
2380
2382 new_scheme = parameter_s.strip()
2381 new_scheme = parameter_s.strip()
2383 if not new_scheme:
2382 if not new_scheme:
2384 raise UsageError(
2383 raise UsageError(
2385 "%colors: you must specify a color scheme. See '%colors?'")
2384 "%colors: you must specify a color scheme. See '%colors?'")
2386 return
2385 return
2387 # local shortcut
2386 # local shortcut
2388 shell = self.shell
2387 shell = self.shell
2389
2388
2390 import IPython.utils.rlineimpl as readline
2389 import IPython.utils.rlineimpl as readline
2391
2390
2392 if not readline.have_readline and sys.platform == "win32":
2391 if not readline.have_readline and sys.platform == "win32":
2393 msg = """\
2392 msg = """\
2394 Proper color support under MS Windows requires the pyreadline library.
2393 Proper color support under MS Windows requires the pyreadline library.
2395 You can find it at:
2394 You can find it at:
2396 http://ipython.scipy.org/moin/PyReadline/Intro
2395 http://ipython.scipy.org/moin/PyReadline/Intro
2397 Gary's readline needs the ctypes module, from:
2396 Gary's readline needs the ctypes module, from:
2398 http://starship.python.net/crew/theller/ctypes
2397 http://starship.python.net/crew/theller/ctypes
2399 (Note that ctypes is already part of Python versions 2.5 and newer).
2398 (Note that ctypes is already part of Python versions 2.5 and newer).
2400
2399
2401 Defaulting color scheme to 'NoColor'"""
2400 Defaulting color scheme to 'NoColor'"""
2402 new_scheme = 'NoColor'
2401 new_scheme = 'NoColor'
2403 warn(msg)
2402 warn(msg)
2404
2403
2405 # readline option is 0
2404 # readline option is 0
2406 if not shell.has_readline:
2405 if not shell.has_readline:
2407 new_scheme = 'NoColor'
2406 new_scheme = 'NoColor'
2408
2407
2409 # Set prompt colors
2408 # Set prompt colors
2410 try:
2409 try:
2411 shell.displayhook.set_colors(new_scheme)
2410 shell.displayhook.set_colors(new_scheme)
2412 except:
2411 except:
2413 color_switch_err('prompt')
2412 color_switch_err('prompt')
2414 else:
2413 else:
2415 shell.colors = \
2414 shell.colors = \
2416 shell.displayhook.color_table.active_scheme_name
2415 shell.displayhook.color_table.active_scheme_name
2417 # Set exception colors
2416 # Set exception colors
2418 try:
2417 try:
2419 shell.InteractiveTB.set_colors(scheme = new_scheme)
2418 shell.InteractiveTB.set_colors(scheme = new_scheme)
2420 shell.SyntaxTB.set_colors(scheme = new_scheme)
2419 shell.SyntaxTB.set_colors(scheme = new_scheme)
2421 except:
2420 except:
2422 color_switch_err('exception')
2421 color_switch_err('exception')
2423
2422
2424 # Set info (for 'object?') colors
2423 # Set info (for 'object?') colors
2425 if shell.color_info:
2424 if shell.color_info:
2426 try:
2425 try:
2427 shell.inspector.set_active_scheme(new_scheme)
2426 shell.inspector.set_active_scheme(new_scheme)
2428 except:
2427 except:
2429 color_switch_err('object inspector')
2428 color_switch_err('object inspector')
2430 else:
2429 else:
2431 shell.inspector.set_active_scheme('NoColor')
2430 shell.inspector.set_active_scheme('NoColor')
2432
2431
2433 def magic_Pprint(self, parameter_s=''):
2432 def magic_Pprint(self, parameter_s=''):
2434 """Toggle pretty printing on/off."""
2433 """Toggle pretty printing on/off."""
2435
2434
2436 self.shell.pprint = 1 - self.shell.pprint
2435 self.shell.pprint = 1 - self.shell.pprint
2437 print 'Pretty printing has been turned', \
2436 print 'Pretty printing has been turned', \
2438 ['OFF','ON'][self.shell.pprint]
2437 ['OFF','ON'][self.shell.pprint]
2439
2438
2440 def magic_Exit(self, parameter_s=''):
2439 def magic_Exit(self, parameter_s=''):
2441 """Exit IPython."""
2440 """Exit IPython."""
2442
2441
2443 self.shell.ask_exit()
2442 self.shell.ask_exit()
2444
2443
2445 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2444 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2446 magic_exit = magic_quit = magic_Quit = magic_Exit
2445 magic_exit = magic_quit = magic_Quit = magic_Exit
2447
2446
2448 #......................................................................
2447 #......................................................................
2449 # Functions to implement unix shell-type things
2448 # Functions to implement unix shell-type things
2450
2449
2451 @testdec.skip_doctest
2450 @testdec.skip_doctest
2452 def magic_alias(self, parameter_s = ''):
2451 def magic_alias(self, parameter_s = ''):
2453 """Define an alias for a system command.
2452 """Define an alias for a system command.
2454
2453
2455 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2454 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2456
2455
2457 Then, typing 'alias_name params' will execute the system command 'cmd
2456 Then, typing 'alias_name params' will execute the system command 'cmd
2458 params' (from your underlying operating system).
2457 params' (from your underlying operating system).
2459
2458
2460 Aliases have lower precedence than magic functions and Python normal
2459 Aliases have lower precedence than magic functions and Python normal
2461 variables, so if 'foo' is both a Python variable and an alias, the
2460 variables, so if 'foo' is both a Python variable and an alias, the
2462 alias can not be executed until 'del foo' removes the Python variable.
2461 alias can not be executed until 'del foo' removes the Python variable.
2463
2462
2464 You can use the %l specifier in an alias definition to represent the
2463 You can use the %l specifier in an alias definition to represent the
2465 whole line when the alias is called. For example:
2464 whole line when the alias is called. For example:
2466
2465
2467 In [2]: alias bracket echo "Input in brackets: <%l>"
2466 In [2]: alias bracket echo "Input in brackets: <%l>"
2468 In [3]: bracket hello world
2467 In [3]: bracket hello world
2469 Input in brackets: <hello world>
2468 Input in brackets: <hello world>
2470
2469
2471 You can also define aliases with parameters using %s specifiers (one
2470 You can also define aliases with parameters using %s specifiers (one
2472 per parameter):
2471 per parameter):
2473
2472
2474 In [1]: alias parts echo first %s second %s
2473 In [1]: alias parts echo first %s second %s
2475 In [2]: %parts A B
2474 In [2]: %parts A B
2476 first A second B
2475 first A second B
2477 In [3]: %parts A
2476 In [3]: %parts A
2478 Incorrect number of arguments: 2 expected.
2477 Incorrect number of arguments: 2 expected.
2479 parts is an alias to: 'echo first %s second %s'
2478 parts is an alias to: 'echo first %s second %s'
2480
2479
2481 Note that %l and %s are mutually exclusive. You can only use one or
2480 Note that %l and %s are mutually exclusive. You can only use one or
2482 the other in your aliases.
2481 the other in your aliases.
2483
2482
2484 Aliases expand Python variables just like system calls using ! or !!
2483 Aliases expand Python variables just like system calls using ! or !!
2485 do: all expressions prefixed with '$' get expanded. For details of
2484 do: all expressions prefixed with '$' get expanded. For details of
2486 the semantic rules, see PEP-215:
2485 the semantic rules, see PEP-215:
2487 http://www.python.org/peps/pep-0215.html. This is the library used by
2486 http://www.python.org/peps/pep-0215.html. This is the library used by
2488 IPython for variable expansion. If you want to access a true shell
2487 IPython for variable expansion. If you want to access a true shell
2489 variable, an extra $ is necessary to prevent its expansion by IPython:
2488 variable, an extra $ is necessary to prevent its expansion by IPython:
2490
2489
2491 In [6]: alias show echo
2490 In [6]: alias show echo
2492 In [7]: PATH='A Python string'
2491 In [7]: PATH='A Python string'
2493 In [8]: show $PATH
2492 In [8]: show $PATH
2494 A Python string
2493 A Python string
2495 In [9]: show $$PATH
2494 In [9]: show $$PATH
2496 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2495 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2497
2496
2498 You can use the alias facility to acess all of $PATH. See the %rehash
2497 You can use the alias facility to acess all of $PATH. See the %rehash
2499 and %rehashx functions, which automatically create aliases for the
2498 and %rehashx functions, which automatically create aliases for the
2500 contents of your $PATH.
2499 contents of your $PATH.
2501
2500
2502 If called with no parameters, %alias prints the current alias table."""
2501 If called with no parameters, %alias prints the current alias table."""
2503
2502
2504 par = parameter_s.strip()
2503 par = parameter_s.strip()
2505 if not par:
2504 if not par:
2506 stored = self.db.get('stored_aliases', {} )
2505 stored = self.db.get('stored_aliases', {} )
2507 aliases = sorted(self.shell.alias_manager.aliases)
2506 aliases = sorted(self.shell.alias_manager.aliases)
2508 # for k, v in stored:
2507 # for k, v in stored:
2509 # atab.append(k, v[0])
2508 # atab.append(k, v[0])
2510
2509
2511 print "Total number of aliases:", len(aliases)
2510 print "Total number of aliases:", len(aliases)
2511 sys.stdout.flush()
2512 return aliases
2512 return aliases
2513
2513
2514 # Now try to define a new one
2514 # Now try to define a new one
2515 try:
2515 try:
2516 alias,cmd = par.split(None, 1)
2516 alias,cmd = par.split(None, 1)
2517 except:
2517 except:
2518 print oinspect.getdoc(self.magic_alias)
2518 print oinspect.getdoc(self.magic_alias)
2519 else:
2519 else:
2520 self.shell.alias_manager.soft_define_alias(alias, cmd)
2520 self.shell.alias_manager.soft_define_alias(alias, cmd)
2521 # end magic_alias
2521 # end magic_alias
2522
2522
2523 def magic_unalias(self, parameter_s = ''):
2523 def magic_unalias(self, parameter_s = ''):
2524 """Remove an alias"""
2524 """Remove an alias"""
2525
2525
2526 aname = parameter_s.strip()
2526 aname = parameter_s.strip()
2527 self.shell.alias_manager.undefine_alias(aname)
2527 self.shell.alias_manager.undefine_alias(aname)
2528 stored = self.db.get('stored_aliases', {} )
2528 stored = self.db.get('stored_aliases', {} )
2529 if aname in stored:
2529 if aname in stored:
2530 print "Removing %stored alias",aname
2530 print "Removing %stored alias",aname
2531 del stored[aname]
2531 del stored[aname]
2532 self.db['stored_aliases'] = stored
2532 self.db['stored_aliases'] = stored
2533
2533
2534 def magic_rehashx(self, parameter_s = ''):
2534 def magic_rehashx(self, parameter_s = ''):
2535 """Update the alias table with all executable files in $PATH.
2535 """Update the alias table with all executable files in $PATH.
2536
2536
2537 This version explicitly checks that every entry in $PATH is a file
2537 This version explicitly checks that every entry in $PATH is a file
2538 with execute access (os.X_OK), so it is much slower than %rehash.
2538 with execute access (os.X_OK), so it is much slower than %rehash.
2539
2539
2540 Under Windows, it checks executability as a match agains a
2540 Under Windows, it checks executability as a match agains a
2541 '|'-separated string of extensions, stored in the IPython config
2541 '|'-separated string of extensions, stored in the IPython config
2542 variable win_exec_ext. This defaults to 'exe|com|bat'.
2542 variable win_exec_ext. This defaults to 'exe|com|bat'.
2543
2543
2544 This function also resets the root module cache of module completer,
2544 This function also resets the root module cache of module completer,
2545 used on slow filesystems.
2545 used on slow filesystems.
2546 """
2546 """
2547 from IPython.core.alias import InvalidAliasError
2547 from IPython.core.alias import InvalidAliasError
2548
2548
2549 # for the benefit of module completer in ipy_completers.py
2549 # for the benefit of module completer in ipy_completers.py
2550 del self.db['rootmodules']
2550 del self.db['rootmodules']
2551
2551
2552 path = [os.path.abspath(os.path.expanduser(p)) for p in
2552 path = [os.path.abspath(os.path.expanduser(p)) for p in
2553 os.environ.get('PATH','').split(os.pathsep)]
2553 os.environ.get('PATH','').split(os.pathsep)]
2554 path = filter(os.path.isdir,path)
2554 path = filter(os.path.isdir,path)
2555
2555
2556 syscmdlist = []
2556 syscmdlist = []
2557 # Now define isexec in a cross platform manner.
2557 # Now define isexec in a cross platform manner.
2558 if os.name == 'posix':
2558 if os.name == 'posix':
2559 isexec = lambda fname:os.path.isfile(fname) and \
2559 isexec = lambda fname:os.path.isfile(fname) and \
2560 os.access(fname,os.X_OK)
2560 os.access(fname,os.X_OK)
2561 else:
2561 else:
2562 try:
2562 try:
2563 winext = os.environ['pathext'].replace(';','|').replace('.','')
2563 winext = os.environ['pathext'].replace(';','|').replace('.','')
2564 except KeyError:
2564 except KeyError:
2565 winext = 'exe|com|bat|py'
2565 winext = 'exe|com|bat|py'
2566 if 'py' not in winext:
2566 if 'py' not in winext:
2567 winext += '|py'
2567 winext += '|py'
2568 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2568 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2569 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2569 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2570 savedir = os.getcwd()
2570 savedir = os.getcwd()
2571
2571
2572 # Now walk the paths looking for executables to alias.
2572 # Now walk the paths looking for executables to alias.
2573 try:
2573 try:
2574 # write the whole loop for posix/Windows so we don't have an if in
2574 # write the whole loop for posix/Windows so we don't have an if in
2575 # the innermost part
2575 # the innermost part
2576 if os.name == 'posix':
2576 if os.name == 'posix':
2577 for pdir in path:
2577 for pdir in path:
2578 os.chdir(pdir)
2578 os.chdir(pdir)
2579 for ff in os.listdir(pdir):
2579 for ff in os.listdir(pdir):
2580 if isexec(ff):
2580 if isexec(ff):
2581 try:
2581 try:
2582 # Removes dots from the name since ipython
2582 # Removes dots from the name since ipython
2583 # will assume names with dots to be python.
2583 # will assume names with dots to be python.
2584 self.shell.alias_manager.define_alias(
2584 self.shell.alias_manager.define_alias(
2585 ff.replace('.',''), ff)
2585 ff.replace('.',''), ff)
2586 except InvalidAliasError:
2586 except InvalidAliasError:
2587 pass
2587 pass
2588 else:
2588 else:
2589 syscmdlist.append(ff)
2589 syscmdlist.append(ff)
2590 else:
2590 else:
2591 no_alias = self.shell.alias_manager.no_alias
2591 no_alias = self.shell.alias_manager.no_alias
2592 for pdir in path:
2592 for pdir in path:
2593 os.chdir(pdir)
2593 os.chdir(pdir)
2594 for ff in os.listdir(pdir):
2594 for ff in os.listdir(pdir):
2595 base, ext = os.path.splitext(ff)
2595 base, ext = os.path.splitext(ff)
2596 if isexec(ff) and base.lower() not in no_alias:
2596 if isexec(ff) and base.lower() not in no_alias:
2597 if ext.lower() == '.exe':
2597 if ext.lower() == '.exe':
2598 ff = base
2598 ff = base
2599 try:
2599 try:
2600 # Removes dots from the name since ipython
2600 # Removes dots from the name since ipython
2601 # will assume names with dots to be python.
2601 # will assume names with dots to be python.
2602 self.shell.alias_manager.define_alias(
2602 self.shell.alias_manager.define_alias(
2603 base.lower().replace('.',''), ff)
2603 base.lower().replace('.',''), ff)
2604 except InvalidAliasError:
2604 except InvalidAliasError:
2605 pass
2605 pass
2606 syscmdlist.append(ff)
2606 syscmdlist.append(ff)
2607 db = self.db
2607 db = self.db
2608 db['syscmdlist'] = syscmdlist
2608 db['syscmdlist'] = syscmdlist
2609 finally:
2609 finally:
2610 os.chdir(savedir)
2610 os.chdir(savedir)
2611
2611
2612 def magic_pwd(self, parameter_s = ''):
2612 def magic_pwd(self, parameter_s = ''):
2613 """Return the current working directory path."""
2613 """Return the current working directory path."""
2614 return os.getcwd()
2614 return os.getcwd()
2615
2615
2616 def magic_cd(self, parameter_s=''):
2616 def magic_cd(self, parameter_s=''):
2617 """Change the current working directory.
2617 """Change the current working directory.
2618
2618
2619 This command automatically maintains an internal list of directories
2619 This command automatically maintains an internal list of directories
2620 you visit during your IPython session, in the variable _dh. The
2620 you visit during your IPython session, in the variable _dh. The
2621 command %dhist shows this history nicely formatted. You can also
2621 command %dhist shows this history nicely formatted. You can also
2622 do 'cd -<tab>' to see directory history conveniently.
2622 do 'cd -<tab>' to see directory history conveniently.
2623
2623
2624 Usage:
2624 Usage:
2625
2625
2626 cd 'dir': changes to directory 'dir'.
2626 cd 'dir': changes to directory 'dir'.
2627
2627
2628 cd -: changes to the last visited directory.
2628 cd -: changes to the last visited directory.
2629
2629
2630 cd -<n>: changes to the n-th directory in the directory history.
2630 cd -<n>: changes to the n-th directory in the directory history.
2631
2631
2632 cd --foo: change to directory that matches 'foo' in history
2632 cd --foo: change to directory that matches 'foo' in history
2633
2633
2634 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2634 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2635 (note: cd <bookmark_name> is enough if there is no
2635 (note: cd <bookmark_name> is enough if there is no
2636 directory <bookmark_name>, but a bookmark with the name exists.)
2636 directory <bookmark_name>, but a bookmark with the name exists.)
2637 'cd -b <tab>' allows you to tab-complete bookmark names.
2637 'cd -b <tab>' allows you to tab-complete bookmark names.
2638
2638
2639 Options:
2639 Options:
2640
2640
2641 -q: quiet. Do not print the working directory after the cd command is
2641 -q: quiet. Do not print the working directory after the cd command is
2642 executed. By default IPython's cd command does print this directory,
2642 executed. By default IPython's cd command does print this directory,
2643 since the default prompts do not display path information.
2643 since the default prompts do not display path information.
2644
2644
2645 Note that !cd doesn't work for this purpose because the shell where
2645 Note that !cd doesn't work for this purpose because the shell where
2646 !command runs is immediately discarded after executing 'command'."""
2646 !command runs is immediately discarded after executing 'command'."""
2647
2647
2648 parameter_s = parameter_s.strip()
2648 parameter_s = parameter_s.strip()
2649 #bkms = self.shell.persist.get("bookmarks",{})
2649 #bkms = self.shell.persist.get("bookmarks",{})
2650
2650
2651 oldcwd = os.getcwd()
2651 oldcwd = os.getcwd()
2652 numcd = re.match(r'(-)(\d+)$',parameter_s)
2652 numcd = re.match(r'(-)(\d+)$',parameter_s)
2653 # jump in directory history by number
2653 # jump in directory history by number
2654 if numcd:
2654 if numcd:
2655 nn = int(numcd.group(2))
2655 nn = int(numcd.group(2))
2656 try:
2656 try:
2657 ps = self.shell.user_ns['_dh'][nn]
2657 ps = self.shell.user_ns['_dh'][nn]
2658 except IndexError:
2658 except IndexError:
2659 print 'The requested directory does not exist in history.'
2659 print 'The requested directory does not exist in history.'
2660 return
2660 return
2661 else:
2661 else:
2662 opts = {}
2662 opts = {}
2663 elif parameter_s.startswith('--'):
2663 elif parameter_s.startswith('--'):
2664 ps = None
2664 ps = None
2665 fallback = None
2665 fallback = None
2666 pat = parameter_s[2:]
2666 pat = parameter_s[2:]
2667 dh = self.shell.user_ns['_dh']
2667 dh = self.shell.user_ns['_dh']
2668 # first search only by basename (last component)
2668 # first search only by basename (last component)
2669 for ent in reversed(dh):
2669 for ent in reversed(dh):
2670 if pat in os.path.basename(ent) and os.path.isdir(ent):
2670 if pat in os.path.basename(ent) and os.path.isdir(ent):
2671 ps = ent
2671 ps = ent
2672 break
2672 break
2673
2673
2674 if fallback is None and pat in ent and os.path.isdir(ent):
2674 if fallback is None and pat in ent and os.path.isdir(ent):
2675 fallback = ent
2675 fallback = ent
2676
2676
2677 # if we have no last part match, pick the first full path match
2677 # if we have no last part match, pick the first full path match
2678 if ps is None:
2678 if ps is None:
2679 ps = fallback
2679 ps = fallback
2680
2680
2681 if ps is None:
2681 if ps is None:
2682 print "No matching entry in directory history"
2682 print "No matching entry in directory history"
2683 return
2683 return
2684 else:
2684 else:
2685 opts = {}
2685 opts = {}
2686
2686
2687
2687
2688 else:
2688 else:
2689 #turn all non-space-escaping backslashes to slashes,
2689 #turn all non-space-escaping backslashes to slashes,
2690 # for c:\windows\directory\names\
2690 # for c:\windows\directory\names\
2691 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2691 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2692 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2692 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2693 # jump to previous
2693 # jump to previous
2694 if ps == '-':
2694 if ps == '-':
2695 try:
2695 try:
2696 ps = self.shell.user_ns['_dh'][-2]
2696 ps = self.shell.user_ns['_dh'][-2]
2697 except IndexError:
2697 except IndexError:
2698 raise UsageError('%cd -: No previous directory to change to.')
2698 raise UsageError('%cd -: No previous directory to change to.')
2699 # jump to bookmark if needed
2699 # jump to bookmark if needed
2700 else:
2700 else:
2701 if not os.path.isdir(ps) or opts.has_key('b'):
2701 if not os.path.isdir(ps) or opts.has_key('b'):
2702 bkms = self.db.get('bookmarks', {})
2702 bkms = self.db.get('bookmarks', {})
2703
2703
2704 if bkms.has_key(ps):
2704 if bkms.has_key(ps):
2705 target = bkms[ps]
2705 target = bkms[ps]
2706 print '(bookmark:%s) -> %s' % (ps,target)
2706 print '(bookmark:%s) -> %s' % (ps,target)
2707 ps = target
2707 ps = target
2708 else:
2708 else:
2709 if opts.has_key('b'):
2709 if opts.has_key('b'):
2710 raise UsageError("Bookmark '%s' not found. "
2710 raise UsageError("Bookmark '%s' not found. "
2711 "Use '%%bookmark -l' to see your bookmarks." % ps)
2711 "Use '%%bookmark -l' to see your bookmarks." % ps)
2712
2712
2713 # at this point ps should point to the target dir
2713 # at this point ps should point to the target dir
2714 if ps:
2714 if ps:
2715 try:
2715 try:
2716 os.chdir(os.path.expanduser(ps))
2716 os.chdir(os.path.expanduser(ps))
2717 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2717 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2718 set_term_title('IPython: ' + abbrev_cwd())
2718 set_term_title('IPython: ' + abbrev_cwd())
2719 except OSError:
2719 except OSError:
2720 print sys.exc_info()[1]
2720 print sys.exc_info()[1]
2721 else:
2721 else:
2722 cwd = os.getcwd()
2722 cwd = os.getcwd()
2723 dhist = self.shell.user_ns['_dh']
2723 dhist = self.shell.user_ns['_dh']
2724 if oldcwd != cwd:
2724 if oldcwd != cwd:
2725 dhist.append(cwd)
2725 dhist.append(cwd)
2726 self.db['dhist'] = compress_dhist(dhist)[-100:]
2726 self.db['dhist'] = compress_dhist(dhist)[-100:]
2727
2727
2728 else:
2728 else:
2729 os.chdir(self.shell.home_dir)
2729 os.chdir(self.shell.home_dir)
2730 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2730 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2731 set_term_title('IPython: ' + '~')
2731 set_term_title('IPython: ' + '~')
2732 cwd = os.getcwd()
2732 cwd = os.getcwd()
2733 dhist = self.shell.user_ns['_dh']
2733 dhist = self.shell.user_ns['_dh']
2734
2734
2735 if oldcwd != cwd:
2735 if oldcwd != cwd:
2736 dhist.append(cwd)
2736 dhist.append(cwd)
2737 self.db['dhist'] = compress_dhist(dhist)[-100:]
2737 self.db['dhist'] = compress_dhist(dhist)[-100:]
2738 if not 'q' in opts and self.shell.user_ns['_dh']:
2738 if not 'q' in opts and self.shell.user_ns['_dh']:
2739 print self.shell.user_ns['_dh'][-1]
2739 print self.shell.user_ns['_dh'][-1]
2740
2740
2741
2741
2742 def magic_env(self, parameter_s=''):
2742 def magic_env(self, parameter_s=''):
2743 """List environment variables."""
2743 """List environment variables."""
2744
2744
2745 return os.environ.data
2745 return os.environ.data
2746
2746
2747 def magic_pushd(self, parameter_s=''):
2747 def magic_pushd(self, parameter_s=''):
2748 """Place the current dir on stack and change directory.
2748 """Place the current dir on stack and change directory.
2749
2749
2750 Usage:\\
2750 Usage:\\
2751 %pushd ['dirname']
2751 %pushd ['dirname']
2752 """
2752 """
2753
2753
2754 dir_s = self.shell.dir_stack
2754 dir_s = self.shell.dir_stack
2755 tgt = os.path.expanduser(parameter_s)
2755 tgt = os.path.expanduser(parameter_s)
2756 cwd = os.getcwd().replace(self.home_dir,'~')
2756 cwd = os.getcwd().replace(self.home_dir,'~')
2757 if tgt:
2757 if tgt:
2758 self.magic_cd(parameter_s)
2758 self.magic_cd(parameter_s)
2759 dir_s.insert(0,cwd)
2759 dir_s.insert(0,cwd)
2760 return self.magic_dirs()
2760 return self.magic_dirs()
2761
2761
2762 def magic_popd(self, parameter_s=''):
2762 def magic_popd(self, parameter_s=''):
2763 """Change to directory popped off the top of the stack.
2763 """Change to directory popped off the top of the stack.
2764 """
2764 """
2765 if not self.shell.dir_stack:
2765 if not self.shell.dir_stack:
2766 raise UsageError("%popd on empty stack")
2766 raise UsageError("%popd on empty stack")
2767 top = self.shell.dir_stack.pop(0)
2767 top = self.shell.dir_stack.pop(0)
2768 self.magic_cd(top)
2768 self.magic_cd(top)
2769 print "popd ->",top
2769 print "popd ->",top
2770
2770
2771 def magic_dirs(self, parameter_s=''):
2771 def magic_dirs(self, parameter_s=''):
2772 """Return the current directory stack."""
2772 """Return the current directory stack."""
2773
2773
2774 return self.shell.dir_stack
2774 return self.shell.dir_stack
2775
2775
2776 def magic_dhist(self, parameter_s=''):
2776 def magic_dhist(self, parameter_s=''):
2777 """Print your history of visited directories.
2777 """Print your history of visited directories.
2778
2778
2779 %dhist -> print full history\\
2779 %dhist -> print full history\\
2780 %dhist n -> print last n entries only\\
2780 %dhist n -> print last n entries only\\
2781 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2781 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2782
2782
2783 This history is automatically maintained by the %cd command, and
2783 This history is automatically maintained by the %cd command, and
2784 always available as the global list variable _dh. You can use %cd -<n>
2784 always available as the global list variable _dh. You can use %cd -<n>
2785 to go to directory number <n>.
2785 to go to directory number <n>.
2786
2786
2787 Note that most of time, you should view directory history by entering
2787 Note that most of time, you should view directory history by entering
2788 cd -<TAB>.
2788 cd -<TAB>.
2789
2789
2790 """
2790 """
2791
2791
2792 dh = self.shell.user_ns['_dh']
2792 dh = self.shell.user_ns['_dh']
2793 if parameter_s:
2793 if parameter_s:
2794 try:
2794 try:
2795 args = map(int,parameter_s.split())
2795 args = map(int,parameter_s.split())
2796 except:
2796 except:
2797 self.arg_err(Magic.magic_dhist)
2797 self.arg_err(Magic.magic_dhist)
2798 return
2798 return
2799 if len(args) == 1:
2799 if len(args) == 1:
2800 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2800 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2801 elif len(args) == 2:
2801 elif len(args) == 2:
2802 ini,fin = args
2802 ini,fin = args
2803 else:
2803 else:
2804 self.arg_err(Magic.magic_dhist)
2804 self.arg_err(Magic.magic_dhist)
2805 return
2805 return
2806 else:
2806 else:
2807 ini,fin = 0,len(dh)
2807 ini,fin = 0,len(dh)
2808 nlprint(dh,
2808 nlprint(dh,
2809 header = 'Directory history (kept in _dh)',
2809 header = 'Directory history (kept in _dh)',
2810 start=ini,stop=fin)
2810 start=ini,stop=fin)
2811
2811
2812 @testdec.skip_doctest
2812 @testdec.skip_doctest
2813 def magic_sc(self, parameter_s=''):
2813 def magic_sc(self, parameter_s=''):
2814 """Shell capture - execute a shell command and capture its output.
2814 """Shell capture - execute a shell command and capture its output.
2815
2815
2816 DEPRECATED. Suboptimal, retained for backwards compatibility.
2816 DEPRECATED. Suboptimal, retained for backwards compatibility.
2817
2817
2818 You should use the form 'var = !command' instead. Example:
2818 You should use the form 'var = !command' instead. Example:
2819
2819
2820 "%sc -l myfiles = ls ~" should now be written as
2820 "%sc -l myfiles = ls ~" should now be written as
2821
2821
2822 "myfiles = !ls ~"
2822 "myfiles = !ls ~"
2823
2823
2824 myfiles.s, myfiles.l and myfiles.n still apply as documented
2824 myfiles.s, myfiles.l and myfiles.n still apply as documented
2825 below.
2825 below.
2826
2826
2827 --
2827 --
2828 %sc [options] varname=command
2828 %sc [options] varname=command
2829
2829
2830 IPython will run the given command using commands.getoutput(), and
2830 IPython will run the given command using commands.getoutput(), and
2831 will then update the user's interactive namespace with a variable
2831 will then update the user's interactive namespace with a variable
2832 called varname, containing the value of the call. Your command can
2832 called varname, containing the value of the call. Your command can
2833 contain shell wildcards, pipes, etc.
2833 contain shell wildcards, pipes, etc.
2834
2834
2835 The '=' sign in the syntax is mandatory, and the variable name you
2835 The '=' sign in the syntax is mandatory, and the variable name you
2836 supply must follow Python's standard conventions for valid names.
2836 supply must follow Python's standard conventions for valid names.
2837
2837
2838 (A special format without variable name exists for internal use)
2838 (A special format without variable name exists for internal use)
2839
2839
2840 Options:
2840 Options:
2841
2841
2842 -l: list output. Split the output on newlines into a list before
2842 -l: list output. Split the output on newlines into a list before
2843 assigning it to the given variable. By default the output is stored
2843 assigning it to the given variable. By default the output is stored
2844 as a single string.
2844 as a single string.
2845
2845
2846 -v: verbose. Print the contents of the variable.
2846 -v: verbose. Print the contents of the variable.
2847
2847
2848 In most cases you should not need to split as a list, because the
2848 In most cases you should not need to split as a list, because the
2849 returned value is a special type of string which can automatically
2849 returned value is a special type of string which can automatically
2850 provide its contents either as a list (split on newlines) or as a
2850 provide its contents either as a list (split on newlines) or as a
2851 space-separated string. These are convenient, respectively, either
2851 space-separated string. These are convenient, respectively, either
2852 for sequential processing or to be passed to a shell command.
2852 for sequential processing or to be passed to a shell command.
2853
2853
2854 For example:
2854 For example:
2855
2855
2856 # all-random
2856 # all-random
2857
2857
2858 # Capture into variable a
2858 # Capture into variable a
2859 In [1]: sc a=ls *py
2859 In [1]: sc a=ls *py
2860
2860
2861 # a is a string with embedded newlines
2861 # a is a string with embedded newlines
2862 In [2]: a
2862 In [2]: a
2863 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2863 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2864
2864
2865 # which can be seen as a list:
2865 # which can be seen as a list:
2866 In [3]: a.l
2866 In [3]: a.l
2867 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2867 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2868
2868
2869 # or as a whitespace-separated string:
2869 # or as a whitespace-separated string:
2870 In [4]: a.s
2870 In [4]: a.s
2871 Out[4]: 'setup.py win32_manual_post_install.py'
2871 Out[4]: 'setup.py win32_manual_post_install.py'
2872
2872
2873 # a.s is useful to pass as a single command line:
2873 # a.s is useful to pass as a single command line:
2874 In [5]: !wc -l $a.s
2874 In [5]: !wc -l $a.s
2875 146 setup.py
2875 146 setup.py
2876 130 win32_manual_post_install.py
2876 130 win32_manual_post_install.py
2877 276 total
2877 276 total
2878
2878
2879 # while the list form is useful to loop over:
2879 # while the list form is useful to loop over:
2880 In [6]: for f in a.l:
2880 In [6]: for f in a.l:
2881 ...: !wc -l $f
2881 ...: !wc -l $f
2882 ...:
2882 ...:
2883 146 setup.py
2883 146 setup.py
2884 130 win32_manual_post_install.py
2884 130 win32_manual_post_install.py
2885
2885
2886 Similiarly, the lists returned by the -l option are also special, in
2886 Similiarly, the lists returned by the -l option are also special, in
2887 the sense that you can equally invoke the .s attribute on them to
2887 the sense that you can equally invoke the .s attribute on them to
2888 automatically get a whitespace-separated string from their contents:
2888 automatically get a whitespace-separated string from their contents:
2889
2889
2890 In [7]: sc -l b=ls *py
2890 In [7]: sc -l b=ls *py
2891
2891
2892 In [8]: b
2892 In [8]: b
2893 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2893 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2894
2894
2895 In [9]: b.s
2895 In [9]: b.s
2896 Out[9]: 'setup.py win32_manual_post_install.py'
2896 Out[9]: 'setup.py win32_manual_post_install.py'
2897
2897
2898 In summary, both the lists and strings used for ouptut capture have
2898 In summary, both the lists and strings used for ouptut capture have
2899 the following special attributes:
2899 the following special attributes:
2900
2900
2901 .l (or .list) : value as list.
2901 .l (or .list) : value as list.
2902 .n (or .nlstr): value as newline-separated string.
2902 .n (or .nlstr): value as newline-separated string.
2903 .s (or .spstr): value as space-separated string.
2903 .s (or .spstr): value as space-separated string.
2904 """
2904 """
2905
2905
2906 opts,args = self.parse_options(parameter_s,'lv')
2906 opts,args = self.parse_options(parameter_s,'lv')
2907 # Try to get a variable name and command to run
2907 # Try to get a variable name and command to run
2908 try:
2908 try:
2909 # the variable name must be obtained from the parse_options
2909 # the variable name must be obtained from the parse_options
2910 # output, which uses shlex.split to strip options out.
2910 # output, which uses shlex.split to strip options out.
2911 var,_ = args.split('=',1)
2911 var,_ = args.split('=',1)
2912 var = var.strip()
2912 var = var.strip()
2913 # But the the command has to be extracted from the original input
2913 # But the the command has to be extracted from the original input
2914 # parameter_s, not on what parse_options returns, to avoid the
2914 # parameter_s, not on what parse_options returns, to avoid the
2915 # quote stripping which shlex.split performs on it.
2915 # quote stripping which shlex.split performs on it.
2916 _,cmd = parameter_s.split('=',1)
2916 _,cmd = parameter_s.split('=',1)
2917 except ValueError:
2917 except ValueError:
2918 var,cmd = '',''
2918 var,cmd = '',''
2919 # If all looks ok, proceed
2919 # If all looks ok, proceed
2920 out = self.shell.getoutput(cmd)
2920 split = 'l' in opts
2921 if opts.has_key('l'):
2921 out = self.shell.getoutput(cmd, split=split)
2922 out = SList(out.splitlines())
2923 else:
2924 out = LSString(out)
2925 if opts.has_key('v'):
2922 if opts.has_key('v'):
2926 print '%s ==\n%s' % (var,pformat(out))
2923 print '%s ==\n%s' % (var,pformat(out))
2927 if var:
2924 if var:
2928 self.shell.user_ns.update({var:out})
2925 self.shell.user_ns.update({var:out})
2929 else:
2926 else:
2930 return out
2927 return out
2931
2928
2932 def magic_sx(self, parameter_s=''):
2929 def magic_sx(self, parameter_s=''):
2933 """Shell execute - run a shell command and capture its output.
2930 """Shell execute - run a shell command and capture its output.
2934
2931
2935 %sx command
2932 %sx command
2936
2933
2937 IPython will run the given command using commands.getoutput(), and
2934 IPython will run the given command using commands.getoutput(), and
2938 return the result formatted as a list (split on '\\n'). Since the
2935 return the result formatted as a list (split on '\\n'). Since the
2939 output is _returned_, it will be stored in ipython's regular output
2936 output is _returned_, it will be stored in ipython's regular output
2940 cache Out[N] and in the '_N' automatic variables.
2937 cache Out[N] and in the '_N' automatic variables.
2941
2938
2942 Notes:
2939 Notes:
2943
2940
2944 1) If an input line begins with '!!', then %sx is automatically
2941 1) If an input line begins with '!!', then %sx is automatically
2945 invoked. That is, while:
2942 invoked. That is, while:
2946 !ls
2943 !ls
2947 causes ipython to simply issue system('ls'), typing
2944 causes ipython to simply issue system('ls'), typing
2948 !!ls
2945 !!ls
2949 is a shorthand equivalent to:
2946 is a shorthand equivalent to:
2950 %sx ls
2947 %sx ls
2951
2948
2952 2) %sx differs from %sc in that %sx automatically splits into a list,
2949 2) %sx differs from %sc in that %sx automatically splits into a list,
2953 like '%sc -l'. The reason for this is to make it as easy as possible
2950 like '%sc -l'. The reason for this is to make it as easy as possible
2954 to process line-oriented shell output via further python commands.
2951 to process line-oriented shell output via further python commands.
2955 %sc is meant to provide much finer control, but requires more
2952 %sc is meant to provide much finer control, but requires more
2956 typing.
2953 typing.
2957
2954
2958 3) Just like %sc -l, this is a list with special attributes:
2955 3) Just like %sc -l, this is a list with special attributes:
2959
2956
2960 .l (or .list) : value as list.
2957 .l (or .list) : value as list.
2961 .n (or .nlstr): value as newline-separated string.
2958 .n (or .nlstr): value as newline-separated string.
2962 .s (or .spstr): value as whitespace-separated string.
2959 .s (or .spstr): value as whitespace-separated string.
2963
2960
2964 This is very useful when trying to use such lists as arguments to
2961 This is very useful when trying to use such lists as arguments to
2965 system commands."""
2962 system commands."""
2966
2963
2967 if parameter_s:
2964 if parameter_s:
2968 out = self.shell.getoutput(parameter_s)
2965 return self.shell.getoutput(parameter_s)
2969 if out is not None:
2970 return SList(out.splitlines())
2971
2966
2972 def magic_r(self, parameter_s=''):
2967 def magic_r(self, parameter_s=''):
2973 """Repeat previous input.
2968 """Repeat previous input.
2974
2969
2975 Note: Consider using the more powerfull %rep instead!
2970 Note: Consider using the more powerfull %rep instead!
2976
2971
2977 If given an argument, repeats the previous command which starts with
2972 If given an argument, repeats the previous command which starts with
2978 the same string, otherwise it just repeats the previous input.
2973 the same string, otherwise it just repeats the previous input.
2979
2974
2980 Shell escaped commands (with ! as first character) are not recognized
2975 Shell escaped commands (with ! as first character) are not recognized
2981 by this system, only pure python code and magic commands.
2976 by this system, only pure python code and magic commands.
2982 """
2977 """
2983
2978
2984 start = parameter_s.strip()
2979 start = parameter_s.strip()
2985 esc_magic = ESC_MAGIC
2980 esc_magic = ESC_MAGIC
2986 # Identify magic commands even if automagic is on (which means
2981 # Identify magic commands even if automagic is on (which means
2987 # the in-memory version is different from that typed by the user).
2982 # the in-memory version is different from that typed by the user).
2988 if self.shell.automagic:
2983 if self.shell.automagic:
2989 start_magic = esc_magic+start
2984 start_magic = esc_magic+start
2990 else:
2985 else:
2991 start_magic = start
2986 start_magic = start
2992 # Look through the input history in reverse
2987 # Look through the input history in reverse
2993 for n in range(len(self.shell.input_hist)-2,0,-1):
2988 for n in range(len(self.shell.input_hist)-2,0,-1):
2994 input = self.shell.input_hist[n]
2989 input = self.shell.input_hist[n]
2995 # skip plain 'r' lines so we don't recurse to infinity
2990 # skip plain 'r' lines so we don't recurse to infinity
2996 if input != '_ip.magic("r")\n' and \
2991 if input != '_ip.magic("r")\n' and \
2997 (input.startswith(start) or input.startswith(start_magic)):
2992 (input.startswith(start) or input.startswith(start_magic)):
2998 #print 'match',`input` # dbg
2993 #print 'match',`input` # dbg
2999 print 'Executing:',input,
2994 print 'Executing:',input,
3000 self.shell.runlines(input)
2995 self.shell.runlines(input)
3001 return
2996 return
3002 print 'No previous input matching `%s` found.' % start
2997 print 'No previous input matching `%s` found.' % start
3003
2998
3004
2999
3005 def magic_bookmark(self, parameter_s=''):
3000 def magic_bookmark(self, parameter_s=''):
3006 """Manage IPython's bookmark system.
3001 """Manage IPython's bookmark system.
3007
3002
3008 %bookmark <name> - set bookmark to current dir
3003 %bookmark <name> - set bookmark to current dir
3009 %bookmark <name> <dir> - set bookmark to <dir>
3004 %bookmark <name> <dir> - set bookmark to <dir>
3010 %bookmark -l - list all bookmarks
3005 %bookmark -l - list all bookmarks
3011 %bookmark -d <name> - remove bookmark
3006 %bookmark -d <name> - remove bookmark
3012 %bookmark -r - remove all bookmarks
3007 %bookmark -r - remove all bookmarks
3013
3008
3014 You can later on access a bookmarked folder with:
3009 You can later on access a bookmarked folder with:
3015 %cd -b <name>
3010 %cd -b <name>
3016 or simply '%cd <name>' if there is no directory called <name> AND
3011 or simply '%cd <name>' if there is no directory called <name> AND
3017 there is such a bookmark defined.
3012 there is such a bookmark defined.
3018
3013
3019 Your bookmarks persist through IPython sessions, but they are
3014 Your bookmarks persist through IPython sessions, but they are
3020 associated with each profile."""
3015 associated with each profile."""
3021
3016
3022 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3017 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3023 if len(args) > 2:
3018 if len(args) > 2:
3024 raise UsageError("%bookmark: too many arguments")
3019 raise UsageError("%bookmark: too many arguments")
3025
3020
3026 bkms = self.db.get('bookmarks',{})
3021 bkms = self.db.get('bookmarks',{})
3027
3022
3028 if opts.has_key('d'):
3023 if opts.has_key('d'):
3029 try:
3024 try:
3030 todel = args[0]
3025 todel = args[0]
3031 except IndexError:
3026 except IndexError:
3032 raise UsageError(
3027 raise UsageError(
3033 "%bookmark -d: must provide a bookmark to delete")
3028 "%bookmark -d: must provide a bookmark to delete")
3034 else:
3029 else:
3035 try:
3030 try:
3036 del bkms[todel]
3031 del bkms[todel]
3037 except KeyError:
3032 except KeyError:
3038 raise UsageError(
3033 raise UsageError(
3039 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3034 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3040
3035
3041 elif opts.has_key('r'):
3036 elif opts.has_key('r'):
3042 bkms = {}
3037 bkms = {}
3043 elif opts.has_key('l'):
3038 elif opts.has_key('l'):
3044 bks = bkms.keys()
3039 bks = bkms.keys()
3045 bks.sort()
3040 bks.sort()
3046 if bks:
3041 if bks:
3047 size = max(map(len,bks))
3042 size = max(map(len,bks))
3048 else:
3043 else:
3049 size = 0
3044 size = 0
3050 fmt = '%-'+str(size)+'s -> %s'
3045 fmt = '%-'+str(size)+'s -> %s'
3051 print 'Current bookmarks:'
3046 print 'Current bookmarks:'
3052 for bk in bks:
3047 for bk in bks:
3053 print fmt % (bk,bkms[bk])
3048 print fmt % (bk,bkms[bk])
3054 else:
3049 else:
3055 if not args:
3050 if not args:
3056 raise UsageError("%bookmark: You must specify the bookmark name")
3051 raise UsageError("%bookmark: You must specify the bookmark name")
3057 elif len(args)==1:
3052 elif len(args)==1:
3058 bkms[args[0]] = os.getcwd()
3053 bkms[args[0]] = os.getcwd()
3059 elif len(args)==2:
3054 elif len(args)==2:
3060 bkms[args[0]] = args[1]
3055 bkms[args[0]] = args[1]
3061 self.db['bookmarks'] = bkms
3056 self.db['bookmarks'] = bkms
3062
3057
3063 def magic_pycat(self, parameter_s=''):
3058 def magic_pycat(self, parameter_s=''):
3064 """Show a syntax-highlighted file through a pager.
3059 """Show a syntax-highlighted file through a pager.
3065
3060
3066 This magic is similar to the cat utility, but it will assume the file
3061 This magic is similar to the cat utility, but it will assume the file
3067 to be Python source and will show it with syntax highlighting. """
3062 to be Python source and will show it with syntax highlighting. """
3068
3063
3069 try:
3064 try:
3070 filename = get_py_filename(parameter_s)
3065 filename = get_py_filename(parameter_s)
3071 cont = file_read(filename)
3066 cont = file_read(filename)
3072 except IOError:
3067 except IOError:
3073 try:
3068 try:
3074 cont = eval(parameter_s,self.user_ns)
3069 cont = eval(parameter_s,self.user_ns)
3075 except NameError:
3070 except NameError:
3076 cont = None
3071 cont = None
3077 if cont is None:
3072 if cont is None:
3078 print "Error: no such file or variable"
3073 print "Error: no such file or variable"
3079 return
3074 return
3080
3075
3081 page.page(self.shell.pycolorize(cont))
3076 page.page(self.shell.pycolorize(cont))
3082
3077
3083 def _rerun_pasted(self):
3078 def _rerun_pasted(self):
3084 """ Rerun a previously pasted command.
3079 """ Rerun a previously pasted command.
3085 """
3080 """
3086 b = self.user_ns.get('pasted_block', None)
3081 b = self.user_ns.get('pasted_block', None)
3087 if b is None:
3082 if b is None:
3088 raise UsageError('No previous pasted block available')
3083 raise UsageError('No previous pasted block available')
3089 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3084 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3090 exec b in self.user_ns
3085 exec b in self.user_ns
3091
3086
3092 def _get_pasted_lines(self, sentinel):
3087 def _get_pasted_lines(self, sentinel):
3093 """ Yield pasted lines until the user enters the given sentinel value.
3088 """ Yield pasted lines until the user enters the given sentinel value.
3094 """
3089 """
3095 from IPython.core import interactiveshell
3090 from IPython.core import interactiveshell
3096 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3091 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3097 while True:
3092 while True:
3098 l = interactiveshell.raw_input_original(':')
3093 l = interactiveshell.raw_input_original(':')
3099 if l == sentinel:
3094 if l == sentinel:
3100 return
3095 return
3101 else:
3096 else:
3102 yield l
3097 yield l
3103
3098
3104 def _strip_pasted_lines_for_code(self, raw_lines):
3099 def _strip_pasted_lines_for_code(self, raw_lines):
3105 """ Strip non-code parts of a sequence of lines to return a block of
3100 """ Strip non-code parts of a sequence of lines to return a block of
3106 code.
3101 code.
3107 """
3102 """
3108 # Regular expressions that declare text we strip from the input:
3103 # Regular expressions that declare text we strip from the input:
3109 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3104 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3110 r'^\s*(\s?>)+', # Python input prompt
3105 r'^\s*(\s?>)+', # Python input prompt
3111 r'^\s*\.{3,}', # Continuation prompts
3106 r'^\s*\.{3,}', # Continuation prompts
3112 r'^\++',
3107 r'^\++',
3113 ]
3108 ]
3114
3109
3115 strip_from_start = map(re.compile,strip_re)
3110 strip_from_start = map(re.compile,strip_re)
3116
3111
3117 lines = []
3112 lines = []
3118 for l in raw_lines:
3113 for l in raw_lines:
3119 for pat in strip_from_start:
3114 for pat in strip_from_start:
3120 l = pat.sub('',l)
3115 l = pat.sub('',l)
3121 lines.append(l)
3116 lines.append(l)
3122
3117
3123 block = "\n".join(lines) + '\n'
3118 block = "\n".join(lines) + '\n'
3124 #print "block:\n",block
3119 #print "block:\n",block
3125 return block
3120 return block
3126
3121
3127 def _execute_block(self, block, par):
3122 def _execute_block(self, block, par):
3128 """ Execute a block, or store it in a variable, per the user's request.
3123 """ Execute a block, or store it in a variable, per the user's request.
3129 """
3124 """
3130 if not par:
3125 if not par:
3131 b = textwrap.dedent(block)
3126 b = textwrap.dedent(block)
3132 self.user_ns['pasted_block'] = b
3127 self.user_ns['pasted_block'] = b
3133 exec b in self.user_ns
3128 exec b in self.user_ns
3134 else:
3129 else:
3135 self.user_ns[par] = SList(block.splitlines())
3130 self.user_ns[par] = SList(block.splitlines())
3136 print "Block assigned to '%s'" % par
3131 print "Block assigned to '%s'" % par
3137
3132
3138 def magic_quickref(self,arg):
3133 def magic_quickref(self,arg):
3139 """ Show a quick reference sheet """
3134 """ Show a quick reference sheet """
3140 import IPython.core.usage
3135 import IPython.core.usage
3141 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3136 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3142
3137
3143 page.page(qr)
3138 page.page(qr)
3144
3139
3145 def magic_doctest_mode(self,parameter_s=''):
3140 def magic_doctest_mode(self,parameter_s=''):
3146 """Toggle doctest mode on and off.
3141 """Toggle doctest mode on and off.
3147
3142
3148 This mode is intended to make IPython behave as much as possible like a
3143 This mode is intended to make IPython behave as much as possible like a
3149 plain Python shell, from the perspective of how its prompts, exceptions
3144 plain Python shell, from the perspective of how its prompts, exceptions
3150 and output look. This makes it easy to copy and paste parts of a
3145 and output look. This makes it easy to copy and paste parts of a
3151 session into doctests. It does so by:
3146 session into doctests. It does so by:
3152
3147
3153 - Changing the prompts to the classic ``>>>`` ones.
3148 - Changing the prompts to the classic ``>>>`` ones.
3154 - Changing the exception reporting mode to 'Plain'.
3149 - Changing the exception reporting mode to 'Plain'.
3155 - Disabling pretty-printing of output.
3150 - Disabling pretty-printing of output.
3156
3151
3157 Note that IPython also supports the pasting of code snippets that have
3152 Note that IPython also supports the pasting of code snippets that have
3158 leading '>>>' and '...' prompts in them. This means that you can paste
3153 leading '>>>' and '...' prompts in them. This means that you can paste
3159 doctests from files or docstrings (even if they have leading
3154 doctests from files or docstrings (even if they have leading
3160 whitespace), and the code will execute correctly. You can then use
3155 whitespace), and the code will execute correctly. You can then use
3161 '%history -t' to see the translated history; this will give you the
3156 '%history -t' to see the translated history; this will give you the
3162 input after removal of all the leading prompts and whitespace, which
3157 input after removal of all the leading prompts and whitespace, which
3163 can be pasted back into an editor.
3158 can be pasted back into an editor.
3164
3159
3165 With these features, you can switch into this mode easily whenever you
3160 With these features, you can switch into this mode easily whenever you
3166 need to do testing and changes to doctests, without having to leave
3161 need to do testing and changes to doctests, without having to leave
3167 your existing IPython session.
3162 your existing IPython session.
3168 """
3163 """
3169
3164
3170 from IPython.utils.ipstruct import Struct
3165 from IPython.utils.ipstruct import Struct
3171
3166
3172 # Shorthands
3167 # Shorthands
3173 shell = self.shell
3168 shell = self.shell
3174 oc = shell.displayhook
3169 oc = shell.displayhook
3175 meta = shell.meta
3170 meta = shell.meta
3176 # dstore is a data store kept in the instance metadata bag to track any
3171 # dstore is a data store kept in the instance metadata bag to track any
3177 # changes we make, so we can undo them later.
3172 # changes we make, so we can undo them later.
3178 dstore = meta.setdefault('doctest_mode',Struct())
3173 dstore = meta.setdefault('doctest_mode',Struct())
3179 save_dstore = dstore.setdefault
3174 save_dstore = dstore.setdefault
3180
3175
3181 # save a few values we'll need to recover later
3176 # save a few values we'll need to recover later
3182 mode = save_dstore('mode',False)
3177 mode = save_dstore('mode',False)
3183 save_dstore('rc_pprint',shell.pprint)
3178 save_dstore('rc_pprint',shell.pprint)
3184 save_dstore('xmode',shell.InteractiveTB.mode)
3179 save_dstore('xmode',shell.InteractiveTB.mode)
3185 save_dstore('rc_separate_out',shell.separate_out)
3180 save_dstore('rc_separate_out',shell.separate_out)
3186 save_dstore('rc_separate_out2',shell.separate_out2)
3181 save_dstore('rc_separate_out2',shell.separate_out2)
3187 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3182 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3188 save_dstore('rc_separate_in',shell.separate_in)
3183 save_dstore('rc_separate_in',shell.separate_in)
3189
3184
3190 if mode == False:
3185 if mode == False:
3191 # turn on
3186 # turn on
3192 oc.prompt1.p_template = '>>> '
3187 oc.prompt1.p_template = '>>> '
3193 oc.prompt2.p_template = '... '
3188 oc.prompt2.p_template = '... '
3194 oc.prompt_out.p_template = ''
3189 oc.prompt_out.p_template = ''
3195
3190
3196 # Prompt separators like plain python
3191 # Prompt separators like plain python
3197 oc.input_sep = oc.prompt1.sep = ''
3192 oc.input_sep = oc.prompt1.sep = ''
3198 oc.output_sep = ''
3193 oc.output_sep = ''
3199 oc.output_sep2 = ''
3194 oc.output_sep2 = ''
3200
3195
3201 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3196 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3202 oc.prompt_out.pad_left = False
3197 oc.prompt_out.pad_left = False
3203
3198
3204 shell.pprint = False
3199 shell.pprint = False
3205
3200
3206 shell.magic_xmode('Plain')
3201 shell.magic_xmode('Plain')
3207 else:
3202 else:
3208 # turn off
3203 # turn off
3209 oc.prompt1.p_template = shell.prompt_in1
3204 oc.prompt1.p_template = shell.prompt_in1
3210 oc.prompt2.p_template = shell.prompt_in2
3205 oc.prompt2.p_template = shell.prompt_in2
3211 oc.prompt_out.p_template = shell.prompt_out
3206 oc.prompt_out.p_template = shell.prompt_out
3212
3207
3213 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3208 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3214
3209
3215 oc.output_sep = dstore.rc_separate_out
3210 oc.output_sep = dstore.rc_separate_out
3216 oc.output_sep2 = dstore.rc_separate_out2
3211 oc.output_sep2 = dstore.rc_separate_out2
3217
3212
3218 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3213 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3219 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3214 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3220
3215
3221 shell.pprint = dstore.rc_pprint
3216 shell.pprint = dstore.rc_pprint
3222
3217
3223 shell.magic_xmode(dstore.xmode)
3218 shell.magic_xmode(dstore.xmode)
3224
3219
3225 # Store new mode and inform
3220 # Store new mode and inform
3226 dstore.mode = bool(1-int(mode))
3221 dstore.mode = bool(1-int(mode))
3227 mode_label = ['OFF','ON'][dstore.mode]
3222 mode_label = ['OFF','ON'][dstore.mode]
3228 print 'Doctest mode is:', mode_label
3223 print 'Doctest mode is:', mode_label
3229
3224
3230 def magic_gui(self, parameter_s=''):
3225 def magic_gui(self, parameter_s=''):
3231 """Enable or disable IPython GUI event loop integration.
3226 """Enable or disable IPython GUI event loop integration.
3232
3227
3233 %gui [GUINAME]
3228 %gui [GUINAME]
3234
3229
3235 This magic replaces IPython's threaded shells that were activated
3230 This magic replaces IPython's threaded shells that were activated
3236 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3231 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3237 can now be enabled, disabled and swtiched at runtime and keyboard
3232 can now be enabled, disabled and swtiched at runtime and keyboard
3238 interrupts should work without any problems. The following toolkits
3233 interrupts should work without any problems. The following toolkits
3239 are supported: wxPython, PyQt4, PyGTK, and Tk::
3234 are supported: wxPython, PyQt4, PyGTK, and Tk::
3240
3235
3241 %gui wx # enable wxPython event loop integration
3236 %gui wx # enable wxPython event loop integration
3242 %gui qt4|qt # enable PyQt4 event loop integration
3237 %gui qt4|qt # enable PyQt4 event loop integration
3243 %gui gtk # enable PyGTK event loop integration
3238 %gui gtk # enable PyGTK event loop integration
3244 %gui tk # enable Tk event loop integration
3239 %gui tk # enable Tk event loop integration
3245 %gui # disable all event loop integration
3240 %gui # disable all event loop integration
3246
3241
3247 WARNING: after any of these has been called you can simply create
3242 WARNING: after any of these has been called you can simply create
3248 an application object, but DO NOT start the event loop yourself, as
3243 an application object, but DO NOT start the event loop yourself, as
3249 we have already handled that.
3244 we have already handled that.
3250 """
3245 """
3251 from IPython.lib.inputhook import enable_gui
3246 from IPython.lib.inputhook import enable_gui
3252 opts, arg = self.parse_options(parameter_s='')
3247 opts, arg = self.parse_options(parameter_s='')
3253 if arg=='': arg = None
3248 if arg=='': arg = None
3254 return enable_gui(arg)
3249 return enable_gui(arg)
3255
3250
3256 def magic_load_ext(self, module_str):
3251 def magic_load_ext(self, module_str):
3257 """Load an IPython extension by its module name."""
3252 """Load an IPython extension by its module name."""
3258 return self.extension_manager.load_extension(module_str)
3253 return self.extension_manager.load_extension(module_str)
3259
3254
3260 def magic_unload_ext(self, module_str):
3255 def magic_unload_ext(self, module_str):
3261 """Unload an IPython extension by its module name."""
3256 """Unload an IPython extension by its module name."""
3262 self.extension_manager.unload_extension(module_str)
3257 self.extension_manager.unload_extension(module_str)
3263
3258
3264 def magic_reload_ext(self, module_str):
3259 def magic_reload_ext(self, module_str):
3265 """Reload an IPython extension by its module name."""
3260 """Reload an IPython extension by its module name."""
3266 self.extension_manager.reload_extension(module_str)
3261 self.extension_manager.reload_extension(module_str)
3267
3262
3268 @testdec.skip_doctest
3263 @testdec.skip_doctest
3269 def magic_install_profiles(self, s):
3264 def magic_install_profiles(self, s):
3270 """Install the default IPython profiles into the .ipython dir.
3265 """Install the default IPython profiles into the .ipython dir.
3271
3266
3272 If the default profiles have already been installed, they will not
3267 If the default profiles have already been installed, they will not
3273 be overwritten. You can force overwriting them by using the ``-o``
3268 be overwritten. You can force overwriting them by using the ``-o``
3274 option::
3269 option::
3275
3270
3276 In [1]: %install_profiles -o
3271 In [1]: %install_profiles -o
3277 """
3272 """
3278 if '-o' in s:
3273 if '-o' in s:
3279 overwrite = True
3274 overwrite = True
3280 else:
3275 else:
3281 overwrite = False
3276 overwrite = False
3282 from IPython.config import profile
3277 from IPython.config import profile
3283 profile_dir = os.path.split(profile.__file__)[0]
3278 profile_dir = os.path.split(profile.__file__)[0]
3284 ipython_dir = self.ipython_dir
3279 ipython_dir = self.ipython_dir
3285 files = os.listdir(profile_dir)
3280 files = os.listdir(profile_dir)
3286
3281
3287 to_install = []
3282 to_install = []
3288 for f in files:
3283 for f in files:
3289 if f.startswith('ipython_config'):
3284 if f.startswith('ipython_config'):
3290 src = os.path.join(profile_dir, f)
3285 src = os.path.join(profile_dir, f)
3291 dst = os.path.join(ipython_dir, f)
3286 dst = os.path.join(ipython_dir, f)
3292 if (not os.path.isfile(dst)) or overwrite:
3287 if (not os.path.isfile(dst)) or overwrite:
3293 to_install.append((f, src, dst))
3288 to_install.append((f, src, dst))
3294 if len(to_install)>0:
3289 if len(to_install)>0:
3295 print "Installing profiles to: ", ipython_dir
3290 print "Installing profiles to: ", ipython_dir
3296 for (f, src, dst) in to_install:
3291 for (f, src, dst) in to_install:
3297 shutil.copy(src, dst)
3292 shutil.copy(src, dst)
3298 print " %s" % f
3293 print " %s" % f
3299
3294
3300 def magic_install_default_config(self, s):
3295 def magic_install_default_config(self, s):
3301 """Install IPython's default config file into the .ipython dir.
3296 """Install IPython's default config file into the .ipython dir.
3302
3297
3303 If the default config file (:file:`ipython_config.py`) is already
3298 If the default config file (:file:`ipython_config.py`) is already
3304 installed, it will not be overwritten. You can force overwriting
3299 installed, it will not be overwritten. You can force overwriting
3305 by using the ``-o`` option::
3300 by using the ``-o`` option::
3306
3301
3307 In [1]: %install_default_config
3302 In [1]: %install_default_config
3308 """
3303 """
3309 if '-o' in s:
3304 if '-o' in s:
3310 overwrite = True
3305 overwrite = True
3311 else:
3306 else:
3312 overwrite = False
3307 overwrite = False
3313 from IPython.config import default
3308 from IPython.config import default
3314 config_dir = os.path.split(default.__file__)[0]
3309 config_dir = os.path.split(default.__file__)[0]
3315 ipython_dir = self.ipython_dir
3310 ipython_dir = self.ipython_dir
3316 default_config_file_name = 'ipython_config.py'
3311 default_config_file_name = 'ipython_config.py'
3317 src = os.path.join(config_dir, default_config_file_name)
3312 src = os.path.join(config_dir, default_config_file_name)
3318 dst = os.path.join(ipython_dir, default_config_file_name)
3313 dst = os.path.join(ipython_dir, default_config_file_name)
3319 if (not os.path.isfile(dst)) or overwrite:
3314 if (not os.path.isfile(dst)) or overwrite:
3320 shutil.copy(src, dst)
3315 shutil.copy(src, dst)
3321 print "Installing default config file: %s" % dst
3316 print "Installing default config file: %s" % dst
3322
3317
3323 # Pylab support: simple wrappers that activate pylab, load gui input
3318 # Pylab support: simple wrappers that activate pylab, load gui input
3324 # handling and modify slightly %run
3319 # handling and modify slightly %run
3325
3320
3326 @testdec.skip_doctest
3321 @testdec.skip_doctest
3327 def _pylab_magic_run(self, parameter_s=''):
3322 def _pylab_magic_run(self, parameter_s=''):
3328 Magic.magic_run(self, parameter_s,
3323 Magic.magic_run(self, parameter_s,
3329 runner=mpl_runner(self.shell.safe_execfile))
3324 runner=mpl_runner(self.shell.safe_execfile))
3330
3325
3331 _pylab_magic_run.__doc__ = magic_run.__doc__
3326 _pylab_magic_run.__doc__ = magic_run.__doc__
3332
3327
3333 @testdec.skip_doctest
3328 @testdec.skip_doctest
3334 def magic_pylab(self, s):
3329 def magic_pylab(self, s):
3335 """Load numpy and matplotlib to work interactively.
3330 """Load numpy and matplotlib to work interactively.
3336
3331
3337 %pylab [GUINAME]
3332 %pylab [GUINAME]
3338
3333
3339 This function lets you activate pylab (matplotlib, numpy and
3334 This function lets you activate pylab (matplotlib, numpy and
3340 interactive support) at any point during an IPython session.
3335 interactive support) at any point during an IPython session.
3341
3336
3342 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3337 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3343 pylab and mlab, as well as all names from numpy and pylab.
3338 pylab and mlab, as well as all names from numpy and pylab.
3344
3339
3345 Parameters
3340 Parameters
3346 ----------
3341 ----------
3347 guiname : optional
3342 guiname : optional
3348 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3343 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3349 'tk'). If given, the corresponding Matplotlib backend is used,
3344 'tk'). If given, the corresponding Matplotlib backend is used,
3350 otherwise matplotlib's default (which you can override in your
3345 otherwise matplotlib's default (which you can override in your
3351 matplotlib config file) is used.
3346 matplotlib config file) is used.
3352
3347
3353 Examples
3348 Examples
3354 --------
3349 --------
3355 In this case, where the MPL default is TkAgg:
3350 In this case, where the MPL default is TkAgg:
3356 In [2]: %pylab
3351 In [2]: %pylab
3357
3352
3358 Welcome to pylab, a matplotlib-based Python environment.
3353 Welcome to pylab, a matplotlib-based Python environment.
3359 Backend in use: TkAgg
3354 Backend in use: TkAgg
3360 For more information, type 'help(pylab)'.
3355 For more information, type 'help(pylab)'.
3361
3356
3362 But you can explicitly request a different backend:
3357 But you can explicitly request a different backend:
3363 In [3]: %pylab qt
3358 In [3]: %pylab qt
3364
3359
3365 Welcome to pylab, a matplotlib-based Python environment.
3360 Welcome to pylab, a matplotlib-based Python environment.
3366 Backend in use: Qt4Agg
3361 Backend in use: Qt4Agg
3367 For more information, type 'help(pylab)'.
3362 For more information, type 'help(pylab)'.
3368 """
3363 """
3369 self.shell.enable_pylab(s)
3364 self.shell.enable_pylab(s)
3370
3365
3371 def magic_tb(self, s):
3366 def magic_tb(self, s):
3372 """Print the last traceback with the currently active exception mode.
3367 """Print the last traceback with the currently active exception mode.
3373
3368
3374 See %xmode for changing exception reporting modes."""
3369 See %xmode for changing exception reporting modes."""
3375 self.shell.showtraceback()
3370 self.shell.showtraceback()
3376
3371
3377 # end Magic
3372 # end Magic
@@ -1,489 +1,535 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22
22
23 # Our own
23 # Our own
24 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
25 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
26 )
26 )
27 from IPython.core import page
27 from IPython.core.displayhook import DisplayHook
28 from IPython.core.displayhook import DisplayHook
28 from IPython.core.macro import Macro
29 from IPython.core.macro import Macro
29 from IPython.core.payloadpage import install_payload_page
30 from IPython.core.payloadpage import install_payload_page
30 from IPython.utils import io
31 from IPython.utils import io
31 from IPython.utils.path import get_py_filename
32 from IPython.utils.path import get_py_filename
32 from IPython.utils.text import StringTypes
33 from IPython.utils.text import StringTypes
33 from IPython.utils.traitlets import Instance, Type, Dict
34 from IPython.utils.traitlets import Instance, Type, Dict
34 from IPython.utils.warn import warn
35 from IPython.utils.warn import warn
35 from IPython.zmq.session import extract_header
36 from IPython.zmq.session import extract_header
36 from session import Session
37 from session import Session
37
38
38 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
39 # Globals and side-effects
40 # Globals and side-effects
40 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
41
42
42 # Install the payload version of page.
43 # Install the payload version of page.
43 install_payload_page()
44 install_payload_page()
44
45
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46 # Functions and classes
47 # Functions and classes
47 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
48
49
49 class ZMQDisplayHook(DisplayHook):
50 class ZMQDisplayHook(DisplayHook):
50
51
51 session = Instance(Session)
52 session = Instance(Session)
52 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 parent_header = Dict({})
54 parent_header = Dict({})
54
55
55 def set_parent(self, parent):
56 def set_parent(self, parent):
56 """Set the parent for outbound messages."""
57 """Set the parent for outbound messages."""
57 self.parent_header = extract_header(parent)
58 self.parent_header = extract_header(parent)
58
59
59 def start_displayhook(self):
60 def start_displayhook(self):
60 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
61 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
61
62
62 def write_output_prompt(self):
63 def write_output_prompt(self):
63 """Write the output prompt."""
64 """Write the output prompt."""
64 if self.do_full_cache:
65 if self.do_full_cache:
65 self.msg['content']['execution_count'] = self.prompt_count
66 self.msg['content']['execution_count'] = self.prompt_count
66
67
67 def write_result_repr(self, result_repr):
68 def write_result_repr(self, result_repr):
68 self.msg['content']['data'] = result_repr
69 self.msg['content']['data'] = result_repr
69
70
70 def finish_displayhook(self):
71 def finish_displayhook(self):
71 """Finish up all displayhook activities."""
72 """Finish up all displayhook activities."""
72 self.pub_socket.send_json(self.msg)
73 self.pub_socket.send_json(self.msg)
73 self.msg = None
74 self.msg = None
74
75
75
76
76 class ZMQInteractiveShell(InteractiveShell):
77 class ZMQInteractiveShell(InteractiveShell):
77 """A subclass of InteractiveShell for ZMQ."""
78 """A subclass of InteractiveShell for ZMQ."""
78
79
79 displayhook_class = Type(ZMQDisplayHook)
80 displayhook_class = Type(ZMQDisplayHook)
80
81
82 def init_environment(self):
83 """Configure the user's environment.
84
85 """
86 env = os.environ
87 # These two ensure 'ls' produces nice coloring on BSD-derived systems
88 env['TERM'] = 'xterm-color'
89 env['CLICOLOR'] = '1'
90 # Since normal pagers don't work at all (over pexpect we don't have
91 # single-key control of the subprocess), try to disable paging in
92 # subprocesses as much as possible.
93 env['PAGER'] = 'cat'
94 env['GIT_PAGER'] = 'cat'
81
95
82 def auto_rewrite_input(self, cmd):
96 def auto_rewrite_input(self, cmd):
83 """Called to show the auto-rewritten input for autocall and friends.
97 """Called to show the auto-rewritten input for autocall and friends.
84
98
85 FIXME: this payload is currently not correctly processed by the
99 FIXME: this payload is currently not correctly processed by the
86 frontend.
100 frontend.
87 """
101 """
88 new = self.displayhook.prompt1.auto_rewrite() + cmd
102 new = self.displayhook.prompt1.auto_rewrite() + cmd
89 payload = dict(
103 payload = dict(
90 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
104 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
91 transformed_input=new,
105 transformed_input=new,
92 )
106 )
93 self.payload_manager.write_payload(payload)
107 self.payload_manager.write_payload(payload)
94
108
95 def ask_exit(self):
109 def ask_exit(self):
96 """Engage the exit actions."""
110 """Engage the exit actions."""
97 payload = dict(
111 payload = dict(
98 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
112 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
99 exit=True,
113 exit=True,
100 )
114 )
101 self.payload_manager.write_payload(payload)
115 self.payload_manager.write_payload(payload)
102
116
103 def _showtraceback(self, etype, evalue, stb):
117 def _showtraceback(self, etype, evalue, stb):
104
118
105 exc_content = {
119 exc_content = {
106 u'traceback' : stb,
120 u'traceback' : stb,
107 u'ename' : unicode(etype.__name__),
121 u'ename' : unicode(etype.__name__),
108 u'evalue' : unicode(evalue)
122 u'evalue' : unicode(evalue)
109 }
123 }
110
124
111 dh = self.displayhook
125 dh = self.displayhook
112 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
126 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
113 # Send exception info over pub socket for other clients than the caller
127 # Send exception info over pub socket for other clients than the caller
114 # to pick up
128 # to pick up
115 dh.pub_socket.send_json(exc_msg)
129 dh.pub_socket.send_json(exc_msg)
116
130
117 # FIXME - Hack: store exception info in shell object. Right now, the
131 # FIXME - Hack: store exception info in shell object. Right now, the
118 # caller is reading this info after the fact, we need to fix this logic
132 # caller is reading this info after the fact, we need to fix this logic
119 # to remove this hack. Even uglier, we need to store the error status
133 # to remove this hack. Even uglier, we need to store the error status
120 # here, because in the main loop, the logic that sets it is being
134 # here, because in the main loop, the logic that sets it is being
121 # skipped because runlines swallows the exceptions.
135 # skipped because runlines swallows the exceptions.
122 exc_content[u'status'] = u'error'
136 exc_content[u'status'] = u'error'
123 self._reply_content = exc_content
137 self._reply_content = exc_content
124 # /FIXME
138 # /FIXME
125
139
126 return exc_content
140 return exc_content
127
141
128 #------------------------------------------------------------------------
142 #------------------------------------------------------------------------
129 # Magic overrides
143 # Magic overrides
130 #------------------------------------------------------------------------
144 #------------------------------------------------------------------------
131 # Once the base class stops inheriting from magic, this code needs to be
145 # Once the base class stops inheriting from magic, this code needs to be
132 # moved into a separate machinery as well. For now, at least isolate here
146 # moved into a separate machinery as well. For now, at least isolate here
133 # the magics which this class needs to implement differently from the base
147 # the magics which this class needs to implement differently from the base
134 # class, or that are unique to it.
148 # class, or that are unique to it.
135
149
136 def magic_doctest_mode(self,parameter_s=''):
150 def magic_doctest_mode(self,parameter_s=''):
137 """Toggle doctest mode on and off.
151 """Toggle doctest mode on and off.
138
152
139 This mode is intended to make IPython behave as much as possible like a
153 This mode is intended to make IPython behave as much as possible like a
140 plain Python shell, from the perspective of how its prompts, exceptions
154 plain Python shell, from the perspective of how its prompts, exceptions
141 and output look. This makes it easy to copy and paste parts of a
155 and output look. This makes it easy to copy and paste parts of a
142 session into doctests. It does so by:
156 session into doctests. It does so by:
143
157
144 - Changing the prompts to the classic ``>>>`` ones.
158 - Changing the prompts to the classic ``>>>`` ones.
145 - Changing the exception reporting mode to 'Plain'.
159 - Changing the exception reporting mode to 'Plain'.
146 - Disabling pretty-printing of output.
160 - Disabling pretty-printing of output.
147
161
148 Note that IPython also supports the pasting of code snippets that have
162 Note that IPython also supports the pasting of code snippets that have
149 leading '>>>' and '...' prompts in them. This means that you can paste
163 leading '>>>' and '...' prompts in them. This means that you can paste
150 doctests from files or docstrings (even if they have leading
164 doctests from files or docstrings (even if they have leading
151 whitespace), and the code will execute correctly. You can then use
165 whitespace), and the code will execute correctly. You can then use
152 '%history -t' to see the translated history; this will give you the
166 '%history -t' to see the translated history; this will give you the
153 input after removal of all the leading prompts and whitespace, which
167 input after removal of all the leading prompts and whitespace, which
154 can be pasted back into an editor.
168 can be pasted back into an editor.
155
169
156 With these features, you can switch into this mode easily whenever you
170 With these features, you can switch into this mode easily whenever you
157 need to do testing and changes to doctests, without having to leave
171 need to do testing and changes to doctests, without having to leave
158 your existing IPython session.
172 your existing IPython session.
159 """
173 """
160
174
161 from IPython.utils.ipstruct import Struct
175 from IPython.utils.ipstruct import Struct
162
176
163 # Shorthands
177 # Shorthands
164 shell = self.shell
178 shell = self.shell
165 # dstore is a data store kept in the instance metadata bag to track any
179 # dstore is a data store kept in the instance metadata bag to track any
166 # changes we make, so we can undo them later.
180 # changes we make, so we can undo them later.
167 dstore = shell.meta.setdefault('doctest_mode', Struct())
181 dstore = shell.meta.setdefault('doctest_mode', Struct())
168 save_dstore = dstore.setdefault
182 save_dstore = dstore.setdefault
169
183
170 # save a few values we'll need to recover later
184 # save a few values we'll need to recover later
171 mode = save_dstore('mode', False)
185 mode = save_dstore('mode', False)
172 save_dstore('rc_pprint', shell.pprint)
186 save_dstore('rc_pprint', shell.pprint)
173 save_dstore('xmode', shell.InteractiveTB.mode)
187 save_dstore('xmode', shell.InteractiveTB.mode)
174
188
175 if mode == False:
189 if mode == False:
176 # turn on
190 # turn on
177 shell.pprint = False
191 shell.pprint = False
178 shell.magic_xmode('Plain')
192 shell.magic_xmode('Plain')
179 else:
193 else:
180 # turn off
194 # turn off
181 shell.pprint = dstore.rc_pprint
195 shell.pprint = dstore.rc_pprint
182 shell.magic_xmode(dstore.xmode)
196 shell.magic_xmode(dstore.xmode)
183
197
184 # Store new mode and inform on console
198 # Store new mode and inform on console
185 dstore.mode = bool(1-int(mode))
199 dstore.mode = bool(1-int(mode))
186 mode_label = ['OFF','ON'][dstore.mode]
200 mode_label = ['OFF','ON'][dstore.mode]
187 print('Doctest mode is:', mode_label)
201 print('Doctest mode is:', mode_label)
188
202
189 # Send the payload back so that clients can modify their prompt display
203 # Send the payload back so that clients can modify their prompt display
190 payload = dict(
204 payload = dict(
191 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
205 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
192 mode=dstore.mode)
206 mode=dstore.mode)
193 self.payload_manager.write_payload(payload)
207 self.payload_manager.write_payload(payload)
194
208
195 def magic_edit(self,parameter_s='',last_call=['','']):
209 def magic_edit(self,parameter_s='',last_call=['','']):
196 """Bring up an editor and execute the resulting code.
210 """Bring up an editor and execute the resulting code.
197
211
198 Usage:
212 Usage:
199 %edit [options] [args]
213 %edit [options] [args]
200
214
201 %edit runs IPython's editor hook. The default version of this hook is
215 %edit runs IPython's editor hook. The default version of this hook is
202 set to call the __IPYTHON__.rc.editor command. This is read from your
216 set to call the __IPYTHON__.rc.editor command. This is read from your
203 environment variable $EDITOR. If this isn't found, it will default to
217 environment variable $EDITOR. If this isn't found, it will default to
204 vi under Linux/Unix and to notepad under Windows. See the end of this
218 vi under Linux/Unix and to notepad under Windows. See the end of this
205 docstring for how to change the editor hook.
219 docstring for how to change the editor hook.
206
220
207 You can also set the value of this editor via the command line option
221 You can also set the value of this editor via the command line option
208 '-editor' or in your ipythonrc file. This is useful if you wish to use
222 '-editor' or in your ipythonrc file. This is useful if you wish to use
209 specifically for IPython an editor different from your typical default
223 specifically for IPython an editor different from your typical default
210 (and for Windows users who typically don't set environment variables).
224 (and for Windows users who typically don't set environment variables).
211
225
212 This command allows you to conveniently edit multi-line code right in
226 This command allows you to conveniently edit multi-line code right in
213 your IPython session.
227 your IPython session.
214
228
215 If called without arguments, %edit opens up an empty editor with a
229 If called without arguments, %edit opens up an empty editor with a
216 temporary file and will execute the contents of this file when you
230 temporary file and will execute the contents of this file when you
217 close it (don't forget to save it!).
231 close it (don't forget to save it!).
218
232
219
233
220 Options:
234 Options:
221
235
222 -n <number>: open the editor at a specified line number. By default,
236 -n <number>: open the editor at a specified line number. By default,
223 the IPython editor hook uses the unix syntax 'editor +N filename', but
237 the IPython editor hook uses the unix syntax 'editor +N filename', but
224 you can configure this by providing your own modified hook if your
238 you can configure this by providing your own modified hook if your
225 favorite editor supports line-number specifications with a different
239 favorite editor supports line-number specifications with a different
226 syntax.
240 syntax.
227
241
228 -p: this will call the editor with the same data as the previous time
242 -p: this will call the editor with the same data as the previous time
229 it was used, regardless of how long ago (in your current session) it
243 it was used, regardless of how long ago (in your current session) it
230 was.
244 was.
231
245
232 -r: use 'raw' input. This option only applies to input taken from the
246 -r: use 'raw' input. This option only applies to input taken from the
233 user's history. By default, the 'processed' history is used, so that
247 user's history. By default, the 'processed' history is used, so that
234 magics are loaded in their transformed version to valid Python. If
248 magics are loaded in their transformed version to valid Python. If
235 this option is given, the raw input as typed as the command line is
249 this option is given, the raw input as typed as the command line is
236 used instead. When you exit the editor, it will be executed by
250 used instead. When you exit the editor, it will be executed by
237 IPython's own processor.
251 IPython's own processor.
238
252
239 -x: do not execute the edited code immediately upon exit. This is
253 -x: do not execute the edited code immediately upon exit. This is
240 mainly useful if you are editing programs which need to be called with
254 mainly useful if you are editing programs which need to be called with
241 command line arguments, which you can then do using %run.
255 command line arguments, which you can then do using %run.
242
256
243
257
244 Arguments:
258 Arguments:
245
259
246 If arguments are given, the following possibilites exist:
260 If arguments are given, the following possibilites exist:
247
261
248 - The arguments are numbers or pairs of colon-separated numbers (like
262 - The arguments are numbers or pairs of colon-separated numbers (like
249 1 4:8 9). These are interpreted as lines of previous input to be
263 1 4:8 9). These are interpreted as lines of previous input to be
250 loaded into the editor. The syntax is the same of the %macro command.
264 loaded into the editor. The syntax is the same of the %macro command.
251
265
252 - If the argument doesn't start with a number, it is evaluated as a
266 - If the argument doesn't start with a number, it is evaluated as a
253 variable and its contents loaded into the editor. You can thus edit
267 variable and its contents loaded into the editor. You can thus edit
254 any string which contains python code (including the result of
268 any string which contains python code (including the result of
255 previous edits).
269 previous edits).
256
270
257 - If the argument is the name of an object (other than a string),
271 - If the argument is the name of an object (other than a string),
258 IPython will try to locate the file where it was defined and open the
272 IPython will try to locate the file where it was defined and open the
259 editor at the point where it is defined. You can use `%edit function`
273 editor at the point where it is defined. You can use `%edit function`
260 to load an editor exactly at the point where 'function' is defined,
274 to load an editor exactly at the point where 'function' is defined,
261 edit it and have the file be executed automatically.
275 edit it and have the file be executed automatically.
262
276
263 If the object is a macro (see %macro for details), this opens up your
277 If the object is a macro (see %macro for details), this opens up your
264 specified editor with a temporary file containing the macro's data.
278 specified editor with a temporary file containing the macro's data.
265 Upon exit, the macro is reloaded with the contents of the file.
279 Upon exit, the macro is reloaded with the contents of the file.
266
280
267 Note: opening at an exact line is only supported under Unix, and some
281 Note: opening at an exact line is only supported under Unix, and some
268 editors (like kedit and gedit up to Gnome 2.8) do not understand the
282 editors (like kedit and gedit up to Gnome 2.8) do not understand the
269 '+NUMBER' parameter necessary for this feature. Good editors like
283 '+NUMBER' parameter necessary for this feature. Good editors like
270 (X)Emacs, vi, jed, pico and joe all do.
284 (X)Emacs, vi, jed, pico and joe all do.
271
285
272 - If the argument is not found as a variable, IPython will look for a
286 - If the argument is not found as a variable, IPython will look for a
273 file with that name (adding .py if necessary) and load it into the
287 file with that name (adding .py if necessary) and load it into the
274 editor. It will execute its contents with execfile() when you exit,
288 editor. It will execute its contents with execfile() when you exit,
275 loading any code in the file into your interactive namespace.
289 loading any code in the file into your interactive namespace.
276
290
277 After executing your code, %edit will return as output the code you
291 After executing your code, %edit will return as output the code you
278 typed in the editor (except when it was an existing file). This way
292 typed in the editor (except when it was an existing file). This way
279 you can reload the code in further invocations of %edit as a variable,
293 you can reload the code in further invocations of %edit as a variable,
280 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
294 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
281 the output.
295 the output.
282
296
283 Note that %edit is also available through the alias %ed.
297 Note that %edit is also available through the alias %ed.
284
298
285 This is an example of creating a simple function inside the editor and
299 This is an example of creating a simple function inside the editor and
286 then modifying it. First, start up the editor:
300 then modifying it. First, start up the editor:
287
301
288 In [1]: ed
302 In [1]: ed
289 Editing... done. Executing edited code...
303 Editing... done. Executing edited code...
290 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
304 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
291
305
292 We can then call the function foo():
306 We can then call the function foo():
293
307
294 In [2]: foo()
308 In [2]: foo()
295 foo() was defined in an editing session
309 foo() was defined in an editing session
296
310
297 Now we edit foo. IPython automatically loads the editor with the
311 Now we edit foo. IPython automatically loads the editor with the
298 (temporary) file where foo() was previously defined:
312 (temporary) file where foo() was previously defined:
299
313
300 In [3]: ed foo
314 In [3]: ed foo
301 Editing... done. Executing edited code...
315 Editing... done. Executing edited code...
302
316
303 And if we call foo() again we get the modified version:
317 And if we call foo() again we get the modified version:
304
318
305 In [4]: foo()
319 In [4]: foo()
306 foo() has now been changed!
320 foo() has now been changed!
307
321
308 Here is an example of how to edit a code snippet successive
322 Here is an example of how to edit a code snippet successive
309 times. First we call the editor:
323 times. First we call the editor:
310
324
311 In [5]: ed
325 In [5]: ed
312 Editing... done. Executing edited code...
326 Editing... done. Executing edited code...
313 hello
327 hello
314 Out[5]: "print 'hello'n"
328 Out[5]: "print 'hello'n"
315
329
316 Now we call it again with the previous output (stored in _):
330 Now we call it again with the previous output (stored in _):
317
331
318 In [6]: ed _
332 In [6]: ed _
319 Editing... done. Executing edited code...
333 Editing... done. Executing edited code...
320 hello world
334 hello world
321 Out[6]: "print 'hello world'n"
335 Out[6]: "print 'hello world'n"
322
336
323 Now we call it with the output #8 (stored in _8, also as Out[8]):
337 Now we call it with the output #8 (stored in _8, also as Out[8]):
324
338
325 In [7]: ed _8
339 In [7]: ed _8
326 Editing... done. Executing edited code...
340 Editing... done. Executing edited code...
327 hello again
341 hello again
328 Out[7]: "print 'hello again'n"
342 Out[7]: "print 'hello again'n"
329
343
330
344
331 Changing the default editor hook:
345 Changing the default editor hook:
332
346
333 If you wish to write your own editor hook, you can put it in a
347 If you wish to write your own editor hook, you can put it in a
334 configuration file which you load at startup time. The default hook
348 configuration file which you load at startup time. The default hook
335 is defined in the IPython.core.hooks module, and you can use that as a
349 is defined in the IPython.core.hooks module, and you can use that as a
336 starting example for further modifications. That file also has
350 starting example for further modifications. That file also has
337 general instructions on how to set a new hook for use once you've
351 general instructions on how to set a new hook for use once you've
338 defined it."""
352 defined it."""
339
353
340 # FIXME: This function has become a convoluted mess. It needs a
354 # FIXME: This function has become a convoluted mess. It needs a
341 # ground-up rewrite with clean, simple logic.
355 # ground-up rewrite with clean, simple logic.
342
356
343 def make_filename(arg):
357 def make_filename(arg):
344 "Make a filename from the given args"
358 "Make a filename from the given args"
345 try:
359 try:
346 filename = get_py_filename(arg)
360 filename = get_py_filename(arg)
347 except IOError:
361 except IOError:
348 if args.endswith('.py'):
362 if args.endswith('.py'):
349 filename = arg
363 filename = arg
350 else:
364 else:
351 filename = None
365 filename = None
352 return filename
366 return filename
353
367
354 # custom exceptions
368 # custom exceptions
355 class DataIsObject(Exception): pass
369 class DataIsObject(Exception): pass
356
370
357 opts,args = self.parse_options(parameter_s,'prn:')
371 opts,args = self.parse_options(parameter_s,'prn:')
358 # Set a few locals from the options for convenience:
372 # Set a few locals from the options for convenience:
359 opts_p = opts.has_key('p')
373 opts_p = opts.has_key('p')
360 opts_r = opts.has_key('r')
374 opts_r = opts.has_key('r')
361
375
362 # Default line number value
376 # Default line number value
363 lineno = opts.get('n',None)
377 lineno = opts.get('n',None)
364 if lineno is not None:
378 if lineno is not None:
365 try:
379 try:
366 lineno = int(lineno)
380 lineno = int(lineno)
367 except:
381 except:
368 warn("The -n argument must be an integer.")
382 warn("The -n argument must be an integer.")
369 return
383 return
370
384
371 if opts_p:
385 if opts_p:
372 args = '_%s' % last_call[0]
386 args = '_%s' % last_call[0]
373 if not self.shell.user_ns.has_key(args):
387 if not self.shell.user_ns.has_key(args):
374 args = last_call[1]
388 args = last_call[1]
375
389
376 # use last_call to remember the state of the previous call, but don't
390 # use last_call to remember the state of the previous call, but don't
377 # let it be clobbered by successive '-p' calls.
391 # let it be clobbered by successive '-p' calls.
378 try:
392 try:
379 last_call[0] = self.shell.displayhook.prompt_count
393 last_call[0] = self.shell.displayhook.prompt_count
380 if not opts_p:
394 if not opts_p:
381 last_call[1] = parameter_s
395 last_call[1] = parameter_s
382 except:
396 except:
383 pass
397 pass
384
398
385 # by default this is done with temp files, except when the given
399 # by default this is done with temp files, except when the given
386 # arg is a filename
400 # arg is a filename
387 use_temp = 1
401 use_temp = 1
388
402
389 if re.match(r'\d',args):
403 if re.match(r'\d',args):
390 # Mode where user specifies ranges of lines, like in %macro.
404 # Mode where user specifies ranges of lines, like in %macro.
391 # This means that you can't edit files whose names begin with
405 # This means that you can't edit files whose names begin with
392 # numbers this way. Tough.
406 # numbers this way. Tough.
393 ranges = args.split()
407 ranges = args.split()
394 data = ''.join(self.extract_input_slices(ranges,opts_r))
408 data = ''.join(self.extract_input_slices(ranges,opts_r))
395 elif args.endswith('.py'):
409 elif args.endswith('.py'):
396 filename = make_filename(args)
410 filename = make_filename(args)
397 data = ''
411 data = ''
398 use_temp = 0
412 use_temp = 0
399 elif args:
413 elif args:
400 try:
414 try:
401 # Load the parameter given as a variable. If not a string,
415 # Load the parameter given as a variable. If not a string,
402 # process it as an object instead (below)
416 # process it as an object instead (below)
403
417
404 #print '*** args',args,'type',type(args) # dbg
418 #print '*** args',args,'type',type(args) # dbg
405 data = eval(args,self.shell.user_ns)
419 data = eval(args,self.shell.user_ns)
406 if not type(data) in StringTypes:
420 if not type(data) in StringTypes:
407 raise DataIsObject
421 raise DataIsObject
408
422
409 except (NameError,SyntaxError):
423 except (NameError,SyntaxError):
410 # given argument is not a variable, try as a filename
424 # given argument is not a variable, try as a filename
411 filename = make_filename(args)
425 filename = make_filename(args)
412 if filename is None:
426 if filename is None:
413 warn("Argument given (%s) can't be found as a variable "
427 warn("Argument given (%s) can't be found as a variable "
414 "or as a filename." % args)
428 "or as a filename." % args)
415 return
429 return
416
430
417 data = ''
431 data = ''
418 use_temp = 0
432 use_temp = 0
419 except DataIsObject:
433 except DataIsObject:
420
434
421 # macros have a special edit function
435 # macros have a special edit function
422 if isinstance(data,Macro):
436 if isinstance(data,Macro):
423 self._edit_macro(args,data)
437 self._edit_macro(args,data)
424 return
438 return
425
439
426 # For objects, try to edit the file where they are defined
440 # For objects, try to edit the file where they are defined
427 try:
441 try:
428 filename = inspect.getabsfile(data)
442 filename = inspect.getabsfile(data)
429 if 'fakemodule' in filename.lower() and inspect.isclass(data):
443 if 'fakemodule' in filename.lower() and inspect.isclass(data):
430 # class created by %edit? Try to find source
444 # class created by %edit? Try to find source
431 # by looking for method definitions instead, the
445 # by looking for method definitions instead, the
432 # __module__ in those classes is FakeModule.
446 # __module__ in those classes is FakeModule.
433 attrs = [getattr(data, aname) for aname in dir(data)]
447 attrs = [getattr(data, aname) for aname in dir(data)]
434 for attr in attrs:
448 for attr in attrs:
435 if not inspect.ismethod(attr):
449 if not inspect.ismethod(attr):
436 continue
450 continue
437 filename = inspect.getabsfile(attr)
451 filename = inspect.getabsfile(attr)
438 if filename and 'fakemodule' not in filename.lower():
452 if filename and 'fakemodule' not in filename.lower():
439 # change the attribute to be the edit target instead
453 # change the attribute to be the edit target instead
440 data = attr
454 data = attr
441 break
455 break
442
456
443 datafile = 1
457 datafile = 1
444 except TypeError:
458 except TypeError:
445 filename = make_filename(args)
459 filename = make_filename(args)
446 datafile = 1
460 datafile = 1
447 warn('Could not find file where `%s` is defined.\n'
461 warn('Could not find file where `%s` is defined.\n'
448 'Opening a file named `%s`' % (args,filename))
462 'Opening a file named `%s`' % (args,filename))
449 # Now, make sure we can actually read the source (if it was in
463 # Now, make sure we can actually read the source (if it was in
450 # a temp file it's gone by now).
464 # a temp file it's gone by now).
451 if datafile:
465 if datafile:
452 try:
466 try:
453 if lineno is None:
467 if lineno is None:
454 lineno = inspect.getsourcelines(data)[1]
468 lineno = inspect.getsourcelines(data)[1]
455 except IOError:
469 except IOError:
456 filename = make_filename(args)
470 filename = make_filename(args)
457 if filename is None:
471 if filename is None:
458 warn('The file `%s` where `%s` was defined cannot '
472 warn('The file `%s` where `%s` was defined cannot '
459 'be read.' % (filename,data))
473 'be read.' % (filename,data))
460 return
474 return
461 use_temp = 0
475 use_temp = 0
462 else:
476 else:
463 data = ''
477 data = ''
464
478
465 if use_temp:
479 if use_temp:
466 filename = self.shell.mktempfile(data)
480 filename = self.shell.mktempfile(data)
467 print('IPython will make a temporary file named:', filename)
481 print('IPython will make a temporary file named:', filename)
468
482
469 # Make sure we send to the client an absolute path, in case the working
483 # Make sure we send to the client an absolute path, in case the working
470 # directory of client and kernel don't match
484 # directory of client and kernel don't match
471 filename = os.path.abspath(filename)
485 filename = os.path.abspath(filename)
472
486
473 payload = {
487 payload = {
474 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
488 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
475 'filename' : filename,
489 'filename' : filename,
476 'line_number' : lineno
490 'line_number' : lineno
477 }
491 }
478 self.payload_manager.write_payload(payload)
492 self.payload_manager.write_payload(payload)
479
493
480 def magic_gui(self, *args, **kwargs):
494 def magic_gui(self, *args, **kwargs):
481 raise NotImplementedError(
495 raise NotImplementedError(
482 'GUI support must be enabled in command line options.')
496 'GUI support must be enabled in command line options.')
483
497
484 def magic_pylab(self, *args, **kwargs):
498 def magic_pylab(self, *args, **kwargs):
485 raise NotImplementedError(
499 raise NotImplementedError(
486 'pylab support must be enabled in command line options.')
500 'pylab support must be enabled in command line options.')
487
501
502 # A few magics that are adapted to the specifics of using pexpect and a
503 # remote terminal
504
505 def magic_clear(self, arg_s):
506 """Clear the terminal."""
507 if os.name == 'posix':
508 self.shell.system("clear")
509 else:
510 self.shell.system("cls")
511
512 if os.name == 'nt':
513 # This is the usual name in windows
514 magic_cls = magic_clear
515
516 # Terminal pagers won't work over pexpect, but we do have our own pager
517
518 def magic_less(self, arg_s):
519 """Show a file through the pager.
520
521 Files ending in .py are syntax-highlighted."""
522 cont = open(arg_s).read()
523 if arg_s.endswith('.py'):
524 cont = self.shell.pycolorize(cont)
525 page.page(cont)
526
527 magic_more = magic_less
528
529 # Man calls a pager, so we also need to redefine it
530 if os.name == 'posix':
531 def magic_man(self, arg_s):
532 """Find the man page for the given command and display in pager."""
533 page.page(self.shell.getoutput('man %s' % arg_s, split=False))
488
534
489 InteractiveShellABC.register(ZMQInteractiveShell)
535 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now