##// END OF EJS Templates
Merge branch 'xdel' into takluyver-xdel
Thomas Kluyver -
r3916:99799666 merge
parent child Browse files
Show More
@@ -1,2500 +1,2542 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-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import SingletonConfigurable
34 from IPython.config.configurable import SingletonConfigurable
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, AliasError
41 from IPython.core.alias import AliasManager, AliasError
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import TryNext, UsageError
48 from IPython.core.error import TryNext, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import IPythonInputSplitter
53 from IPython.core.inputsplitter import IPythonInputSplitter
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.magic import Magic
56 from IPython.core.magic import Magic
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.plugin import PluginManager
58 from IPython.core.plugin import PluginManager
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.external.Itpl import ItplNS
60 from IPython.external.Itpl import ItplNS
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils.doctestreload import doctest_reload
63 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.io import ask_yes_no, rprint
64 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.ipstruct import Struct
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.strdispatch import StrDispatch
69 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.syspathcontext import prepended_to_syspath
70 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 List, Unicode, Instance, Type)
73 List, Unicode, Instance, Type)
74 from IPython.utils.warn import warn, error, fatal
74 from IPython.utils.warn import warn, error, fatal
75 import IPython.core.hooks
75 import IPython.core.hooks
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Globals
78 # Globals
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # compiled regexps for autoindent management
81 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Utilities
85 # Utilities
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 # store the builtin raw_input globally, and use this always, in case user code
88 # store the builtin raw_input globally, and use this always, in case user code
89 # overwrites it (like wx.py.PyShell does)
89 # overwrites it (like wx.py.PyShell does)
90 raw_input_original = raw_input
90 raw_input_original = raw_input
91
91
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107
107
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 class SpaceInInput(Exception): pass
110 class SpaceInInput(Exception): pass
111
111
112 class Bunch: pass
112 class Bunch: pass
113
113
114
114
115 def get_default_colors():
115 def get_default_colors():
116 if sys.platform=='darwin':
116 if sys.platform=='darwin':
117 return "LightBG"
117 return "LightBG"
118 elif os.name=='nt':
118 elif os.name=='nt':
119 return 'Linux'
119 return 'Linux'
120 else:
120 else:
121 return 'Linux'
121 return 'Linux'
122
122
123
123
124 class SeparateStr(Str):
124 class SeparateStr(Str):
125 """A Str subclass to validate separate_in, separate_out, etc.
125 """A Str subclass to validate separate_in, separate_out, etc.
126
126
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 """
128 """
129
129
130 def validate(self, obj, value):
130 def validate(self, obj, value):
131 if value == '0': value = ''
131 if value == '0': value = ''
132 value = value.replace('\\n','\n')
132 value = value.replace('\\n','\n')
133 return super(SeparateStr, self).validate(obj, value)
133 return super(SeparateStr, self).validate(obj, value)
134
134
135
135
136 class ReadlineNoRecord(object):
136 class ReadlineNoRecord(object):
137 """Context manager to execute some code, then reload readline history
137 """Context manager to execute some code, then reload readline history
138 so that interactive input to the code doesn't appear when pressing up."""
138 so that interactive input to the code doesn't appear when pressing up."""
139 def __init__(self, shell):
139 def __init__(self, shell):
140 self.shell = shell
140 self.shell = shell
141 self._nested_level = 0
141 self._nested_level = 0
142
142
143 def __enter__(self):
143 def __enter__(self):
144 if self._nested_level == 0:
144 if self._nested_level == 0:
145 try:
145 try:
146 self.orig_length = self.current_length()
146 self.orig_length = self.current_length()
147 self.readline_tail = self.get_readline_tail()
147 self.readline_tail = self.get_readline_tail()
148 except (AttributeError, IndexError): # Can fail with pyreadline
148 except (AttributeError, IndexError): # Can fail with pyreadline
149 self.orig_length, self.readline_tail = 999999, []
149 self.orig_length, self.readline_tail = 999999, []
150 self._nested_level += 1
150 self._nested_level += 1
151
151
152 def __exit__(self, type, value, traceback):
152 def __exit__(self, type, value, traceback):
153 self._nested_level -= 1
153 self._nested_level -= 1
154 if self._nested_level == 0:
154 if self._nested_level == 0:
155 # Try clipping the end if it's got longer
155 # Try clipping the end if it's got longer
156 try:
156 try:
157 e = self.current_length() - self.orig_length
157 e = self.current_length() - self.orig_length
158 if e > 0:
158 if e > 0:
159 for _ in range(e):
159 for _ in range(e):
160 self.shell.readline.remove_history_item(self.orig_length)
160 self.shell.readline.remove_history_item(self.orig_length)
161
161
162 # If it still doesn't match, just reload readline history.
162 # If it still doesn't match, just reload readline history.
163 if self.current_length() != self.orig_length \
163 if self.current_length() != self.orig_length \
164 or self.get_readline_tail() != self.readline_tail:
164 or self.get_readline_tail() != self.readline_tail:
165 self.shell.refill_readline_hist()
165 self.shell.refill_readline_hist()
166 except (AttributeError, IndexError):
166 except (AttributeError, IndexError):
167 pass
167 pass
168 # Returning False will cause exceptions to propagate
168 # Returning False will cause exceptions to propagate
169 return False
169 return False
170
170
171 def current_length(self):
171 def current_length(self):
172 return self.shell.readline.get_current_history_length()
172 return self.shell.readline.get_current_history_length()
173
173
174 def get_readline_tail(self, n=10):
174 def get_readline_tail(self, n=10):
175 """Get the last n items in readline history."""
175 """Get the last n items in readline history."""
176 end = self.shell.readline.get_current_history_length() + 1
176 end = self.shell.readline.get_current_history_length() + 1
177 start = max(end-n, 1)
177 start = max(end-n, 1)
178 ghi = self.shell.readline.get_history_item
178 ghi = self.shell.readline.get_history_item
179 return [ghi(x) for x in range(start, end)]
179 return [ghi(x) for x in range(start, end)]
180
180
181
181
182 _autocall_help = """
182 _autocall_help = """
183 Make IPython automatically call any callable object even if
183 Make IPython automatically call any callable object even if
184 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
184 you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 automatically. The value can be '0' to disable the feature, '1' for 'smart'
185 automatically. The value can be '0' to disable the feature, '1' for 'smart'
186 autocall, where it is not applied if there are no more arguments on the line,
186 autocall, where it is not applied if there are no more arguments on the line,
187 and '2' for 'full' autocall, where all callable objects are automatically
187 and '2' for 'full' autocall, where all callable objects are automatically
188 called (even if no arguments are present). The default is '1'.
188 called (even if no arguments are present). The default is '1'.
189 """
189 """
190
190
191 #-----------------------------------------------------------------------------
191 #-----------------------------------------------------------------------------
192 # Main IPython class
192 # Main IPython class
193 #-----------------------------------------------------------------------------
193 #-----------------------------------------------------------------------------
194
194
195 class InteractiveShell(SingletonConfigurable, Magic):
195 class InteractiveShell(SingletonConfigurable, Magic):
196 """An enhanced, interactive shell for Python."""
196 """An enhanced, interactive shell for Python."""
197
197
198 _instance = None
198 _instance = None
199
199
200 autocall = Enum((0,1,2), default_value=1, config=True, help=
200 autocall = Enum((0,1,2), default_value=1, config=True, help=
201 """
201 """
202 Make IPython automatically call any callable object even if you didn't
202 Make IPython automatically call any callable object even if you didn't
203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
203 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
204 automatically. The value can be '0' to disable the feature, '1' for
204 automatically. The value can be '0' to disable the feature, '1' for
205 'smart' autocall, where it is not applied if there are no more
205 'smart' autocall, where it is not applied if there are no more
206 arguments on the line, and '2' for 'full' autocall, where all callable
206 arguments on the line, and '2' for 'full' autocall, where all callable
207 objects are automatically called (even if no arguments are present).
207 objects are automatically called (even if no arguments are present).
208 The default is '1'.
208 The default is '1'.
209 """
209 """
210 )
210 )
211 # TODO: remove all autoindent logic and put into frontends.
211 # TODO: remove all autoindent logic and put into frontends.
212 # We can't do this yet because even runlines uses the autoindent.
212 # We can't do this yet because even runlines uses the autoindent.
213 autoindent = CBool(True, config=True, help=
213 autoindent = CBool(True, config=True, help=
214 """
214 """
215 Autoindent IPython code entered interactively.
215 Autoindent IPython code entered interactively.
216 """
216 """
217 )
217 )
218 automagic = CBool(True, config=True, help=
218 automagic = CBool(True, config=True, help=
219 """
219 """
220 Enable magic commands to be called without the leading %.
220 Enable magic commands to be called without the leading %.
221 """
221 """
222 )
222 )
223 cache_size = Int(1000, config=True, help=
223 cache_size = Int(1000, config=True, help=
224 """
224 """
225 Set the size of the output cache. The default is 1000, you can
225 Set the size of the output cache. The default is 1000, you can
226 change it permanently in your config file. Setting it to 0 completely
226 change it permanently in your config file. Setting it to 0 completely
227 disables the caching system, and the minimum value accepted is 20 (if
227 disables the caching system, and the minimum value accepted is 20 (if
228 you provide a value less than 20, it is reset to 0 and a warning is
228 you provide a value less than 20, it is reset to 0 and a warning is
229 issued). This limit is defined because otherwise you'll spend more
229 issued). This limit is defined because otherwise you'll spend more
230 time re-flushing a too small cache than working
230 time re-flushing a too small cache than working
231 """
231 """
232 )
232 )
233 color_info = CBool(True, config=True, help=
233 color_info = CBool(True, config=True, help=
234 """
234 """
235 Use colors for displaying information about objects. Because this
235 Use colors for displaying information about objects. Because this
236 information is passed through a pager (like 'less'), and some pagers
236 information is passed through a pager (like 'less'), and some pagers
237 get confused with color codes, this capability can be turned off.
237 get confused with color codes, this capability can be turned off.
238 """
238 """
239 )
239 )
240 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
240 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
241 default_value=get_default_colors(), config=True)
241 default_value=get_default_colors(), config=True)
242 debug = CBool(False, config=True)
242 debug = CBool(False, config=True)
243 deep_reload = CBool(False, config=True, help=
243 deep_reload = CBool(False, config=True, help=
244 """
244 """
245 Enable deep (recursive) reloading by default. IPython can use the
245 Enable deep (recursive) reloading by default. IPython can use the
246 deep_reload module which reloads changes in modules recursively (it
246 deep_reload module which reloads changes in modules recursively (it
247 replaces the reload() function, so you don't need to change anything to
247 replaces the reload() function, so you don't need to change anything to
248 use it). deep_reload() forces a full reload of modules whose code may
248 use it). deep_reload() forces a full reload of modules whose code may
249 have changed, which the default reload() function does not. When
249 have changed, which the default reload() function does not. When
250 deep_reload is off, IPython will use the normal reload(), but
250 deep_reload is off, IPython will use the normal reload(), but
251 deep_reload will still be available as dreload().
251 deep_reload will still be available as dreload().
252 """
252 """
253 )
253 )
254 display_formatter = Instance(DisplayFormatter)
254 display_formatter = Instance(DisplayFormatter)
255 displayhook_class = Type(DisplayHook)
255 displayhook_class = Type(DisplayHook)
256 display_pub_class = Type(DisplayPublisher)
256 display_pub_class = Type(DisplayPublisher)
257
257
258 exit_now = CBool(False)
258 exit_now = CBool(False)
259 exiter = Instance(ExitAutocall)
259 exiter = Instance(ExitAutocall)
260 def _exiter_default(self):
260 def _exiter_default(self):
261 return ExitAutocall(self)
261 return ExitAutocall(self)
262 # Monotonically increasing execution counter
262 # Monotonically increasing execution counter
263 execution_count = Int(1)
263 execution_count = Int(1)
264 filename = Unicode("<ipython console>")
264 filename = Unicode("<ipython console>")
265 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
265 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
266
266
267 # Input splitter, to split entire cells of input into either individual
267 # Input splitter, to split entire cells of input into either individual
268 # interactive statements or whole blocks.
268 # interactive statements or whole blocks.
269 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
269 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
270 (), {})
270 (), {})
271 logstart = CBool(False, config=True, help=
271 logstart = CBool(False, config=True, help=
272 """
272 """
273 Start logging to the default log file.
273 Start logging to the default log file.
274 """
274 """
275 )
275 )
276 logfile = Unicode('', config=True, help=
276 logfile = Unicode('', config=True, help=
277 """
277 """
278 The name of the logfile to use.
278 The name of the logfile to use.
279 """
279 """
280 )
280 )
281 logappend = Unicode('', config=True, help=
281 logappend = Unicode('', config=True, help=
282 """
282 """
283 Start logging to the given file in append mode.
283 Start logging to the given file in append mode.
284 """
284 """
285 )
285 )
286 object_info_string_level = Enum((0,1,2), default_value=0,
286 object_info_string_level = Enum((0,1,2), default_value=0,
287 config=True)
287 config=True)
288 pdb = CBool(False, config=True, help=
288 pdb = CBool(False, config=True, help=
289 """
289 """
290 Automatically call the pdb debugger after every exception.
290 Automatically call the pdb debugger after every exception.
291 """
291 """
292 )
292 )
293
293
294 profile = Unicode('', config=True)
294 profile = Unicode('', config=True)
295 prompt_in1 = Str('In [\\#]: ', config=True)
295 prompt_in1 = Str('In [\\#]: ', config=True)
296 prompt_in2 = Str(' .\\D.: ', config=True)
296 prompt_in2 = Str(' .\\D.: ', config=True)
297 prompt_out = Str('Out[\\#]: ', config=True)
297 prompt_out = Str('Out[\\#]: ', config=True)
298 prompts_pad_left = CBool(True, config=True)
298 prompts_pad_left = CBool(True, config=True)
299 quiet = CBool(False, config=True)
299 quiet = CBool(False, config=True)
300
300
301 history_length = Int(10000, config=True)
301 history_length = Int(10000, config=True)
302
302
303 # The readline stuff will eventually be moved to the terminal subclass
303 # The readline stuff will eventually be moved to the terminal subclass
304 # but for now, we can't do that as readline is welded in everywhere.
304 # but for now, we can't do that as readline is welded in everywhere.
305 readline_use = CBool(True, config=True)
305 readline_use = CBool(True, config=True)
306 readline_merge_completions = CBool(True, config=True)
306 readline_merge_completions = CBool(True, config=True)
307 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
307 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
308 readline_remove_delims = Str('-/~', config=True)
308 readline_remove_delims = Str('-/~', config=True)
309 # don't use \M- bindings by default, because they
309 # don't use \M- bindings by default, because they
310 # conflict with 8-bit encodings. See gh-58,gh-88
310 # conflict with 8-bit encodings. See gh-58,gh-88
311 readline_parse_and_bind = List([
311 readline_parse_and_bind = List([
312 'tab: complete',
312 'tab: complete',
313 '"\C-l": clear-screen',
313 '"\C-l": clear-screen',
314 'set show-all-if-ambiguous on',
314 'set show-all-if-ambiguous on',
315 '"\C-o": tab-insert',
315 '"\C-o": tab-insert',
316 '"\C-r": reverse-search-history',
316 '"\C-r": reverse-search-history',
317 '"\C-s": forward-search-history',
317 '"\C-s": forward-search-history',
318 '"\C-p": history-search-backward',
318 '"\C-p": history-search-backward',
319 '"\C-n": history-search-forward',
319 '"\C-n": history-search-forward',
320 '"\e[A": history-search-backward',
320 '"\e[A": history-search-backward',
321 '"\e[B": history-search-forward',
321 '"\e[B": history-search-forward',
322 '"\C-k": kill-line',
322 '"\C-k": kill-line',
323 '"\C-u": unix-line-discard',
323 '"\C-u": unix-line-discard',
324 ], allow_none=False, config=True)
324 ], allow_none=False, config=True)
325
325
326 # TODO: this part of prompt management should be moved to the frontends.
326 # TODO: this part of prompt management should be moved to the frontends.
327 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
327 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
328 separate_in = SeparateStr('\n', config=True)
328 separate_in = SeparateStr('\n', config=True)
329 separate_out = SeparateStr('', config=True)
329 separate_out = SeparateStr('', config=True)
330 separate_out2 = SeparateStr('', config=True)
330 separate_out2 = SeparateStr('', config=True)
331 wildcards_case_sensitive = CBool(True, config=True)
331 wildcards_case_sensitive = CBool(True, config=True)
332 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
332 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
333 default_value='Context', config=True)
333 default_value='Context', config=True)
334
334
335 # Subcomponents of InteractiveShell
335 # Subcomponents of InteractiveShell
336 alias_manager = Instance('IPython.core.alias.AliasManager')
336 alias_manager = Instance('IPython.core.alias.AliasManager')
337 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
337 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
338 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
338 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
339 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
339 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
340 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
340 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
341 plugin_manager = Instance('IPython.core.plugin.PluginManager')
341 plugin_manager = Instance('IPython.core.plugin.PluginManager')
342 payload_manager = Instance('IPython.core.payload.PayloadManager')
342 payload_manager = Instance('IPython.core.payload.PayloadManager')
343 history_manager = Instance('IPython.core.history.HistoryManager')
343 history_manager = Instance('IPython.core.history.HistoryManager')
344
344
345 # Private interface
345 # Private interface
346 _post_execute = Instance(dict)
346 _post_execute = Instance(dict)
347
347
348 def __init__(self, config=None, ipython_dir=None,
348 def __init__(self, config=None, ipython_dir=None,
349 user_ns=None, user_global_ns=None,
349 user_ns=None, user_global_ns=None,
350 custom_exceptions=((), None)):
350 custom_exceptions=((), None)):
351
351
352 # This is where traits with a config_key argument are updated
352 # This is where traits with a config_key argument are updated
353 # from the values on config.
353 # from the values on config.
354 super(InteractiveShell, self).__init__(config=config)
354 super(InteractiveShell, self).__init__(config=config)
355
355
356 # These are relatively independent and stateless
356 # These are relatively independent and stateless
357 self.init_ipython_dir(ipython_dir)
357 self.init_ipython_dir(ipython_dir)
358 self.init_instance_attrs()
358 self.init_instance_attrs()
359 self.init_environment()
359 self.init_environment()
360
360
361 # Create namespaces (user_ns, user_global_ns, etc.)
361 # Create namespaces (user_ns, user_global_ns, etc.)
362 self.init_create_namespaces(user_ns, user_global_ns)
362 self.init_create_namespaces(user_ns, user_global_ns)
363 # This has to be done after init_create_namespaces because it uses
363 # This has to be done after init_create_namespaces because it uses
364 # something in self.user_ns, but before init_sys_modules, which
364 # something in self.user_ns, but before init_sys_modules, which
365 # is the first thing to modify sys.
365 # is the first thing to modify sys.
366 # TODO: When we override sys.stdout and sys.stderr before this class
366 # TODO: When we override sys.stdout and sys.stderr before this class
367 # is created, we are saving the overridden ones here. Not sure if this
367 # is created, we are saving the overridden ones here. Not sure if this
368 # is what we want to do.
368 # is what we want to do.
369 self.save_sys_module_state()
369 self.save_sys_module_state()
370 self.init_sys_modules()
370 self.init_sys_modules()
371
371
372 # While we're trying to have each part of the code directly access what
372 # While we're trying to have each part of the code directly access what
373 # it needs without keeping redundant references to objects, we have too
373 # it needs without keeping redundant references to objects, we have too
374 # much legacy code that expects ip.db to exist.
374 # much legacy code that expects ip.db to exist.
375 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
375 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
376
376
377 self.init_history()
377 self.init_history()
378 self.init_encoding()
378 self.init_encoding()
379 self.init_prefilter()
379 self.init_prefilter()
380
380
381 Magic.__init__(self, self)
381 Magic.__init__(self, self)
382
382
383 self.init_syntax_highlighting()
383 self.init_syntax_highlighting()
384 self.init_hooks()
384 self.init_hooks()
385 self.init_pushd_popd_magic()
385 self.init_pushd_popd_magic()
386 # self.init_traceback_handlers use to be here, but we moved it below
386 # self.init_traceback_handlers use to be here, but we moved it below
387 # because it and init_io have to come after init_readline.
387 # because it and init_io have to come after init_readline.
388 self.init_user_ns()
388 self.init_user_ns()
389 self.init_logger()
389 self.init_logger()
390 self.init_alias()
390 self.init_alias()
391 self.init_builtins()
391 self.init_builtins()
392
392
393 # pre_config_initialization
393 # pre_config_initialization
394
394
395 # The next section should contain everything that was in ipmaker.
395 # The next section should contain everything that was in ipmaker.
396 self.init_logstart()
396 self.init_logstart()
397
397
398 # The following was in post_config_initialization
398 # The following was in post_config_initialization
399 self.init_inspector()
399 self.init_inspector()
400 # init_readline() must come before init_io(), because init_io uses
400 # init_readline() must come before init_io(), because init_io uses
401 # readline related things.
401 # readline related things.
402 self.init_readline()
402 self.init_readline()
403 # init_completer must come after init_readline, because it needs to
403 # init_completer must come after init_readline, because it needs to
404 # know whether readline is present or not system-wide to configure the
404 # know whether readline is present or not system-wide to configure the
405 # completers, since the completion machinery can now operate
405 # completers, since the completion machinery can now operate
406 # independently of readline (e.g. over the network)
406 # independently of readline (e.g. over the network)
407 self.init_completer()
407 self.init_completer()
408 # TODO: init_io() needs to happen before init_traceback handlers
408 # TODO: init_io() needs to happen before init_traceback handlers
409 # because the traceback handlers hardcode the stdout/stderr streams.
409 # because the traceback handlers hardcode the stdout/stderr streams.
410 # This logic in in debugger.Pdb and should eventually be changed.
410 # This logic in in debugger.Pdb and should eventually be changed.
411 self.init_io()
411 self.init_io()
412 self.init_traceback_handlers(custom_exceptions)
412 self.init_traceback_handlers(custom_exceptions)
413 self.init_prompts()
413 self.init_prompts()
414 self.init_display_formatter()
414 self.init_display_formatter()
415 self.init_display_pub()
415 self.init_display_pub()
416 self.init_displayhook()
416 self.init_displayhook()
417 self.init_reload_doctest()
417 self.init_reload_doctest()
418 self.init_magics()
418 self.init_magics()
419 self.init_pdb()
419 self.init_pdb()
420 self.init_extension_manager()
420 self.init_extension_manager()
421 self.init_plugin_manager()
421 self.init_plugin_manager()
422 self.init_payload()
422 self.init_payload()
423 self.hooks.late_startup_hook()
423 self.hooks.late_startup_hook()
424 atexit.register(self.atexit_operations)
424 atexit.register(self.atexit_operations)
425
425
426 def get_ipython(self):
426 def get_ipython(self):
427 """Return the currently running IPython instance."""
427 """Return the currently running IPython instance."""
428 return self
428 return self
429
429
430 #-------------------------------------------------------------------------
430 #-------------------------------------------------------------------------
431 # Trait changed handlers
431 # Trait changed handlers
432 #-------------------------------------------------------------------------
432 #-------------------------------------------------------------------------
433
433
434 def _ipython_dir_changed(self, name, new):
434 def _ipython_dir_changed(self, name, new):
435 if not os.path.isdir(new):
435 if not os.path.isdir(new):
436 os.makedirs(new, mode = 0777)
436 os.makedirs(new, mode = 0777)
437
437
438 def set_autoindent(self,value=None):
438 def set_autoindent(self,value=None):
439 """Set the autoindent flag, checking for readline support.
439 """Set the autoindent flag, checking for readline support.
440
440
441 If called with no arguments, it acts as a toggle."""
441 If called with no arguments, it acts as a toggle."""
442
442
443 if not self.has_readline:
443 if not self.has_readline:
444 if os.name == 'posix':
444 if os.name == 'posix':
445 warn("The auto-indent feature requires the readline library")
445 warn("The auto-indent feature requires the readline library")
446 self.autoindent = 0
446 self.autoindent = 0
447 return
447 return
448 if value is None:
448 if value is None:
449 self.autoindent = not self.autoindent
449 self.autoindent = not self.autoindent
450 else:
450 else:
451 self.autoindent = value
451 self.autoindent = value
452
452
453 #-------------------------------------------------------------------------
453 #-------------------------------------------------------------------------
454 # init_* methods called by __init__
454 # init_* methods called by __init__
455 #-------------------------------------------------------------------------
455 #-------------------------------------------------------------------------
456
456
457 def init_ipython_dir(self, ipython_dir):
457 def init_ipython_dir(self, ipython_dir):
458 if ipython_dir is not None:
458 if ipython_dir is not None:
459 self.ipython_dir = ipython_dir
459 self.ipython_dir = ipython_dir
460 self.config.Global.ipython_dir = self.ipython_dir
460 self.config.Global.ipython_dir = self.ipython_dir
461 return
461 return
462
462
463 if hasattr(self.config.Global, 'ipython_dir'):
463 if hasattr(self.config.Global, 'ipython_dir'):
464 self.ipython_dir = self.config.Global.ipython_dir
464 self.ipython_dir = self.config.Global.ipython_dir
465 else:
465 else:
466 self.ipython_dir = get_ipython_dir()
466 self.ipython_dir = get_ipython_dir()
467
467
468 # All children can just read this
468 # All children can just read this
469 self.config.Global.ipython_dir = self.ipython_dir
469 self.config.Global.ipython_dir = self.ipython_dir
470
470
471 def init_instance_attrs(self):
471 def init_instance_attrs(self):
472 self.more = False
472 self.more = False
473
473
474 # command compiler
474 # command compiler
475 self.compile = CachingCompiler()
475 self.compile = CachingCompiler()
476
476
477 # Make an empty namespace, which extension writers can rely on both
477 # Make an empty namespace, which extension writers can rely on both
478 # existing and NEVER being used by ipython itself. This gives them a
478 # existing and NEVER being used by ipython itself. This gives them a
479 # convenient location for storing additional information and state
479 # convenient location for storing additional information and state
480 # their extensions may require, without fear of collisions with other
480 # their extensions may require, without fear of collisions with other
481 # ipython names that may develop later.
481 # ipython names that may develop later.
482 self.meta = Struct()
482 self.meta = Struct()
483
483
484 # Temporary files used for various purposes. Deleted at exit.
484 # Temporary files used for various purposes. Deleted at exit.
485 self.tempfiles = []
485 self.tempfiles = []
486
486
487 # Keep track of readline usage (later set by init_readline)
487 # Keep track of readline usage (later set by init_readline)
488 self.has_readline = False
488 self.has_readline = False
489
489
490 # keep track of where we started running (mainly for crash post-mortem)
490 # keep track of where we started running (mainly for crash post-mortem)
491 # This is not being used anywhere currently.
491 # This is not being used anywhere currently.
492 self.starting_dir = os.getcwd()
492 self.starting_dir = os.getcwd()
493
493
494 # Indentation management
494 # Indentation management
495 self.indent_current_nsp = 0
495 self.indent_current_nsp = 0
496
496
497 # Dict to track post-execution functions that have been registered
497 # Dict to track post-execution functions that have been registered
498 self._post_execute = {}
498 self._post_execute = {}
499
499
500 def init_environment(self):
500 def init_environment(self):
501 """Any changes we need to make to the user's environment."""
501 """Any changes we need to make to the user's environment."""
502 pass
502 pass
503
503
504 def init_encoding(self):
504 def init_encoding(self):
505 # Get system encoding at startup time. Certain terminals (like Emacs
505 # Get system encoding at startup time. Certain terminals (like Emacs
506 # under Win32 have it set to None, and we need to have a known valid
506 # under Win32 have it set to None, and we need to have a known valid
507 # encoding to use in the raw_input() method
507 # encoding to use in the raw_input() method
508 try:
508 try:
509 self.stdin_encoding = sys.stdin.encoding or 'ascii'
509 self.stdin_encoding = sys.stdin.encoding or 'ascii'
510 except AttributeError:
510 except AttributeError:
511 self.stdin_encoding = 'ascii'
511 self.stdin_encoding = 'ascii'
512
512
513 def init_syntax_highlighting(self):
513 def init_syntax_highlighting(self):
514 # Python source parser/formatter for syntax highlighting
514 # Python source parser/formatter for syntax highlighting
515 pyformat = PyColorize.Parser().format
515 pyformat = PyColorize.Parser().format
516 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
516 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
517
517
518 def init_pushd_popd_magic(self):
518 def init_pushd_popd_magic(self):
519 # for pushd/popd management
519 # for pushd/popd management
520 try:
520 try:
521 self.home_dir = get_home_dir()
521 self.home_dir = get_home_dir()
522 except HomeDirError, msg:
522 except HomeDirError, msg:
523 fatal(msg)
523 fatal(msg)
524
524
525 self.dir_stack = []
525 self.dir_stack = []
526
526
527 def init_logger(self):
527 def init_logger(self):
528 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
528 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
529 logmode='rotate')
529 logmode='rotate')
530
530
531 def init_logstart(self):
531 def init_logstart(self):
532 """Initialize logging in case it was requested at the command line.
532 """Initialize logging in case it was requested at the command line.
533 """
533 """
534 if self.logappend:
534 if self.logappend:
535 self.magic_logstart(self.logappend + ' append')
535 self.magic_logstart(self.logappend + ' append')
536 elif self.logfile:
536 elif self.logfile:
537 self.magic_logstart(self.logfile)
537 self.magic_logstart(self.logfile)
538 elif self.logstart:
538 elif self.logstart:
539 self.magic_logstart()
539 self.magic_logstart()
540
540
541 def init_builtins(self):
541 def init_builtins(self):
542 self.builtin_trap = BuiltinTrap(shell=self)
542 self.builtin_trap = BuiltinTrap(shell=self)
543
543
544 def init_inspector(self):
544 def init_inspector(self):
545 # Object inspector
545 # Object inspector
546 self.inspector = oinspect.Inspector(oinspect.InspectColors,
546 self.inspector = oinspect.Inspector(oinspect.InspectColors,
547 PyColorize.ANSICodeColors,
547 PyColorize.ANSICodeColors,
548 'NoColor',
548 'NoColor',
549 self.object_info_string_level)
549 self.object_info_string_level)
550
550
551 def init_io(self):
551 def init_io(self):
552 # This will just use sys.stdout and sys.stderr. If you want to
552 # This will just use sys.stdout and sys.stderr. If you want to
553 # override sys.stdout and sys.stderr themselves, you need to do that
553 # override sys.stdout and sys.stderr themselves, you need to do that
554 # *before* instantiating this class, because io holds onto
554 # *before* instantiating this class, because io holds onto
555 # references to the underlying streams.
555 # references to the underlying streams.
556 if sys.platform == 'win32' and self.has_readline:
556 if sys.platform == 'win32' and self.has_readline:
557 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
557 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
558 else:
558 else:
559 io.stdout = io.IOStream(sys.stdout)
559 io.stdout = io.IOStream(sys.stdout)
560 io.stderr = io.IOStream(sys.stderr)
560 io.stderr = io.IOStream(sys.stderr)
561
561
562 def init_prompts(self):
562 def init_prompts(self):
563 # TODO: This is a pass for now because the prompts are managed inside
563 # TODO: This is a pass for now because the prompts are managed inside
564 # the DisplayHook. Once there is a separate prompt manager, this
564 # the DisplayHook. Once there is a separate prompt manager, this
565 # will initialize that object and all prompt related information.
565 # will initialize that object and all prompt related information.
566 pass
566 pass
567
567
568 def init_display_formatter(self):
568 def init_display_formatter(self):
569 self.display_formatter = DisplayFormatter(config=self.config)
569 self.display_formatter = DisplayFormatter(config=self.config)
570
570
571 def init_display_pub(self):
571 def init_display_pub(self):
572 self.display_pub = self.display_pub_class(config=self.config)
572 self.display_pub = self.display_pub_class(config=self.config)
573
573
574 def init_displayhook(self):
574 def init_displayhook(self):
575 # Initialize displayhook, set in/out prompts and printing system
575 # Initialize displayhook, set in/out prompts and printing system
576 self.displayhook = self.displayhook_class(
576 self.displayhook = self.displayhook_class(
577 config=self.config,
577 config=self.config,
578 shell=self,
578 shell=self,
579 cache_size=self.cache_size,
579 cache_size=self.cache_size,
580 input_sep = self.separate_in,
580 input_sep = self.separate_in,
581 output_sep = self.separate_out,
581 output_sep = self.separate_out,
582 output_sep2 = self.separate_out2,
582 output_sep2 = self.separate_out2,
583 ps1 = self.prompt_in1,
583 ps1 = self.prompt_in1,
584 ps2 = self.prompt_in2,
584 ps2 = self.prompt_in2,
585 ps_out = self.prompt_out,
585 ps_out = self.prompt_out,
586 pad_left = self.prompts_pad_left
586 pad_left = self.prompts_pad_left
587 )
587 )
588 # This is a context manager that installs/revmoes the displayhook at
588 # This is a context manager that installs/revmoes the displayhook at
589 # the appropriate time.
589 # the appropriate time.
590 self.display_trap = DisplayTrap(hook=self.displayhook)
590 self.display_trap = DisplayTrap(hook=self.displayhook)
591
591
592 def init_reload_doctest(self):
592 def init_reload_doctest(self):
593 # Do a proper resetting of doctest, including the necessary displayhook
593 # Do a proper resetting of doctest, including the necessary displayhook
594 # monkeypatching
594 # monkeypatching
595 try:
595 try:
596 doctest_reload()
596 doctest_reload()
597 except ImportError:
597 except ImportError:
598 warn("doctest module does not exist.")
598 warn("doctest module does not exist.")
599
599
600 #-------------------------------------------------------------------------
600 #-------------------------------------------------------------------------
601 # Things related to injections into the sys module
601 # Things related to injections into the sys module
602 #-------------------------------------------------------------------------
602 #-------------------------------------------------------------------------
603
603
604 def save_sys_module_state(self):
604 def save_sys_module_state(self):
605 """Save the state of hooks in the sys module.
605 """Save the state of hooks in the sys module.
606
606
607 This has to be called after self.user_ns is created.
607 This has to be called after self.user_ns is created.
608 """
608 """
609 self._orig_sys_module_state = {}
609 self._orig_sys_module_state = {}
610 self._orig_sys_module_state['stdin'] = sys.stdin
610 self._orig_sys_module_state['stdin'] = sys.stdin
611 self._orig_sys_module_state['stdout'] = sys.stdout
611 self._orig_sys_module_state['stdout'] = sys.stdout
612 self._orig_sys_module_state['stderr'] = sys.stderr
612 self._orig_sys_module_state['stderr'] = sys.stderr
613 self._orig_sys_module_state['excepthook'] = sys.excepthook
613 self._orig_sys_module_state['excepthook'] = sys.excepthook
614 try:
614 try:
615 self._orig_sys_modules_main_name = self.user_ns['__name__']
615 self._orig_sys_modules_main_name = self.user_ns['__name__']
616 except KeyError:
616 except KeyError:
617 pass
617 pass
618
618
619 def restore_sys_module_state(self):
619 def restore_sys_module_state(self):
620 """Restore the state of the sys module."""
620 """Restore the state of the sys module."""
621 try:
621 try:
622 for k, v in self._orig_sys_module_state.iteritems():
622 for k, v in self._orig_sys_module_state.iteritems():
623 setattr(sys, k, v)
623 setattr(sys, k, v)
624 except AttributeError:
624 except AttributeError:
625 pass
625 pass
626 # Reset what what done in self.init_sys_modules
626 # Reset what what done in self.init_sys_modules
627 try:
627 try:
628 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
628 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
629 except (AttributeError, KeyError):
629 except (AttributeError, KeyError):
630 pass
630 pass
631
631
632 #-------------------------------------------------------------------------
632 #-------------------------------------------------------------------------
633 # Things related to hooks
633 # Things related to hooks
634 #-------------------------------------------------------------------------
634 #-------------------------------------------------------------------------
635
635
636 def init_hooks(self):
636 def init_hooks(self):
637 # hooks holds pointers used for user-side customizations
637 # hooks holds pointers used for user-side customizations
638 self.hooks = Struct()
638 self.hooks = Struct()
639
639
640 self.strdispatchers = {}
640 self.strdispatchers = {}
641
641
642 # Set all default hooks, defined in the IPython.hooks module.
642 # Set all default hooks, defined in the IPython.hooks module.
643 hooks = IPython.core.hooks
643 hooks = IPython.core.hooks
644 for hook_name in hooks.__all__:
644 for hook_name in hooks.__all__:
645 # default hooks have priority 100, i.e. low; user hooks should have
645 # default hooks have priority 100, i.e. low; user hooks should have
646 # 0-100 priority
646 # 0-100 priority
647 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
647 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
648
648
649 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
649 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
650 """set_hook(name,hook) -> sets an internal IPython hook.
650 """set_hook(name,hook) -> sets an internal IPython hook.
651
651
652 IPython exposes some of its internal API as user-modifiable hooks. By
652 IPython exposes some of its internal API as user-modifiable hooks. By
653 adding your function to one of these hooks, you can modify IPython's
653 adding your function to one of these hooks, you can modify IPython's
654 behavior to call at runtime your own routines."""
654 behavior to call at runtime your own routines."""
655
655
656 # At some point in the future, this should validate the hook before it
656 # At some point in the future, this should validate the hook before it
657 # accepts it. Probably at least check that the hook takes the number
657 # accepts it. Probably at least check that the hook takes the number
658 # of args it's supposed to.
658 # of args it's supposed to.
659
659
660 f = types.MethodType(hook,self)
660 f = types.MethodType(hook,self)
661
661
662 # check if the hook is for strdispatcher first
662 # check if the hook is for strdispatcher first
663 if str_key is not None:
663 if str_key is not None:
664 sdp = self.strdispatchers.get(name, StrDispatch())
664 sdp = self.strdispatchers.get(name, StrDispatch())
665 sdp.add_s(str_key, f, priority )
665 sdp.add_s(str_key, f, priority )
666 self.strdispatchers[name] = sdp
666 self.strdispatchers[name] = sdp
667 return
667 return
668 if re_key is not None:
668 if re_key is not None:
669 sdp = self.strdispatchers.get(name, StrDispatch())
669 sdp = self.strdispatchers.get(name, StrDispatch())
670 sdp.add_re(re.compile(re_key), f, priority )
670 sdp.add_re(re.compile(re_key), f, priority )
671 self.strdispatchers[name] = sdp
671 self.strdispatchers[name] = sdp
672 return
672 return
673
673
674 dp = getattr(self.hooks, name, None)
674 dp = getattr(self.hooks, name, None)
675 if name not in IPython.core.hooks.__all__:
675 if name not in IPython.core.hooks.__all__:
676 print "Warning! Hook '%s' is not one of %s" % \
676 print "Warning! Hook '%s' is not one of %s" % \
677 (name, IPython.core.hooks.__all__ )
677 (name, IPython.core.hooks.__all__ )
678 if not dp:
678 if not dp:
679 dp = IPython.core.hooks.CommandChainDispatcher()
679 dp = IPython.core.hooks.CommandChainDispatcher()
680
680
681 try:
681 try:
682 dp.add(f,priority)
682 dp.add(f,priority)
683 except AttributeError:
683 except AttributeError:
684 # it was not commandchain, plain old func - replace
684 # it was not commandchain, plain old func - replace
685 dp = f
685 dp = f
686
686
687 setattr(self.hooks,name, dp)
687 setattr(self.hooks,name, dp)
688
688
689 def register_post_execute(self, func):
689 def register_post_execute(self, func):
690 """Register a function for calling after code execution.
690 """Register a function for calling after code execution.
691 """
691 """
692 if not callable(func):
692 if not callable(func):
693 raise ValueError('argument %s must be callable' % func)
693 raise ValueError('argument %s must be callable' % func)
694 self._post_execute[func] = True
694 self._post_execute[func] = True
695
695
696 #-------------------------------------------------------------------------
696 #-------------------------------------------------------------------------
697 # Things related to the "main" module
697 # Things related to the "main" module
698 #-------------------------------------------------------------------------
698 #-------------------------------------------------------------------------
699
699
700 def new_main_mod(self,ns=None):
700 def new_main_mod(self,ns=None):
701 """Return a new 'main' module object for user code execution.
701 """Return a new 'main' module object for user code execution.
702 """
702 """
703 main_mod = self._user_main_module
703 main_mod = self._user_main_module
704 init_fakemod_dict(main_mod,ns)
704 init_fakemod_dict(main_mod,ns)
705 return main_mod
705 return main_mod
706
706
707 def cache_main_mod(self,ns,fname):
707 def cache_main_mod(self,ns,fname):
708 """Cache a main module's namespace.
708 """Cache a main module's namespace.
709
709
710 When scripts are executed via %run, we must keep a reference to the
710 When scripts are executed via %run, we must keep a reference to the
711 namespace of their __main__ module (a FakeModule instance) around so
711 namespace of their __main__ module (a FakeModule instance) around so
712 that Python doesn't clear it, rendering objects defined therein
712 that Python doesn't clear it, rendering objects defined therein
713 useless.
713 useless.
714
714
715 This method keeps said reference in a private dict, keyed by the
715 This method keeps said reference in a private dict, keyed by the
716 absolute path of the module object (which corresponds to the script
716 absolute path of the module object (which corresponds to the script
717 path). This way, for multiple executions of the same script we only
717 path). This way, for multiple executions of the same script we only
718 keep one copy of the namespace (the last one), thus preventing memory
718 keep one copy of the namespace (the last one), thus preventing memory
719 leaks from old references while allowing the objects from the last
719 leaks from old references while allowing the objects from the last
720 execution to be accessible.
720 execution to be accessible.
721
721
722 Note: we can not allow the actual FakeModule instances to be deleted,
722 Note: we can not allow the actual FakeModule instances to be deleted,
723 because of how Python tears down modules (it hard-sets all their
723 because of how Python tears down modules (it hard-sets all their
724 references to None without regard for reference counts). This method
724 references to None without regard for reference counts). This method
725 must therefore make a *copy* of the given namespace, to allow the
725 must therefore make a *copy* of the given namespace, to allow the
726 original module's __dict__ to be cleared and reused.
726 original module's __dict__ to be cleared and reused.
727
727
728
728
729 Parameters
729 Parameters
730 ----------
730 ----------
731 ns : a namespace (a dict, typically)
731 ns : a namespace (a dict, typically)
732
732
733 fname : str
733 fname : str
734 Filename associated with the namespace.
734 Filename associated with the namespace.
735
735
736 Examples
736 Examples
737 --------
737 --------
738
738
739 In [10]: import IPython
739 In [10]: import IPython
740
740
741 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
741 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
742
742
743 In [12]: IPython.__file__ in _ip._main_ns_cache
743 In [12]: IPython.__file__ in _ip._main_ns_cache
744 Out[12]: True
744 Out[12]: True
745 """
745 """
746 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
746 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
747
747
748 def clear_main_mod_cache(self):
748 def clear_main_mod_cache(self):
749 """Clear the cache of main modules.
749 """Clear the cache of main modules.
750
750
751 Mainly for use by utilities like %reset.
751 Mainly for use by utilities like %reset.
752
752
753 Examples
753 Examples
754 --------
754 --------
755
755
756 In [15]: import IPython
756 In [15]: import IPython
757
757
758 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
758 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
759
759
760 In [17]: len(_ip._main_ns_cache) > 0
760 In [17]: len(_ip._main_ns_cache) > 0
761 Out[17]: True
761 Out[17]: True
762
762
763 In [18]: _ip.clear_main_mod_cache()
763 In [18]: _ip.clear_main_mod_cache()
764
764
765 In [19]: len(_ip._main_ns_cache) == 0
765 In [19]: len(_ip._main_ns_cache) == 0
766 Out[19]: True
766 Out[19]: True
767 """
767 """
768 self._main_ns_cache.clear()
768 self._main_ns_cache.clear()
769
769
770 #-------------------------------------------------------------------------
770 #-------------------------------------------------------------------------
771 # Things related to debugging
771 # Things related to debugging
772 #-------------------------------------------------------------------------
772 #-------------------------------------------------------------------------
773
773
774 def init_pdb(self):
774 def init_pdb(self):
775 # Set calling of pdb on exceptions
775 # Set calling of pdb on exceptions
776 # self.call_pdb is a property
776 # self.call_pdb is a property
777 self.call_pdb = self.pdb
777 self.call_pdb = self.pdb
778
778
779 def _get_call_pdb(self):
779 def _get_call_pdb(self):
780 return self._call_pdb
780 return self._call_pdb
781
781
782 def _set_call_pdb(self,val):
782 def _set_call_pdb(self,val):
783
783
784 if val not in (0,1,False,True):
784 if val not in (0,1,False,True):
785 raise ValueError,'new call_pdb value must be boolean'
785 raise ValueError,'new call_pdb value must be boolean'
786
786
787 # store value in instance
787 # store value in instance
788 self._call_pdb = val
788 self._call_pdb = val
789
789
790 # notify the actual exception handlers
790 # notify the actual exception handlers
791 self.InteractiveTB.call_pdb = val
791 self.InteractiveTB.call_pdb = val
792
792
793 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
793 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
794 'Control auto-activation of pdb at exceptions')
794 'Control auto-activation of pdb at exceptions')
795
795
796 def debugger(self,force=False):
796 def debugger(self,force=False):
797 """Call the pydb/pdb debugger.
797 """Call the pydb/pdb debugger.
798
798
799 Keywords:
799 Keywords:
800
800
801 - force(False): by default, this routine checks the instance call_pdb
801 - force(False): by default, this routine checks the instance call_pdb
802 flag and does not actually invoke the debugger if the flag is false.
802 flag and does not actually invoke the debugger if the flag is false.
803 The 'force' option forces the debugger to activate even if the flag
803 The 'force' option forces the debugger to activate even if the flag
804 is false.
804 is false.
805 """
805 """
806
806
807 if not (force or self.call_pdb):
807 if not (force or self.call_pdb):
808 return
808 return
809
809
810 if not hasattr(sys,'last_traceback'):
810 if not hasattr(sys,'last_traceback'):
811 error('No traceback has been produced, nothing to debug.')
811 error('No traceback has been produced, nothing to debug.')
812 return
812 return
813
813
814 # use pydb if available
814 # use pydb if available
815 if debugger.has_pydb:
815 if debugger.has_pydb:
816 from pydb import pm
816 from pydb import pm
817 else:
817 else:
818 # fallback to our internal debugger
818 # fallback to our internal debugger
819 pm = lambda : self.InteractiveTB.debugger(force=True)
819 pm = lambda : self.InteractiveTB.debugger(force=True)
820
820
821 with self.readline_no_record:
821 with self.readline_no_record:
822 pm()
822 pm()
823
823
824 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
825 # Things related to IPython's various namespaces
825 # Things related to IPython's various namespaces
826 #-------------------------------------------------------------------------
826 #-------------------------------------------------------------------------
827
827
828 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
828 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
829 # Create the namespace where the user will operate. user_ns is
829 # Create the namespace where the user will operate. user_ns is
830 # normally the only one used, and it is passed to the exec calls as
830 # normally the only one used, and it is passed to the exec calls as
831 # the locals argument. But we do carry a user_global_ns namespace
831 # the locals argument. But we do carry a user_global_ns namespace
832 # given as the exec 'globals' argument, This is useful in embedding
832 # given as the exec 'globals' argument, This is useful in embedding
833 # situations where the ipython shell opens in a context where the
833 # situations where the ipython shell opens in a context where the
834 # distinction between locals and globals is meaningful. For
834 # distinction between locals and globals is meaningful. For
835 # non-embedded contexts, it is just the same object as the user_ns dict.
835 # non-embedded contexts, it is just the same object as the user_ns dict.
836
836
837 # FIXME. For some strange reason, __builtins__ is showing up at user
837 # FIXME. For some strange reason, __builtins__ is showing up at user
838 # level as a dict instead of a module. This is a manual fix, but I
838 # level as a dict instead of a module. This is a manual fix, but I
839 # should really track down where the problem is coming from. Alex
839 # should really track down where the problem is coming from. Alex
840 # Schmolck reported this problem first.
840 # Schmolck reported this problem first.
841
841
842 # A useful post by Alex Martelli on this topic:
842 # A useful post by Alex Martelli on this topic:
843 # Re: inconsistent value from __builtins__
843 # Re: inconsistent value from __builtins__
844 # Von: Alex Martelli <aleaxit@yahoo.com>
844 # Von: Alex Martelli <aleaxit@yahoo.com>
845 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
845 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
846 # Gruppen: comp.lang.python
846 # Gruppen: comp.lang.python
847
847
848 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
848 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
849 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
849 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
850 # > <type 'dict'>
850 # > <type 'dict'>
851 # > >>> print type(__builtins__)
851 # > >>> print type(__builtins__)
852 # > <type 'module'>
852 # > <type 'module'>
853 # > Is this difference in return value intentional?
853 # > Is this difference in return value intentional?
854
854
855 # Well, it's documented that '__builtins__' can be either a dictionary
855 # Well, it's documented that '__builtins__' can be either a dictionary
856 # or a module, and it's been that way for a long time. Whether it's
856 # or a module, and it's been that way for a long time. Whether it's
857 # intentional (or sensible), I don't know. In any case, the idea is
857 # intentional (or sensible), I don't know. In any case, the idea is
858 # that if you need to access the built-in namespace directly, you
858 # that if you need to access the built-in namespace directly, you
859 # should start with "import __builtin__" (note, no 's') which will
859 # should start with "import __builtin__" (note, no 's') which will
860 # definitely give you a module. Yeah, it's somewhat confusing:-(.
860 # definitely give you a module. Yeah, it's somewhat confusing:-(.
861
861
862 # These routines return properly built dicts as needed by the rest of
862 # These routines return properly built dicts as needed by the rest of
863 # the code, and can also be used by extension writers to generate
863 # the code, and can also be used by extension writers to generate
864 # properly initialized namespaces.
864 # properly initialized namespaces.
865 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
865 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
866 user_global_ns)
866 user_global_ns)
867
867
868 # Assign namespaces
868 # Assign namespaces
869 # This is the namespace where all normal user variables live
869 # This is the namespace where all normal user variables live
870 self.user_ns = user_ns
870 self.user_ns = user_ns
871 self.user_global_ns = user_global_ns
871 self.user_global_ns = user_global_ns
872
872
873 # An auxiliary namespace that checks what parts of the user_ns were
873 # An auxiliary namespace that checks what parts of the user_ns were
874 # loaded at startup, so we can list later only variables defined in
874 # loaded at startup, so we can list later only variables defined in
875 # actual interactive use. Since it is always a subset of user_ns, it
875 # actual interactive use. Since it is always a subset of user_ns, it
876 # doesn't need to be separately tracked in the ns_table.
876 # doesn't need to be separately tracked in the ns_table.
877 self.user_ns_hidden = {}
877 self.user_ns_hidden = {}
878
878
879 # A namespace to keep track of internal data structures to prevent
879 # A namespace to keep track of internal data structures to prevent
880 # them from cluttering user-visible stuff. Will be updated later
880 # them from cluttering user-visible stuff. Will be updated later
881 self.internal_ns = {}
881 self.internal_ns = {}
882
882
883 # Now that FakeModule produces a real module, we've run into a nasty
883 # Now that FakeModule produces a real module, we've run into a nasty
884 # problem: after script execution (via %run), the module where the user
884 # problem: after script execution (via %run), the module where the user
885 # code ran is deleted. Now that this object is a true module (needed
885 # code ran is deleted. Now that this object is a true module (needed
886 # so docetst and other tools work correctly), the Python module
886 # so docetst and other tools work correctly), the Python module
887 # teardown mechanism runs over it, and sets to None every variable
887 # teardown mechanism runs over it, and sets to None every variable
888 # present in that module. Top-level references to objects from the
888 # present in that module. Top-level references to objects from the
889 # script survive, because the user_ns is updated with them. However,
889 # script survive, because the user_ns is updated with them. However,
890 # calling functions defined in the script that use other things from
890 # calling functions defined in the script that use other things from
891 # the script will fail, because the function's closure had references
891 # the script will fail, because the function's closure had references
892 # to the original objects, which are now all None. So we must protect
892 # to the original objects, which are now all None. So we must protect
893 # these modules from deletion by keeping a cache.
893 # these modules from deletion by keeping a cache.
894 #
894 #
895 # To avoid keeping stale modules around (we only need the one from the
895 # To avoid keeping stale modules around (we only need the one from the
896 # last run), we use a dict keyed with the full path to the script, so
896 # last run), we use a dict keyed with the full path to the script, so
897 # only the last version of the module is held in the cache. Note,
897 # only the last version of the module is held in the cache. Note,
898 # however, that we must cache the module *namespace contents* (their
898 # however, that we must cache the module *namespace contents* (their
899 # __dict__). Because if we try to cache the actual modules, old ones
899 # __dict__). Because if we try to cache the actual modules, old ones
900 # (uncached) could be destroyed while still holding references (such as
900 # (uncached) could be destroyed while still holding references (such as
901 # those held by GUI objects that tend to be long-lived)>
901 # those held by GUI objects that tend to be long-lived)>
902 #
902 #
903 # The %reset command will flush this cache. See the cache_main_mod()
903 # The %reset command will flush this cache. See the cache_main_mod()
904 # and clear_main_mod_cache() methods for details on use.
904 # and clear_main_mod_cache() methods for details on use.
905
905
906 # This is the cache used for 'main' namespaces
906 # This is the cache used for 'main' namespaces
907 self._main_ns_cache = {}
907 self._main_ns_cache = {}
908 # And this is the single instance of FakeModule whose __dict__ we keep
908 # And this is the single instance of FakeModule whose __dict__ we keep
909 # copying and clearing for reuse on each %run
909 # copying and clearing for reuse on each %run
910 self._user_main_module = FakeModule()
910 self._user_main_module = FakeModule()
911
911
912 # A table holding all the namespaces IPython deals with, so that
912 # A table holding all the namespaces IPython deals with, so that
913 # introspection facilities can search easily.
913 # introspection facilities can search easily.
914 self.ns_table = {'user':user_ns,
914 self.ns_table = {'user':user_ns,
915 'user_global':user_global_ns,
915 'user_global':user_global_ns,
916 'internal':self.internal_ns,
916 'internal':self.internal_ns,
917 'builtin':__builtin__.__dict__
917 'builtin':__builtin__.__dict__
918 }
918 }
919
919
920 # Similarly, track all namespaces where references can be held and that
920 # Similarly, track all namespaces where references can be held and that
921 # we can safely clear (so it can NOT include builtin). This one can be
921 # we can safely clear (so it can NOT include builtin). This one can be
922 # a simple list. Note that the main execution namespaces, user_ns and
922 # a simple list. Note that the main execution namespaces, user_ns and
923 # user_global_ns, can NOT be listed here, as clearing them blindly
923 # user_global_ns, can NOT be listed here, as clearing them blindly
924 # causes errors in object __del__ methods. Instead, the reset() method
924 # causes errors in object __del__ methods. Instead, the reset() method
925 # clears them manually and carefully.
925 # clears them manually and carefully.
926 self.ns_refs_table = [ self.user_ns_hidden,
926 self.ns_refs_table = [ self.user_ns_hidden,
927 self.internal_ns, self._main_ns_cache ]
927 self.internal_ns, self._main_ns_cache ]
928
928
929 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
929 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
930 """Return a valid local and global user interactive namespaces.
930 """Return a valid local and global user interactive namespaces.
931
931
932 This builds a dict with the minimal information needed to operate as a
932 This builds a dict with the minimal information needed to operate as a
933 valid IPython user namespace, which you can pass to the various
933 valid IPython user namespace, which you can pass to the various
934 embedding classes in ipython. The default implementation returns the
934 embedding classes in ipython. The default implementation returns the
935 same dict for both the locals and the globals to allow functions to
935 same dict for both the locals and the globals to allow functions to
936 refer to variables in the namespace. Customized implementations can
936 refer to variables in the namespace. Customized implementations can
937 return different dicts. The locals dictionary can actually be anything
937 return different dicts. The locals dictionary can actually be anything
938 following the basic mapping protocol of a dict, but the globals dict
938 following the basic mapping protocol of a dict, but the globals dict
939 must be a true dict, not even a subclass. It is recommended that any
939 must be a true dict, not even a subclass. It is recommended that any
940 custom object for the locals namespace synchronize with the globals
940 custom object for the locals namespace synchronize with the globals
941 dict somehow.
941 dict somehow.
942
942
943 Raises TypeError if the provided globals namespace is not a true dict.
943 Raises TypeError if the provided globals namespace is not a true dict.
944
944
945 Parameters
945 Parameters
946 ----------
946 ----------
947 user_ns : dict-like, optional
947 user_ns : dict-like, optional
948 The current user namespace. The items in this namespace should
948 The current user namespace. The items in this namespace should
949 be included in the output. If None, an appropriate blank
949 be included in the output. If None, an appropriate blank
950 namespace should be created.
950 namespace should be created.
951 user_global_ns : dict, optional
951 user_global_ns : dict, optional
952 The current user global namespace. The items in this namespace
952 The current user global namespace. The items in this namespace
953 should be included in the output. If None, an appropriate
953 should be included in the output. If None, an appropriate
954 blank namespace should be created.
954 blank namespace should be created.
955
955
956 Returns
956 Returns
957 -------
957 -------
958 A pair of dictionary-like object to be used as the local namespace
958 A pair of dictionary-like object to be used as the local namespace
959 of the interpreter and a dict to be used as the global namespace.
959 of the interpreter and a dict to be used as the global namespace.
960 """
960 """
961
961
962
962
963 # We must ensure that __builtin__ (without the final 's') is always
963 # We must ensure that __builtin__ (without the final 's') is always
964 # available and pointing to the __builtin__ *module*. For more details:
964 # available and pointing to the __builtin__ *module*. For more details:
965 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
965 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
966
966
967 if user_ns is None:
967 if user_ns is None:
968 # Set __name__ to __main__ to better match the behavior of the
968 # Set __name__ to __main__ to better match the behavior of the
969 # normal interpreter.
969 # normal interpreter.
970 user_ns = {'__name__' :'__main__',
970 user_ns = {'__name__' :'__main__',
971 '__builtin__' : __builtin__,
971 '__builtin__' : __builtin__,
972 '__builtins__' : __builtin__,
972 '__builtins__' : __builtin__,
973 }
973 }
974 else:
974 else:
975 user_ns.setdefault('__name__','__main__')
975 user_ns.setdefault('__name__','__main__')
976 user_ns.setdefault('__builtin__',__builtin__)
976 user_ns.setdefault('__builtin__',__builtin__)
977 user_ns.setdefault('__builtins__',__builtin__)
977 user_ns.setdefault('__builtins__',__builtin__)
978
978
979 if user_global_ns is None:
979 if user_global_ns is None:
980 user_global_ns = user_ns
980 user_global_ns = user_ns
981 if type(user_global_ns) is not dict:
981 if type(user_global_ns) is not dict:
982 raise TypeError("user_global_ns must be a true dict; got %r"
982 raise TypeError("user_global_ns must be a true dict; got %r"
983 % type(user_global_ns))
983 % type(user_global_ns))
984
984
985 return user_ns, user_global_ns
985 return user_ns, user_global_ns
986
986
987 def init_sys_modules(self):
987 def init_sys_modules(self):
988 # We need to insert into sys.modules something that looks like a
988 # We need to insert into sys.modules something that looks like a
989 # module but which accesses the IPython namespace, for shelve and
989 # module but which accesses the IPython namespace, for shelve and
990 # pickle to work interactively. Normally they rely on getting
990 # pickle to work interactively. Normally they rely on getting
991 # everything out of __main__, but for embedding purposes each IPython
991 # everything out of __main__, but for embedding purposes each IPython
992 # instance has its own private namespace, so we can't go shoving
992 # instance has its own private namespace, so we can't go shoving
993 # everything into __main__.
993 # everything into __main__.
994
994
995 # note, however, that we should only do this for non-embedded
995 # note, however, that we should only do this for non-embedded
996 # ipythons, which really mimic the __main__.__dict__ with their own
996 # ipythons, which really mimic the __main__.__dict__ with their own
997 # namespace. Embedded instances, on the other hand, should not do
997 # namespace. Embedded instances, on the other hand, should not do
998 # this because they need to manage the user local/global namespaces
998 # this because they need to manage the user local/global namespaces
999 # only, but they live within a 'normal' __main__ (meaning, they
999 # only, but they live within a 'normal' __main__ (meaning, they
1000 # shouldn't overtake the execution environment of the script they're
1000 # shouldn't overtake the execution environment of the script they're
1001 # embedded in).
1001 # embedded in).
1002
1002
1003 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1003 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1004
1004
1005 try:
1005 try:
1006 main_name = self.user_ns['__name__']
1006 main_name = self.user_ns['__name__']
1007 except KeyError:
1007 except KeyError:
1008 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1008 raise KeyError('user_ns dictionary MUST have a "__name__" key')
1009 else:
1009 else:
1010 sys.modules[main_name] = FakeModule(self.user_ns)
1010 sys.modules[main_name] = FakeModule(self.user_ns)
1011
1011
1012 def init_user_ns(self):
1012 def init_user_ns(self):
1013 """Initialize all user-visible namespaces to their minimum defaults.
1013 """Initialize all user-visible namespaces to their minimum defaults.
1014
1014
1015 Certain history lists are also initialized here, as they effectively
1015 Certain history lists are also initialized here, as they effectively
1016 act as user namespaces.
1016 act as user namespaces.
1017
1017
1018 Notes
1018 Notes
1019 -----
1019 -----
1020 All data structures here are only filled in, they are NOT reset by this
1020 All data structures here are only filled in, they are NOT reset by this
1021 method. If they were not empty before, data will simply be added to
1021 method. If they were not empty before, data will simply be added to
1022 therm.
1022 therm.
1023 """
1023 """
1024 # This function works in two parts: first we put a few things in
1024 # This function works in two parts: first we put a few things in
1025 # user_ns, and we sync that contents into user_ns_hidden so that these
1025 # user_ns, and we sync that contents into user_ns_hidden so that these
1026 # initial variables aren't shown by %who. After the sync, we add the
1026 # initial variables aren't shown by %who. After the sync, we add the
1027 # rest of what we *do* want the user to see with %who even on a new
1027 # rest of what we *do* want the user to see with %who even on a new
1028 # session (probably nothing, so theye really only see their own stuff)
1028 # session (probably nothing, so theye really only see their own stuff)
1029
1029
1030 # The user dict must *always* have a __builtin__ reference to the
1030 # The user dict must *always* have a __builtin__ reference to the
1031 # Python standard __builtin__ namespace, which must be imported.
1031 # Python standard __builtin__ namespace, which must be imported.
1032 # This is so that certain operations in prompt evaluation can be
1032 # This is so that certain operations in prompt evaluation can be
1033 # reliably executed with builtins. Note that we can NOT use
1033 # reliably executed with builtins. Note that we can NOT use
1034 # __builtins__ (note the 's'), because that can either be a dict or a
1034 # __builtins__ (note the 's'), because that can either be a dict or a
1035 # module, and can even mutate at runtime, depending on the context
1035 # module, and can even mutate at runtime, depending on the context
1036 # (Python makes no guarantees on it). In contrast, __builtin__ is
1036 # (Python makes no guarantees on it). In contrast, __builtin__ is
1037 # always a module object, though it must be explicitly imported.
1037 # always a module object, though it must be explicitly imported.
1038
1038
1039 # For more details:
1039 # For more details:
1040 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1040 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1041 ns = dict(__builtin__ = __builtin__)
1041 ns = dict(__builtin__ = __builtin__)
1042
1042
1043 # Put 'help' in the user namespace
1043 # Put 'help' in the user namespace
1044 try:
1044 try:
1045 from site import _Helper
1045 from site import _Helper
1046 ns['help'] = _Helper()
1046 ns['help'] = _Helper()
1047 except ImportError:
1047 except ImportError:
1048 warn('help() not available - check site.py')
1048 warn('help() not available - check site.py')
1049
1049
1050 # make global variables for user access to the histories
1050 # make global variables for user access to the histories
1051 ns['_ih'] = self.history_manager.input_hist_parsed
1051 ns['_ih'] = self.history_manager.input_hist_parsed
1052 ns['_oh'] = self.history_manager.output_hist
1052 ns['_oh'] = self.history_manager.output_hist
1053 ns['_dh'] = self.history_manager.dir_hist
1053 ns['_dh'] = self.history_manager.dir_hist
1054
1054
1055 ns['_sh'] = shadowns
1055 ns['_sh'] = shadowns
1056
1056
1057 # user aliases to input and output histories. These shouldn't show up
1057 # user aliases to input and output histories. These shouldn't show up
1058 # in %who, as they can have very large reprs.
1058 # in %who, as they can have very large reprs.
1059 ns['In'] = self.history_manager.input_hist_parsed
1059 ns['In'] = self.history_manager.input_hist_parsed
1060 ns['Out'] = self.history_manager.output_hist
1060 ns['Out'] = self.history_manager.output_hist
1061
1061
1062 # Store myself as the public api!!!
1062 # Store myself as the public api!!!
1063 ns['get_ipython'] = self.get_ipython
1063 ns['get_ipython'] = self.get_ipython
1064
1064
1065 ns['exit'] = self.exiter
1065 ns['exit'] = self.exiter
1066 ns['quit'] = self.exiter
1066 ns['quit'] = self.exiter
1067
1067
1068 # Sync what we've added so far to user_ns_hidden so these aren't seen
1068 # Sync what we've added so far to user_ns_hidden so these aren't seen
1069 # by %who
1069 # by %who
1070 self.user_ns_hidden.update(ns)
1070 self.user_ns_hidden.update(ns)
1071
1071
1072 # Anything put into ns now would show up in %who. Think twice before
1072 # Anything put into ns now would show up in %who. Think twice before
1073 # putting anything here, as we really want %who to show the user their
1073 # putting anything here, as we really want %who to show the user their
1074 # stuff, not our variables.
1074 # stuff, not our variables.
1075
1075
1076 # Finally, update the real user's namespace
1076 # Finally, update the real user's namespace
1077 self.user_ns.update(ns)
1077 self.user_ns.update(ns)
1078
1078
1079 def reset(self, new_session=True):
1079 def reset(self, new_session=True):
1080 """Clear all internal namespaces, and attempt to release references to
1080 """Clear all internal namespaces, and attempt to release references to
1081 user objects.
1081 user objects.
1082
1082
1083 If new_session is True, a new history session will be opened.
1083 If new_session is True, a new history session will be opened.
1084 """
1084 """
1085 # Clear histories
1085 # Clear histories
1086 self.history_manager.reset(new_session)
1086 self.history_manager.reset(new_session)
1087 # Reset counter used to index all histories
1087 # Reset counter used to index all histories
1088 if new_session:
1088 if new_session:
1089 self.execution_count = 1
1089 self.execution_count = 1
1090
1090
1091 # Flush cached output items
1091 # Flush cached output items
1092 if self.displayhook.do_full_cache:
1092 if self.displayhook.do_full_cache:
1093 self.displayhook.flush()
1093 self.displayhook.flush()
1094
1094
1095 # Restore the user namespaces to minimal usability
1095 # Restore the user namespaces to minimal usability
1096 for ns in self.ns_refs_table:
1096 for ns in self.ns_refs_table:
1097 ns.clear()
1097 ns.clear()
1098
1098
1099 # The main execution namespaces must be cleared very carefully,
1099 # The main execution namespaces must be cleared very carefully,
1100 # skipping the deletion of the builtin-related keys, because doing so
1100 # skipping the deletion of the builtin-related keys, because doing so
1101 # would cause errors in many object's __del__ methods.
1101 # would cause errors in many object's __del__ methods.
1102 for ns in [self.user_ns, self.user_global_ns]:
1102 for ns in [self.user_ns, self.user_global_ns]:
1103 drop_keys = set(ns.keys())
1103 drop_keys = set(ns.keys())
1104 drop_keys.discard('__builtin__')
1104 drop_keys.discard('__builtin__')
1105 drop_keys.discard('__builtins__')
1105 drop_keys.discard('__builtins__')
1106 for k in drop_keys:
1106 for k in drop_keys:
1107 del ns[k]
1107 del ns[k]
1108
1108
1109 # Restore the user namespaces to minimal usability
1109 # Restore the user namespaces to minimal usability
1110 self.init_user_ns()
1110 self.init_user_ns()
1111
1111
1112 # Restore the default and user aliases
1112 # Restore the default and user aliases
1113 self.alias_manager.clear_aliases()
1113 self.alias_manager.clear_aliases()
1114 self.alias_manager.init_aliases()
1114 self.alias_manager.init_aliases()
1115
1115
1116 # Flush the private list of module references kept for script
1116 # Flush the private list of module references kept for script
1117 # execution protection
1117 # execution protection
1118 self.clear_main_mod_cache()
1118 self.clear_main_mod_cache()
1119
1119
1120 # Clear out the namespace from the last %run
1120 # Clear out the namespace from the last %run
1121 self.new_main_mod()
1121 self.new_main_mod()
1122
1122
1123 def del_var(self, varname, by_name=False):
1124 """Delete a variable from the various namespaces, so that, as
1125 far as possible, we're not keeping any hidden references to it.
1126
1127 Parameters
1128 ----------
1129 varname : str
1130 The name of the variable to delete.
1131 by_name : bool
1132 If True, delete variables with the given name in each
1133 namespace. If False (default), find the variable in the user
1134 namespace, and delete references to it.
1135 """
1136 if varname in ('__builtin__', '__builtins__'):
1137 raise ValueError("Refusing to delete %s" % varname)
1138 ns_refs = self.ns_refs_table + [self.user_ns,
1139 self.user_global_ns, self._user_main_module.__dict__] +\
1140 self._main_ns_cache.values()
1141
1142 if by_name: # Delete by name
1143 for ns in ns_refs:
1144 try:
1145 del ns[varname]
1146 except KeyError:
1147 pass
1148 else: # Delete by object
1149 try:
1150 obj = self.user_ns[varname]
1151 except KeyError:
1152 raise NameError("name '%s' is not defined" % varname)
1153 # Also check in output history
1154 ns_refs.append(self.history_manager.output_hist)
1155 for ns in ns_refs:
1156 to_delete = [n for n, o in ns.iteritems() if o is obj]
1157 for name in to_delete:
1158 del ns[name]
1159
1160 # displayhook keeps extra references, but not in a dictionary
1161 for name in ('_', '__', '___'):
1162 if getattr(self.displayhook, name) is obj:
1163 setattr(self.displayhook, name, None)
1164
1123 def reset_selective(self, regex=None):
1165 def reset_selective(self, regex=None):
1124 """Clear selective variables from internal namespaces based on a
1166 """Clear selective variables from internal namespaces based on a
1125 specified regular expression.
1167 specified regular expression.
1126
1168
1127 Parameters
1169 Parameters
1128 ----------
1170 ----------
1129 regex : string or compiled pattern, optional
1171 regex : string or compiled pattern, optional
1130 A regular expression pattern that will be used in searching
1172 A regular expression pattern that will be used in searching
1131 variable names in the users namespaces.
1173 variable names in the users namespaces.
1132 """
1174 """
1133 if regex is not None:
1175 if regex is not None:
1134 try:
1176 try:
1135 m = re.compile(regex)
1177 m = re.compile(regex)
1136 except TypeError:
1178 except TypeError:
1137 raise TypeError('regex must be a string or compiled pattern')
1179 raise TypeError('regex must be a string or compiled pattern')
1138 # Search for keys in each namespace that match the given regex
1180 # Search for keys in each namespace that match the given regex
1139 # If a match is found, delete the key/value pair.
1181 # If a match is found, delete the key/value pair.
1140 for ns in self.ns_refs_table:
1182 for ns in self.ns_refs_table:
1141 for var in ns:
1183 for var in ns:
1142 if m.search(var):
1184 if m.search(var):
1143 del ns[var]
1185 del ns[var]
1144
1186
1145 def push(self, variables, interactive=True):
1187 def push(self, variables, interactive=True):
1146 """Inject a group of variables into the IPython user namespace.
1188 """Inject a group of variables into the IPython user namespace.
1147
1189
1148 Parameters
1190 Parameters
1149 ----------
1191 ----------
1150 variables : dict, str or list/tuple of str
1192 variables : dict, str or list/tuple of str
1151 The variables to inject into the user's namespace. If a dict, a
1193 The variables to inject into the user's namespace. If a dict, a
1152 simple update is done. If a str, the string is assumed to have
1194 simple update is done. If a str, the string is assumed to have
1153 variable names separated by spaces. A list/tuple of str can also
1195 variable names separated by spaces. A list/tuple of str can also
1154 be used to give the variable names. If just the variable names are
1196 be used to give the variable names. If just the variable names are
1155 give (list/tuple/str) then the variable values looked up in the
1197 give (list/tuple/str) then the variable values looked up in the
1156 callers frame.
1198 callers frame.
1157 interactive : bool
1199 interactive : bool
1158 If True (default), the variables will be listed with the ``who``
1200 If True (default), the variables will be listed with the ``who``
1159 magic.
1201 magic.
1160 """
1202 """
1161 vdict = None
1203 vdict = None
1162
1204
1163 # We need a dict of name/value pairs to do namespace updates.
1205 # We need a dict of name/value pairs to do namespace updates.
1164 if isinstance(variables, dict):
1206 if isinstance(variables, dict):
1165 vdict = variables
1207 vdict = variables
1166 elif isinstance(variables, (basestring, list, tuple)):
1208 elif isinstance(variables, (basestring, list, tuple)):
1167 if isinstance(variables, basestring):
1209 if isinstance(variables, basestring):
1168 vlist = variables.split()
1210 vlist = variables.split()
1169 else:
1211 else:
1170 vlist = variables
1212 vlist = variables
1171 vdict = {}
1213 vdict = {}
1172 cf = sys._getframe(1)
1214 cf = sys._getframe(1)
1173 for name in vlist:
1215 for name in vlist:
1174 try:
1216 try:
1175 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1217 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1176 except:
1218 except:
1177 print ('Could not get variable %s from %s' %
1219 print ('Could not get variable %s from %s' %
1178 (name,cf.f_code.co_name))
1220 (name,cf.f_code.co_name))
1179 else:
1221 else:
1180 raise ValueError('variables must be a dict/str/list/tuple')
1222 raise ValueError('variables must be a dict/str/list/tuple')
1181
1223
1182 # Propagate variables to user namespace
1224 # Propagate variables to user namespace
1183 self.user_ns.update(vdict)
1225 self.user_ns.update(vdict)
1184
1226
1185 # And configure interactive visibility
1227 # And configure interactive visibility
1186 config_ns = self.user_ns_hidden
1228 config_ns = self.user_ns_hidden
1187 if interactive:
1229 if interactive:
1188 for name, val in vdict.iteritems():
1230 for name, val in vdict.iteritems():
1189 config_ns.pop(name, None)
1231 config_ns.pop(name, None)
1190 else:
1232 else:
1191 for name,val in vdict.iteritems():
1233 for name,val in vdict.iteritems():
1192 config_ns[name] = val
1234 config_ns[name] = val
1193
1235
1194 #-------------------------------------------------------------------------
1236 #-------------------------------------------------------------------------
1195 # Things related to object introspection
1237 # Things related to object introspection
1196 #-------------------------------------------------------------------------
1238 #-------------------------------------------------------------------------
1197
1239
1198 def _ofind(self, oname, namespaces=None):
1240 def _ofind(self, oname, namespaces=None):
1199 """Find an object in the available namespaces.
1241 """Find an object in the available namespaces.
1200
1242
1201 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1243 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1202
1244
1203 Has special code to detect magic functions.
1245 Has special code to detect magic functions.
1204 """
1246 """
1205 #oname = oname.strip()
1247 #oname = oname.strip()
1206 #print '1- oname: <%r>' % oname # dbg
1248 #print '1- oname: <%r>' % oname # dbg
1207 try:
1249 try:
1208 oname = oname.strip().encode('ascii')
1250 oname = oname.strip().encode('ascii')
1209 #print '2- oname: <%r>' % oname # dbg
1251 #print '2- oname: <%r>' % oname # dbg
1210 except UnicodeEncodeError:
1252 except UnicodeEncodeError:
1211 print 'Python identifiers can only contain ascii characters.'
1253 print 'Python identifiers can only contain ascii characters.'
1212 return dict(found=False)
1254 return dict(found=False)
1213
1255
1214 alias_ns = None
1256 alias_ns = None
1215 if namespaces is None:
1257 if namespaces is None:
1216 # Namespaces to search in:
1258 # Namespaces to search in:
1217 # Put them in a list. The order is important so that we
1259 # Put them in a list. The order is important so that we
1218 # find things in the same order that Python finds them.
1260 # find things in the same order that Python finds them.
1219 namespaces = [ ('Interactive', self.user_ns),
1261 namespaces = [ ('Interactive', self.user_ns),
1220 ('IPython internal', self.internal_ns),
1262 ('IPython internal', self.internal_ns),
1221 ('Python builtin', __builtin__.__dict__),
1263 ('Python builtin', __builtin__.__dict__),
1222 ('Alias', self.alias_manager.alias_table),
1264 ('Alias', self.alias_manager.alias_table),
1223 ]
1265 ]
1224 alias_ns = self.alias_manager.alias_table
1266 alias_ns = self.alias_manager.alias_table
1225
1267
1226 # initialize results to 'null'
1268 # initialize results to 'null'
1227 found = False; obj = None; ospace = None; ds = None;
1269 found = False; obj = None; ospace = None; ds = None;
1228 ismagic = False; isalias = False; parent = None
1270 ismagic = False; isalias = False; parent = None
1229
1271
1230 # We need to special-case 'print', which as of python2.6 registers as a
1272 # We need to special-case 'print', which as of python2.6 registers as a
1231 # function but should only be treated as one if print_function was
1273 # function but should only be treated as one if print_function was
1232 # loaded with a future import. In this case, just bail.
1274 # loaded with a future import. In this case, just bail.
1233 if (oname == 'print' and not (self.compile.compiler_flags &
1275 if (oname == 'print' and not (self.compile.compiler_flags &
1234 __future__.CO_FUTURE_PRINT_FUNCTION)):
1276 __future__.CO_FUTURE_PRINT_FUNCTION)):
1235 return {'found':found, 'obj':obj, 'namespace':ospace,
1277 return {'found':found, 'obj':obj, 'namespace':ospace,
1236 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1278 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1237
1279
1238 # Look for the given name by splitting it in parts. If the head is
1280 # Look for the given name by splitting it in parts. If the head is
1239 # found, then we look for all the remaining parts as members, and only
1281 # found, then we look for all the remaining parts as members, and only
1240 # declare success if we can find them all.
1282 # declare success if we can find them all.
1241 oname_parts = oname.split('.')
1283 oname_parts = oname.split('.')
1242 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1284 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1243 for nsname,ns in namespaces:
1285 for nsname,ns in namespaces:
1244 try:
1286 try:
1245 obj = ns[oname_head]
1287 obj = ns[oname_head]
1246 except KeyError:
1288 except KeyError:
1247 continue
1289 continue
1248 else:
1290 else:
1249 #print 'oname_rest:', oname_rest # dbg
1291 #print 'oname_rest:', oname_rest # dbg
1250 for part in oname_rest:
1292 for part in oname_rest:
1251 try:
1293 try:
1252 parent = obj
1294 parent = obj
1253 obj = getattr(obj,part)
1295 obj = getattr(obj,part)
1254 except:
1296 except:
1255 # Blanket except b/c some badly implemented objects
1297 # Blanket except b/c some badly implemented objects
1256 # allow __getattr__ to raise exceptions other than
1298 # allow __getattr__ to raise exceptions other than
1257 # AttributeError, which then crashes IPython.
1299 # AttributeError, which then crashes IPython.
1258 break
1300 break
1259 else:
1301 else:
1260 # If we finish the for loop (no break), we got all members
1302 # If we finish the for loop (no break), we got all members
1261 found = True
1303 found = True
1262 ospace = nsname
1304 ospace = nsname
1263 if ns == alias_ns:
1305 if ns == alias_ns:
1264 isalias = True
1306 isalias = True
1265 break # namespace loop
1307 break # namespace loop
1266
1308
1267 # Try to see if it's magic
1309 # Try to see if it's magic
1268 if not found:
1310 if not found:
1269 if oname.startswith(ESC_MAGIC):
1311 if oname.startswith(ESC_MAGIC):
1270 oname = oname[1:]
1312 oname = oname[1:]
1271 obj = getattr(self,'magic_'+oname,None)
1313 obj = getattr(self,'magic_'+oname,None)
1272 if obj is not None:
1314 if obj is not None:
1273 found = True
1315 found = True
1274 ospace = 'IPython internal'
1316 ospace = 'IPython internal'
1275 ismagic = True
1317 ismagic = True
1276
1318
1277 # Last try: special-case some literals like '', [], {}, etc:
1319 # Last try: special-case some literals like '', [], {}, etc:
1278 if not found and oname_head in ["''",'""','[]','{}','()']:
1320 if not found and oname_head in ["''",'""','[]','{}','()']:
1279 obj = eval(oname_head)
1321 obj = eval(oname_head)
1280 found = True
1322 found = True
1281 ospace = 'Interactive'
1323 ospace = 'Interactive'
1282
1324
1283 return {'found':found, 'obj':obj, 'namespace':ospace,
1325 return {'found':found, 'obj':obj, 'namespace':ospace,
1284 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1326 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1285
1327
1286 def _ofind_property(self, oname, info):
1328 def _ofind_property(self, oname, info):
1287 """Second part of object finding, to look for property details."""
1329 """Second part of object finding, to look for property details."""
1288 if info.found:
1330 if info.found:
1289 # Get the docstring of the class property if it exists.
1331 # Get the docstring of the class property if it exists.
1290 path = oname.split('.')
1332 path = oname.split('.')
1291 root = '.'.join(path[:-1])
1333 root = '.'.join(path[:-1])
1292 if info.parent is not None:
1334 if info.parent is not None:
1293 try:
1335 try:
1294 target = getattr(info.parent, '__class__')
1336 target = getattr(info.parent, '__class__')
1295 # The object belongs to a class instance.
1337 # The object belongs to a class instance.
1296 try:
1338 try:
1297 target = getattr(target, path[-1])
1339 target = getattr(target, path[-1])
1298 # The class defines the object.
1340 # The class defines the object.
1299 if isinstance(target, property):
1341 if isinstance(target, property):
1300 oname = root + '.__class__.' + path[-1]
1342 oname = root + '.__class__.' + path[-1]
1301 info = Struct(self._ofind(oname))
1343 info = Struct(self._ofind(oname))
1302 except AttributeError: pass
1344 except AttributeError: pass
1303 except AttributeError: pass
1345 except AttributeError: pass
1304
1346
1305 # We return either the new info or the unmodified input if the object
1347 # We return either the new info or the unmodified input if the object
1306 # hadn't been found
1348 # hadn't been found
1307 return info
1349 return info
1308
1350
1309 def _object_find(self, oname, namespaces=None):
1351 def _object_find(self, oname, namespaces=None):
1310 """Find an object and return a struct with info about it."""
1352 """Find an object and return a struct with info about it."""
1311 inf = Struct(self._ofind(oname, namespaces))
1353 inf = Struct(self._ofind(oname, namespaces))
1312 return Struct(self._ofind_property(oname, inf))
1354 return Struct(self._ofind_property(oname, inf))
1313
1355
1314 def _inspect(self, meth, oname, namespaces=None, **kw):
1356 def _inspect(self, meth, oname, namespaces=None, **kw):
1315 """Generic interface to the inspector system.
1357 """Generic interface to the inspector system.
1316
1358
1317 This function is meant to be called by pdef, pdoc & friends."""
1359 This function is meant to be called by pdef, pdoc & friends."""
1318 info = self._object_find(oname)
1360 info = self._object_find(oname)
1319 if info.found:
1361 if info.found:
1320 pmethod = getattr(self.inspector, meth)
1362 pmethod = getattr(self.inspector, meth)
1321 formatter = format_screen if info.ismagic else None
1363 formatter = format_screen if info.ismagic else None
1322 if meth == 'pdoc':
1364 if meth == 'pdoc':
1323 pmethod(info.obj, oname, formatter)
1365 pmethod(info.obj, oname, formatter)
1324 elif meth == 'pinfo':
1366 elif meth == 'pinfo':
1325 pmethod(info.obj, oname, formatter, info, **kw)
1367 pmethod(info.obj, oname, formatter, info, **kw)
1326 else:
1368 else:
1327 pmethod(info.obj, oname)
1369 pmethod(info.obj, oname)
1328 else:
1370 else:
1329 print 'Object `%s` not found.' % oname
1371 print 'Object `%s` not found.' % oname
1330 return 'not found' # so callers can take other action
1372 return 'not found' # so callers can take other action
1331
1373
1332 def object_inspect(self, oname):
1374 def object_inspect(self, oname):
1333 with self.builtin_trap:
1375 with self.builtin_trap:
1334 info = self._object_find(oname)
1376 info = self._object_find(oname)
1335 if info.found:
1377 if info.found:
1336 return self.inspector.info(info.obj, oname, info=info)
1378 return self.inspector.info(info.obj, oname, info=info)
1337 else:
1379 else:
1338 return oinspect.object_info(name=oname, found=False)
1380 return oinspect.object_info(name=oname, found=False)
1339
1381
1340 #-------------------------------------------------------------------------
1382 #-------------------------------------------------------------------------
1341 # Things related to history management
1383 # Things related to history management
1342 #-------------------------------------------------------------------------
1384 #-------------------------------------------------------------------------
1343
1385
1344 def init_history(self):
1386 def init_history(self):
1345 """Sets up the command history, and starts regular autosaves."""
1387 """Sets up the command history, and starts regular autosaves."""
1346 self.history_manager = HistoryManager(shell=self, config=self.config)
1388 self.history_manager = HistoryManager(shell=self, config=self.config)
1347
1389
1348 #-------------------------------------------------------------------------
1390 #-------------------------------------------------------------------------
1349 # Things related to exception handling and tracebacks (not debugging)
1391 # Things related to exception handling and tracebacks (not debugging)
1350 #-------------------------------------------------------------------------
1392 #-------------------------------------------------------------------------
1351
1393
1352 def init_traceback_handlers(self, custom_exceptions):
1394 def init_traceback_handlers(self, custom_exceptions):
1353 # Syntax error handler.
1395 # Syntax error handler.
1354 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1396 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1355
1397
1356 # The interactive one is initialized with an offset, meaning we always
1398 # The interactive one is initialized with an offset, meaning we always
1357 # want to remove the topmost item in the traceback, which is our own
1399 # want to remove the topmost item in the traceback, which is our own
1358 # internal code. Valid modes: ['Plain','Context','Verbose']
1400 # internal code. Valid modes: ['Plain','Context','Verbose']
1359 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1401 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1360 color_scheme='NoColor',
1402 color_scheme='NoColor',
1361 tb_offset = 1,
1403 tb_offset = 1,
1362 check_cache=self.compile.check_cache)
1404 check_cache=self.compile.check_cache)
1363
1405
1364 # The instance will store a pointer to the system-wide exception hook,
1406 # The instance will store a pointer to the system-wide exception hook,
1365 # so that runtime code (such as magics) can access it. This is because
1407 # so that runtime code (such as magics) can access it. This is because
1366 # during the read-eval loop, it may get temporarily overwritten.
1408 # during the read-eval loop, it may get temporarily overwritten.
1367 self.sys_excepthook = sys.excepthook
1409 self.sys_excepthook = sys.excepthook
1368
1410
1369 # and add any custom exception handlers the user may have specified
1411 # and add any custom exception handlers the user may have specified
1370 self.set_custom_exc(*custom_exceptions)
1412 self.set_custom_exc(*custom_exceptions)
1371
1413
1372 # Set the exception mode
1414 # Set the exception mode
1373 self.InteractiveTB.set_mode(mode=self.xmode)
1415 self.InteractiveTB.set_mode(mode=self.xmode)
1374
1416
1375 def set_custom_exc(self, exc_tuple, handler):
1417 def set_custom_exc(self, exc_tuple, handler):
1376 """set_custom_exc(exc_tuple,handler)
1418 """set_custom_exc(exc_tuple,handler)
1377
1419
1378 Set a custom exception handler, which will be called if any of the
1420 Set a custom exception handler, which will be called if any of the
1379 exceptions in exc_tuple occur in the mainloop (specifically, in the
1421 exceptions in exc_tuple occur in the mainloop (specifically, in the
1380 run_code() method.
1422 run_code() method.
1381
1423
1382 Inputs:
1424 Inputs:
1383
1425
1384 - exc_tuple: a *tuple* of valid exceptions to call the defined
1426 - exc_tuple: a *tuple* of valid exceptions to call the defined
1385 handler for. It is very important that you use a tuple, and NOT A
1427 handler for. It is very important that you use a tuple, and NOT A
1386 LIST here, because of the way Python's except statement works. If
1428 LIST here, because of the way Python's except statement works. If
1387 you only want to trap a single exception, use a singleton tuple:
1429 you only want to trap a single exception, use a singleton tuple:
1388
1430
1389 exc_tuple == (MyCustomException,)
1431 exc_tuple == (MyCustomException,)
1390
1432
1391 - handler: this must be defined as a function with the following
1433 - handler: this must be defined as a function with the following
1392 basic interface::
1434 basic interface::
1393
1435
1394 def my_handler(self, etype, value, tb, tb_offset=None)
1436 def my_handler(self, etype, value, tb, tb_offset=None)
1395 ...
1437 ...
1396 # The return value must be
1438 # The return value must be
1397 return structured_traceback
1439 return structured_traceback
1398
1440
1399 This will be made into an instance method (via types.MethodType)
1441 This will be made into an instance method (via types.MethodType)
1400 of IPython itself, and it will be called if any of the exceptions
1442 of IPython itself, and it will be called if any of the exceptions
1401 listed in the exc_tuple are caught. If the handler is None, an
1443 listed in the exc_tuple are caught. If the handler is None, an
1402 internal basic one is used, which just prints basic info.
1444 internal basic one is used, which just prints basic info.
1403
1445
1404 WARNING: by putting in your own exception handler into IPython's main
1446 WARNING: by putting in your own exception handler into IPython's main
1405 execution loop, you run a very good chance of nasty crashes. This
1447 execution loop, you run a very good chance of nasty crashes. This
1406 facility should only be used if you really know what you are doing."""
1448 facility should only be used if you really know what you are doing."""
1407
1449
1408 assert type(exc_tuple)==type(()) , \
1450 assert type(exc_tuple)==type(()) , \
1409 "The custom exceptions must be given AS A TUPLE."
1451 "The custom exceptions must be given AS A TUPLE."
1410
1452
1411 def dummy_handler(self,etype,value,tb):
1453 def dummy_handler(self,etype,value,tb):
1412 print '*** Simple custom exception handler ***'
1454 print '*** Simple custom exception handler ***'
1413 print 'Exception type :',etype
1455 print 'Exception type :',etype
1414 print 'Exception value:',value
1456 print 'Exception value:',value
1415 print 'Traceback :',tb
1457 print 'Traceback :',tb
1416 #print 'Source code :','\n'.join(self.buffer)
1458 #print 'Source code :','\n'.join(self.buffer)
1417
1459
1418 if handler is None: handler = dummy_handler
1460 if handler is None: handler = dummy_handler
1419
1461
1420 self.CustomTB = types.MethodType(handler,self)
1462 self.CustomTB = types.MethodType(handler,self)
1421 self.custom_exceptions = exc_tuple
1463 self.custom_exceptions = exc_tuple
1422
1464
1423 def excepthook(self, etype, value, tb):
1465 def excepthook(self, etype, value, tb):
1424 """One more defense for GUI apps that call sys.excepthook.
1466 """One more defense for GUI apps that call sys.excepthook.
1425
1467
1426 GUI frameworks like wxPython trap exceptions and call
1468 GUI frameworks like wxPython trap exceptions and call
1427 sys.excepthook themselves. I guess this is a feature that
1469 sys.excepthook themselves. I guess this is a feature that
1428 enables them to keep running after exceptions that would
1470 enables them to keep running after exceptions that would
1429 otherwise kill their mainloop. This is a bother for IPython
1471 otherwise kill their mainloop. This is a bother for IPython
1430 which excepts to catch all of the program exceptions with a try:
1472 which excepts to catch all of the program exceptions with a try:
1431 except: statement.
1473 except: statement.
1432
1474
1433 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1475 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1434 any app directly invokes sys.excepthook, it will look to the user like
1476 any app directly invokes sys.excepthook, it will look to the user like
1435 IPython crashed. In order to work around this, we can disable the
1477 IPython crashed. In order to work around this, we can disable the
1436 CrashHandler and replace it with this excepthook instead, which prints a
1478 CrashHandler and replace it with this excepthook instead, which prints a
1437 regular traceback using our InteractiveTB. In this fashion, apps which
1479 regular traceback using our InteractiveTB. In this fashion, apps which
1438 call sys.excepthook will generate a regular-looking exception from
1480 call sys.excepthook will generate a regular-looking exception from
1439 IPython, and the CrashHandler will only be triggered by real IPython
1481 IPython, and the CrashHandler will only be triggered by real IPython
1440 crashes.
1482 crashes.
1441
1483
1442 This hook should be used sparingly, only in places which are not likely
1484 This hook should be used sparingly, only in places which are not likely
1443 to be true IPython errors.
1485 to be true IPython errors.
1444 """
1486 """
1445 self.showtraceback((etype,value,tb),tb_offset=0)
1487 self.showtraceback((etype,value,tb),tb_offset=0)
1446
1488
1447 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1489 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1448 exception_only=False):
1490 exception_only=False):
1449 """Display the exception that just occurred.
1491 """Display the exception that just occurred.
1450
1492
1451 If nothing is known about the exception, this is the method which
1493 If nothing is known about the exception, this is the method which
1452 should be used throughout the code for presenting user tracebacks,
1494 should be used throughout the code for presenting user tracebacks,
1453 rather than directly invoking the InteractiveTB object.
1495 rather than directly invoking the InteractiveTB object.
1454
1496
1455 A specific showsyntaxerror() also exists, but this method can take
1497 A specific showsyntaxerror() also exists, but this method can take
1456 care of calling it if needed, so unless you are explicitly catching a
1498 care of calling it if needed, so unless you are explicitly catching a
1457 SyntaxError exception, don't try to analyze the stack manually and
1499 SyntaxError exception, don't try to analyze the stack manually and
1458 simply call this method."""
1500 simply call this method."""
1459
1501
1460 try:
1502 try:
1461 if exc_tuple is None:
1503 if exc_tuple is None:
1462 etype, value, tb = sys.exc_info()
1504 etype, value, tb = sys.exc_info()
1463 else:
1505 else:
1464 etype, value, tb = exc_tuple
1506 etype, value, tb = exc_tuple
1465
1507
1466 if etype is None:
1508 if etype is None:
1467 if hasattr(sys, 'last_type'):
1509 if hasattr(sys, 'last_type'):
1468 etype, value, tb = sys.last_type, sys.last_value, \
1510 etype, value, tb = sys.last_type, sys.last_value, \
1469 sys.last_traceback
1511 sys.last_traceback
1470 else:
1512 else:
1471 self.write_err('No traceback available to show.\n')
1513 self.write_err('No traceback available to show.\n')
1472 return
1514 return
1473
1515
1474 if etype is SyntaxError:
1516 if etype is SyntaxError:
1475 # Though this won't be called by syntax errors in the input
1517 # Though this won't be called by syntax errors in the input
1476 # line, there may be SyntaxError cases whith imported code.
1518 # line, there may be SyntaxError cases whith imported code.
1477 self.showsyntaxerror(filename)
1519 self.showsyntaxerror(filename)
1478 elif etype is UsageError:
1520 elif etype is UsageError:
1479 print "UsageError:", value
1521 print "UsageError:", value
1480 else:
1522 else:
1481 # WARNING: these variables are somewhat deprecated and not
1523 # WARNING: these variables are somewhat deprecated and not
1482 # necessarily safe to use in a threaded environment, but tools
1524 # necessarily safe to use in a threaded environment, but tools
1483 # like pdb depend on their existence, so let's set them. If we
1525 # like pdb depend on their existence, so let's set them. If we
1484 # find problems in the field, we'll need to revisit their use.
1526 # find problems in the field, we'll need to revisit their use.
1485 sys.last_type = etype
1527 sys.last_type = etype
1486 sys.last_value = value
1528 sys.last_value = value
1487 sys.last_traceback = tb
1529 sys.last_traceback = tb
1488 if etype in self.custom_exceptions:
1530 if etype in self.custom_exceptions:
1489 # FIXME: Old custom traceback objects may just return a
1531 # FIXME: Old custom traceback objects may just return a
1490 # string, in that case we just put it into a list
1532 # string, in that case we just put it into a list
1491 stb = self.CustomTB(etype, value, tb, tb_offset)
1533 stb = self.CustomTB(etype, value, tb, tb_offset)
1492 if isinstance(ctb, basestring):
1534 if isinstance(ctb, basestring):
1493 stb = [stb]
1535 stb = [stb]
1494 else:
1536 else:
1495 if exception_only:
1537 if exception_only:
1496 stb = ['An exception has occurred, use %tb to see '
1538 stb = ['An exception has occurred, use %tb to see '
1497 'the full traceback.\n']
1539 'the full traceback.\n']
1498 stb.extend(self.InteractiveTB.get_exception_only(etype,
1540 stb.extend(self.InteractiveTB.get_exception_only(etype,
1499 value))
1541 value))
1500 else:
1542 else:
1501 stb = self.InteractiveTB.structured_traceback(etype,
1543 stb = self.InteractiveTB.structured_traceback(etype,
1502 value, tb, tb_offset=tb_offset)
1544 value, tb, tb_offset=tb_offset)
1503
1545
1504 if self.call_pdb:
1546 if self.call_pdb:
1505 # drop into debugger
1547 # drop into debugger
1506 self.debugger(force=True)
1548 self.debugger(force=True)
1507
1549
1508 # Actually show the traceback
1550 # Actually show the traceback
1509 self._showtraceback(etype, value, stb)
1551 self._showtraceback(etype, value, stb)
1510
1552
1511 except KeyboardInterrupt:
1553 except KeyboardInterrupt:
1512 self.write_err("\nKeyboardInterrupt\n")
1554 self.write_err("\nKeyboardInterrupt\n")
1513
1555
1514 def _showtraceback(self, etype, evalue, stb):
1556 def _showtraceback(self, etype, evalue, stb):
1515 """Actually show a traceback.
1557 """Actually show a traceback.
1516
1558
1517 Subclasses may override this method to put the traceback on a different
1559 Subclasses may override this method to put the traceback on a different
1518 place, like a side channel.
1560 place, like a side channel.
1519 """
1561 """
1520 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1562 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1521
1563
1522 def showsyntaxerror(self, filename=None):
1564 def showsyntaxerror(self, filename=None):
1523 """Display the syntax error that just occurred.
1565 """Display the syntax error that just occurred.
1524
1566
1525 This doesn't display a stack trace because there isn't one.
1567 This doesn't display a stack trace because there isn't one.
1526
1568
1527 If a filename is given, it is stuffed in the exception instead
1569 If a filename is given, it is stuffed in the exception instead
1528 of what was there before (because Python's parser always uses
1570 of what was there before (because Python's parser always uses
1529 "<string>" when reading from a string).
1571 "<string>" when reading from a string).
1530 """
1572 """
1531 etype, value, last_traceback = sys.exc_info()
1573 etype, value, last_traceback = sys.exc_info()
1532
1574
1533 # See note about these variables in showtraceback() above
1575 # See note about these variables in showtraceback() above
1534 sys.last_type = etype
1576 sys.last_type = etype
1535 sys.last_value = value
1577 sys.last_value = value
1536 sys.last_traceback = last_traceback
1578 sys.last_traceback = last_traceback
1537
1579
1538 if filename and etype is SyntaxError:
1580 if filename and etype is SyntaxError:
1539 # Work hard to stuff the correct filename in the exception
1581 # Work hard to stuff the correct filename in the exception
1540 try:
1582 try:
1541 msg, (dummy_filename, lineno, offset, line) = value
1583 msg, (dummy_filename, lineno, offset, line) = value
1542 except:
1584 except:
1543 # Not the format we expect; leave it alone
1585 # Not the format we expect; leave it alone
1544 pass
1586 pass
1545 else:
1587 else:
1546 # Stuff in the right filename
1588 # Stuff in the right filename
1547 try:
1589 try:
1548 # Assume SyntaxError is a class exception
1590 # Assume SyntaxError is a class exception
1549 value = SyntaxError(msg, (filename, lineno, offset, line))
1591 value = SyntaxError(msg, (filename, lineno, offset, line))
1550 except:
1592 except:
1551 # If that failed, assume SyntaxError is a string
1593 # If that failed, assume SyntaxError is a string
1552 value = msg, (filename, lineno, offset, line)
1594 value = msg, (filename, lineno, offset, line)
1553 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1595 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1554 self._showtraceback(etype, value, stb)
1596 self._showtraceback(etype, value, stb)
1555
1597
1556 #-------------------------------------------------------------------------
1598 #-------------------------------------------------------------------------
1557 # Things related to readline
1599 # Things related to readline
1558 #-------------------------------------------------------------------------
1600 #-------------------------------------------------------------------------
1559
1601
1560 def init_readline(self):
1602 def init_readline(self):
1561 """Command history completion/saving/reloading."""
1603 """Command history completion/saving/reloading."""
1562
1604
1563 if self.readline_use:
1605 if self.readline_use:
1564 import IPython.utils.rlineimpl as readline
1606 import IPython.utils.rlineimpl as readline
1565
1607
1566 self.rl_next_input = None
1608 self.rl_next_input = None
1567 self.rl_do_indent = False
1609 self.rl_do_indent = False
1568
1610
1569 if not self.readline_use or not readline.have_readline:
1611 if not self.readline_use or not readline.have_readline:
1570 self.has_readline = False
1612 self.has_readline = False
1571 self.readline = None
1613 self.readline = None
1572 # Set a number of methods that depend on readline to be no-op
1614 # Set a number of methods that depend on readline to be no-op
1573 self.set_readline_completer = no_op
1615 self.set_readline_completer = no_op
1574 self.set_custom_completer = no_op
1616 self.set_custom_completer = no_op
1575 self.set_completer_frame = no_op
1617 self.set_completer_frame = no_op
1576 warn('Readline services not available or not loaded.')
1618 warn('Readline services not available or not loaded.')
1577 else:
1619 else:
1578 self.has_readline = True
1620 self.has_readline = True
1579 self.readline = readline
1621 self.readline = readline
1580 sys.modules['readline'] = readline
1622 sys.modules['readline'] = readline
1581
1623
1582 # Platform-specific configuration
1624 # Platform-specific configuration
1583 if os.name == 'nt':
1625 if os.name == 'nt':
1584 # FIXME - check with Frederick to see if we can harmonize
1626 # FIXME - check with Frederick to see if we can harmonize
1585 # naming conventions with pyreadline to avoid this
1627 # naming conventions with pyreadline to avoid this
1586 # platform-dependent check
1628 # platform-dependent check
1587 self.readline_startup_hook = readline.set_pre_input_hook
1629 self.readline_startup_hook = readline.set_pre_input_hook
1588 else:
1630 else:
1589 self.readline_startup_hook = readline.set_startup_hook
1631 self.readline_startup_hook = readline.set_startup_hook
1590
1632
1591 # Load user's initrc file (readline config)
1633 # Load user's initrc file (readline config)
1592 # Or if libedit is used, load editrc.
1634 # Or if libedit is used, load editrc.
1593 inputrc_name = os.environ.get('INPUTRC')
1635 inputrc_name = os.environ.get('INPUTRC')
1594 if inputrc_name is None:
1636 if inputrc_name is None:
1595 home_dir = get_home_dir()
1637 home_dir = get_home_dir()
1596 if home_dir is not None:
1638 if home_dir is not None:
1597 inputrc_name = '.inputrc'
1639 inputrc_name = '.inputrc'
1598 if readline.uses_libedit:
1640 if readline.uses_libedit:
1599 inputrc_name = '.editrc'
1641 inputrc_name = '.editrc'
1600 inputrc_name = os.path.join(home_dir, inputrc_name)
1642 inputrc_name = os.path.join(home_dir, inputrc_name)
1601 if os.path.isfile(inputrc_name):
1643 if os.path.isfile(inputrc_name):
1602 try:
1644 try:
1603 readline.read_init_file(inputrc_name)
1645 readline.read_init_file(inputrc_name)
1604 except:
1646 except:
1605 warn('Problems reading readline initialization file <%s>'
1647 warn('Problems reading readline initialization file <%s>'
1606 % inputrc_name)
1648 % inputrc_name)
1607
1649
1608 # Configure readline according to user's prefs
1650 # Configure readline according to user's prefs
1609 # This is only done if GNU readline is being used. If libedit
1651 # This is only done if GNU readline is being used. If libedit
1610 # is being used (as on Leopard) the readline config is
1652 # is being used (as on Leopard) the readline config is
1611 # not run as the syntax for libedit is different.
1653 # not run as the syntax for libedit is different.
1612 if not readline.uses_libedit:
1654 if not readline.uses_libedit:
1613 for rlcommand in self.readline_parse_and_bind:
1655 for rlcommand in self.readline_parse_and_bind:
1614 #print "loading rl:",rlcommand # dbg
1656 #print "loading rl:",rlcommand # dbg
1615 readline.parse_and_bind(rlcommand)
1657 readline.parse_and_bind(rlcommand)
1616
1658
1617 # Remove some chars from the delimiters list. If we encounter
1659 # Remove some chars from the delimiters list. If we encounter
1618 # unicode chars, discard them.
1660 # unicode chars, discard them.
1619 delims = readline.get_completer_delims().encode("ascii", "ignore")
1661 delims = readline.get_completer_delims().encode("ascii", "ignore")
1620 delims = delims.translate(None, self.readline_remove_delims)
1662 delims = delims.translate(None, self.readline_remove_delims)
1621 delims = delims.replace(ESC_MAGIC, '')
1663 delims = delims.replace(ESC_MAGIC, '')
1622 readline.set_completer_delims(delims)
1664 readline.set_completer_delims(delims)
1623 # otherwise we end up with a monster history after a while:
1665 # otherwise we end up with a monster history after a while:
1624 readline.set_history_length(self.history_length)
1666 readline.set_history_length(self.history_length)
1625
1667
1626 self.refill_readline_hist()
1668 self.refill_readline_hist()
1627 self.readline_no_record = ReadlineNoRecord(self)
1669 self.readline_no_record = ReadlineNoRecord(self)
1628
1670
1629 # Configure auto-indent for all platforms
1671 # Configure auto-indent for all platforms
1630 self.set_autoindent(self.autoindent)
1672 self.set_autoindent(self.autoindent)
1631
1673
1632 def refill_readline_hist(self):
1674 def refill_readline_hist(self):
1633 # Load the last 1000 lines from history
1675 # Load the last 1000 lines from history
1634 self.readline.clear_history()
1676 self.readline.clear_history()
1635 stdin_encoding = sys.stdin.encoding or "utf-8"
1677 stdin_encoding = sys.stdin.encoding or "utf-8"
1636 for _, _, cell in self.history_manager.get_tail(1000,
1678 for _, _, cell in self.history_manager.get_tail(1000,
1637 include_latest=True):
1679 include_latest=True):
1638 if cell.strip(): # Ignore blank lines
1680 if cell.strip(): # Ignore blank lines
1639 for line in cell.splitlines():
1681 for line in cell.splitlines():
1640 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1682 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1641
1683
1642 def set_next_input(self, s):
1684 def set_next_input(self, s):
1643 """ Sets the 'default' input string for the next command line.
1685 """ Sets the 'default' input string for the next command line.
1644
1686
1645 Requires readline.
1687 Requires readline.
1646
1688
1647 Example:
1689 Example:
1648
1690
1649 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1691 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1650 [D:\ipython]|2> Hello Word_ # cursor is here
1692 [D:\ipython]|2> Hello Word_ # cursor is here
1651 """
1693 """
1652
1694
1653 self.rl_next_input = s
1695 self.rl_next_input = s
1654
1696
1655 # Maybe move this to the terminal subclass?
1697 # Maybe move this to the terminal subclass?
1656 def pre_readline(self):
1698 def pre_readline(self):
1657 """readline hook to be used at the start of each line.
1699 """readline hook to be used at the start of each line.
1658
1700
1659 Currently it handles auto-indent only."""
1701 Currently it handles auto-indent only."""
1660
1702
1661 if self.rl_do_indent:
1703 if self.rl_do_indent:
1662 self.readline.insert_text(self._indent_current_str())
1704 self.readline.insert_text(self._indent_current_str())
1663 if self.rl_next_input is not None:
1705 if self.rl_next_input is not None:
1664 self.readline.insert_text(self.rl_next_input)
1706 self.readline.insert_text(self.rl_next_input)
1665 self.rl_next_input = None
1707 self.rl_next_input = None
1666
1708
1667 def _indent_current_str(self):
1709 def _indent_current_str(self):
1668 """return the current level of indentation as a string"""
1710 """return the current level of indentation as a string"""
1669 return self.input_splitter.indent_spaces * ' '
1711 return self.input_splitter.indent_spaces * ' '
1670
1712
1671 #-------------------------------------------------------------------------
1713 #-------------------------------------------------------------------------
1672 # Things related to text completion
1714 # Things related to text completion
1673 #-------------------------------------------------------------------------
1715 #-------------------------------------------------------------------------
1674
1716
1675 def init_completer(self):
1717 def init_completer(self):
1676 """Initialize the completion machinery.
1718 """Initialize the completion machinery.
1677
1719
1678 This creates completion machinery that can be used by client code,
1720 This creates completion machinery that can be used by client code,
1679 either interactively in-process (typically triggered by the readline
1721 either interactively in-process (typically triggered by the readline
1680 library), programatically (such as in test suites) or out-of-prcess
1722 library), programatically (such as in test suites) or out-of-prcess
1681 (typically over the network by remote frontends).
1723 (typically over the network by remote frontends).
1682 """
1724 """
1683 from IPython.core.completer import IPCompleter
1725 from IPython.core.completer import IPCompleter
1684 from IPython.core.completerlib import (module_completer,
1726 from IPython.core.completerlib import (module_completer,
1685 magic_run_completer, cd_completer)
1727 magic_run_completer, cd_completer)
1686
1728
1687 self.Completer = IPCompleter(self,
1729 self.Completer = IPCompleter(self,
1688 self.user_ns,
1730 self.user_ns,
1689 self.user_global_ns,
1731 self.user_global_ns,
1690 self.readline_omit__names,
1732 self.readline_omit__names,
1691 self.alias_manager.alias_table,
1733 self.alias_manager.alias_table,
1692 self.has_readline)
1734 self.has_readline)
1693
1735
1694 # Add custom completers to the basic ones built into IPCompleter
1736 # Add custom completers to the basic ones built into IPCompleter
1695 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1737 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1696 self.strdispatchers['complete_command'] = sdisp
1738 self.strdispatchers['complete_command'] = sdisp
1697 self.Completer.custom_completers = sdisp
1739 self.Completer.custom_completers = sdisp
1698
1740
1699 self.set_hook('complete_command', module_completer, str_key = 'import')
1741 self.set_hook('complete_command', module_completer, str_key = 'import')
1700 self.set_hook('complete_command', module_completer, str_key = 'from')
1742 self.set_hook('complete_command', module_completer, str_key = 'from')
1701 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1743 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1702 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1744 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1703
1745
1704 # Only configure readline if we truly are using readline. IPython can
1746 # Only configure readline if we truly are using readline. IPython can
1705 # do tab-completion over the network, in GUIs, etc, where readline
1747 # do tab-completion over the network, in GUIs, etc, where readline
1706 # itself may be absent
1748 # itself may be absent
1707 if self.has_readline:
1749 if self.has_readline:
1708 self.set_readline_completer()
1750 self.set_readline_completer()
1709
1751
1710 def complete(self, text, line=None, cursor_pos=None):
1752 def complete(self, text, line=None, cursor_pos=None):
1711 """Return the completed text and a list of completions.
1753 """Return the completed text and a list of completions.
1712
1754
1713 Parameters
1755 Parameters
1714 ----------
1756 ----------
1715
1757
1716 text : string
1758 text : string
1717 A string of text to be completed on. It can be given as empty and
1759 A string of text to be completed on. It can be given as empty and
1718 instead a line/position pair are given. In this case, the
1760 instead a line/position pair are given. In this case, the
1719 completer itself will split the line like readline does.
1761 completer itself will split the line like readline does.
1720
1762
1721 line : string, optional
1763 line : string, optional
1722 The complete line that text is part of.
1764 The complete line that text is part of.
1723
1765
1724 cursor_pos : int, optional
1766 cursor_pos : int, optional
1725 The position of the cursor on the input line.
1767 The position of the cursor on the input line.
1726
1768
1727 Returns
1769 Returns
1728 -------
1770 -------
1729 text : string
1771 text : string
1730 The actual text that was completed.
1772 The actual text that was completed.
1731
1773
1732 matches : list
1774 matches : list
1733 A sorted list with all possible completions.
1775 A sorted list with all possible completions.
1734
1776
1735 The optional arguments allow the completion to take more context into
1777 The optional arguments allow the completion to take more context into
1736 account, and are part of the low-level completion API.
1778 account, and are part of the low-level completion API.
1737
1779
1738 This is a wrapper around the completion mechanism, similar to what
1780 This is a wrapper around the completion mechanism, similar to what
1739 readline does at the command line when the TAB key is hit. By
1781 readline does at the command line when the TAB key is hit. By
1740 exposing it as a method, it can be used by other non-readline
1782 exposing it as a method, it can be used by other non-readline
1741 environments (such as GUIs) for text completion.
1783 environments (such as GUIs) for text completion.
1742
1784
1743 Simple usage example:
1785 Simple usage example:
1744
1786
1745 In [1]: x = 'hello'
1787 In [1]: x = 'hello'
1746
1788
1747 In [2]: _ip.complete('x.l')
1789 In [2]: _ip.complete('x.l')
1748 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1790 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1749 """
1791 """
1750
1792
1751 # Inject names into __builtin__ so we can complete on the added names.
1793 # Inject names into __builtin__ so we can complete on the added names.
1752 with self.builtin_trap:
1794 with self.builtin_trap:
1753 return self.Completer.complete(text, line, cursor_pos)
1795 return self.Completer.complete(text, line, cursor_pos)
1754
1796
1755 def set_custom_completer(self, completer, pos=0):
1797 def set_custom_completer(self, completer, pos=0):
1756 """Adds a new custom completer function.
1798 """Adds a new custom completer function.
1757
1799
1758 The position argument (defaults to 0) is the index in the completers
1800 The position argument (defaults to 0) is the index in the completers
1759 list where you want the completer to be inserted."""
1801 list where you want the completer to be inserted."""
1760
1802
1761 newcomp = types.MethodType(completer,self.Completer)
1803 newcomp = types.MethodType(completer,self.Completer)
1762 self.Completer.matchers.insert(pos,newcomp)
1804 self.Completer.matchers.insert(pos,newcomp)
1763
1805
1764 def set_readline_completer(self):
1806 def set_readline_completer(self):
1765 """Reset readline's completer to be our own."""
1807 """Reset readline's completer to be our own."""
1766 self.readline.set_completer(self.Completer.rlcomplete)
1808 self.readline.set_completer(self.Completer.rlcomplete)
1767
1809
1768 def set_completer_frame(self, frame=None):
1810 def set_completer_frame(self, frame=None):
1769 """Set the frame of the completer."""
1811 """Set the frame of the completer."""
1770 if frame:
1812 if frame:
1771 self.Completer.namespace = frame.f_locals
1813 self.Completer.namespace = frame.f_locals
1772 self.Completer.global_namespace = frame.f_globals
1814 self.Completer.global_namespace = frame.f_globals
1773 else:
1815 else:
1774 self.Completer.namespace = self.user_ns
1816 self.Completer.namespace = self.user_ns
1775 self.Completer.global_namespace = self.user_global_ns
1817 self.Completer.global_namespace = self.user_global_ns
1776
1818
1777 #-------------------------------------------------------------------------
1819 #-------------------------------------------------------------------------
1778 # Things related to magics
1820 # Things related to magics
1779 #-------------------------------------------------------------------------
1821 #-------------------------------------------------------------------------
1780
1822
1781 def init_magics(self):
1823 def init_magics(self):
1782 # FIXME: Move the color initialization to the DisplayHook, which
1824 # FIXME: Move the color initialization to the DisplayHook, which
1783 # should be split into a prompt manager and displayhook. We probably
1825 # should be split into a prompt manager and displayhook. We probably
1784 # even need a centralize colors management object.
1826 # even need a centralize colors management object.
1785 self.magic_colors(self.colors)
1827 self.magic_colors(self.colors)
1786 # History was moved to a separate module
1828 # History was moved to a separate module
1787 from . import history
1829 from . import history
1788 history.init_ipython(self)
1830 history.init_ipython(self)
1789
1831
1790 def magic(self,arg_s):
1832 def magic(self,arg_s):
1791 """Call a magic function by name.
1833 """Call a magic function by name.
1792
1834
1793 Input: a string containing the name of the magic function to call and
1835 Input: a string containing the name of the magic function to call and
1794 any additional arguments to be passed to the magic.
1836 any additional arguments to be passed to the magic.
1795
1837
1796 magic('name -opt foo bar') is equivalent to typing at the ipython
1838 magic('name -opt foo bar') is equivalent to typing at the ipython
1797 prompt:
1839 prompt:
1798
1840
1799 In[1]: %name -opt foo bar
1841 In[1]: %name -opt foo bar
1800
1842
1801 To call a magic without arguments, simply use magic('name').
1843 To call a magic without arguments, simply use magic('name').
1802
1844
1803 This provides a proper Python function to call IPython's magics in any
1845 This provides a proper Python function to call IPython's magics in any
1804 valid Python code you can type at the interpreter, including loops and
1846 valid Python code you can type at the interpreter, including loops and
1805 compound statements.
1847 compound statements.
1806 """
1848 """
1807 args = arg_s.split(' ',1)
1849 args = arg_s.split(' ',1)
1808 magic_name = args[0]
1850 magic_name = args[0]
1809 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1851 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1810
1852
1811 try:
1853 try:
1812 magic_args = args[1]
1854 magic_args = args[1]
1813 except IndexError:
1855 except IndexError:
1814 magic_args = ''
1856 magic_args = ''
1815 fn = getattr(self,'magic_'+magic_name,None)
1857 fn = getattr(self,'magic_'+magic_name,None)
1816 if fn is None:
1858 if fn is None:
1817 error("Magic function `%s` not found." % magic_name)
1859 error("Magic function `%s` not found." % magic_name)
1818 else:
1860 else:
1819 magic_args = self.var_expand(magic_args,1)
1861 magic_args = self.var_expand(magic_args,1)
1820 # Grab local namespace if we need it:
1862 # Grab local namespace if we need it:
1821 if getattr(fn, "needs_local_scope", False):
1863 if getattr(fn, "needs_local_scope", False):
1822 self._magic_locals = sys._getframe(1).f_locals
1864 self._magic_locals = sys._getframe(1).f_locals
1823 with self.builtin_trap:
1865 with self.builtin_trap:
1824 result = fn(magic_args)
1866 result = fn(magic_args)
1825 # Ensure we're not keeping object references around:
1867 # Ensure we're not keeping object references around:
1826 self._magic_locals = {}
1868 self._magic_locals = {}
1827 return result
1869 return result
1828
1870
1829 def define_magic(self, magicname, func):
1871 def define_magic(self, magicname, func):
1830 """Expose own function as magic function for ipython
1872 """Expose own function as magic function for ipython
1831
1873
1832 def foo_impl(self,parameter_s=''):
1874 def foo_impl(self,parameter_s=''):
1833 'My very own magic!. (Use docstrings, IPython reads them).'
1875 'My very own magic!. (Use docstrings, IPython reads them).'
1834 print 'Magic function. Passed parameter is between < >:'
1876 print 'Magic function. Passed parameter is between < >:'
1835 print '<%s>' % parameter_s
1877 print '<%s>' % parameter_s
1836 print 'The self object is:',self
1878 print 'The self object is:',self
1837
1879
1838 self.define_magic('foo',foo_impl)
1880 self.define_magic('foo',foo_impl)
1839 """
1881 """
1840
1882
1841 import new
1883 import new
1842 im = types.MethodType(func,self)
1884 im = types.MethodType(func,self)
1843 old = getattr(self, "magic_" + magicname, None)
1885 old = getattr(self, "magic_" + magicname, None)
1844 setattr(self, "magic_" + magicname, im)
1886 setattr(self, "magic_" + magicname, im)
1845 return old
1887 return old
1846
1888
1847 #-------------------------------------------------------------------------
1889 #-------------------------------------------------------------------------
1848 # Things related to macros
1890 # Things related to macros
1849 #-------------------------------------------------------------------------
1891 #-------------------------------------------------------------------------
1850
1892
1851 def define_macro(self, name, themacro):
1893 def define_macro(self, name, themacro):
1852 """Define a new macro
1894 """Define a new macro
1853
1895
1854 Parameters
1896 Parameters
1855 ----------
1897 ----------
1856 name : str
1898 name : str
1857 The name of the macro.
1899 The name of the macro.
1858 themacro : str or Macro
1900 themacro : str or Macro
1859 The action to do upon invoking the macro. If a string, a new
1901 The action to do upon invoking the macro. If a string, a new
1860 Macro object is created by passing the string to it.
1902 Macro object is created by passing the string to it.
1861 """
1903 """
1862
1904
1863 from IPython.core import macro
1905 from IPython.core import macro
1864
1906
1865 if isinstance(themacro, basestring):
1907 if isinstance(themacro, basestring):
1866 themacro = macro.Macro(themacro)
1908 themacro = macro.Macro(themacro)
1867 if not isinstance(themacro, macro.Macro):
1909 if not isinstance(themacro, macro.Macro):
1868 raise ValueError('A macro must be a string or a Macro instance.')
1910 raise ValueError('A macro must be a string or a Macro instance.')
1869 self.user_ns[name] = themacro
1911 self.user_ns[name] = themacro
1870
1912
1871 #-------------------------------------------------------------------------
1913 #-------------------------------------------------------------------------
1872 # Things related to the running of system commands
1914 # Things related to the running of system commands
1873 #-------------------------------------------------------------------------
1915 #-------------------------------------------------------------------------
1874
1916
1875 def system_piped(self, cmd):
1917 def system_piped(self, cmd):
1876 """Call the given cmd in a subprocess, piping stdout/err
1918 """Call the given cmd in a subprocess, piping stdout/err
1877
1919
1878 Parameters
1920 Parameters
1879 ----------
1921 ----------
1880 cmd : str
1922 cmd : str
1881 Command to execute (can not end in '&', as background processes are
1923 Command to execute (can not end in '&', as background processes are
1882 not supported. Should not be a command that expects input
1924 not supported. Should not be a command that expects input
1883 other than simple text.
1925 other than simple text.
1884 """
1926 """
1885 if cmd.rstrip().endswith('&'):
1927 if cmd.rstrip().endswith('&'):
1886 # this is *far* from a rigorous test
1928 # this is *far* from a rigorous test
1887 # We do not support backgrounding processes because we either use
1929 # We do not support backgrounding processes because we either use
1888 # pexpect or pipes to read from. Users can always just call
1930 # pexpect or pipes to read from. Users can always just call
1889 # os.system() or use ip.system=ip.system_raw
1931 # os.system() or use ip.system=ip.system_raw
1890 # if they really want a background process.
1932 # if they really want a background process.
1891 raise OSError("Background processes not supported.")
1933 raise OSError("Background processes not supported.")
1892
1934
1893 # we explicitly do NOT return the subprocess status code, because
1935 # we explicitly do NOT return the subprocess status code, because
1894 # a non-None value would trigger :func:`sys.displayhook` calls.
1936 # a non-None value would trigger :func:`sys.displayhook` calls.
1895 # Instead, we store the exit_code in user_ns.
1937 # Instead, we store the exit_code in user_ns.
1896 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1938 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
1897
1939
1898 def system_raw(self, cmd):
1940 def system_raw(self, cmd):
1899 """Call the given cmd in a subprocess using os.system
1941 """Call the given cmd in a subprocess using os.system
1900
1942
1901 Parameters
1943 Parameters
1902 ----------
1944 ----------
1903 cmd : str
1945 cmd : str
1904 Command to execute.
1946 Command to execute.
1905 """
1947 """
1906 # We explicitly do NOT return the subprocess status code, because
1948 # We explicitly do NOT return the subprocess status code, because
1907 # a non-None value would trigger :func:`sys.displayhook` calls.
1949 # a non-None value would trigger :func:`sys.displayhook` calls.
1908 # Instead, we store the exit_code in user_ns.
1950 # Instead, we store the exit_code in user_ns.
1909 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1951 self.user_ns['_exit_code'] = os.system(self.var_expand(cmd, depth=2))
1910
1952
1911 # use piped system by default, because it is better behaved
1953 # use piped system by default, because it is better behaved
1912 system = system_piped
1954 system = system_piped
1913
1955
1914 def getoutput(self, cmd, split=True):
1956 def getoutput(self, cmd, split=True):
1915 """Get output (possibly including stderr) from a subprocess.
1957 """Get output (possibly including stderr) from a subprocess.
1916
1958
1917 Parameters
1959 Parameters
1918 ----------
1960 ----------
1919 cmd : str
1961 cmd : str
1920 Command to execute (can not end in '&', as background processes are
1962 Command to execute (can not end in '&', as background processes are
1921 not supported.
1963 not supported.
1922 split : bool, optional
1964 split : bool, optional
1923
1965
1924 If True, split the output into an IPython SList. Otherwise, an
1966 If True, split the output into an IPython SList. Otherwise, an
1925 IPython LSString is returned. These are objects similar to normal
1967 IPython LSString is returned. These are objects similar to normal
1926 lists and strings, with a few convenience attributes for easier
1968 lists and strings, with a few convenience attributes for easier
1927 manipulation of line-based output. You can use '?' on them for
1969 manipulation of line-based output. You can use '?' on them for
1928 details.
1970 details.
1929 """
1971 """
1930 if cmd.rstrip().endswith('&'):
1972 if cmd.rstrip().endswith('&'):
1931 # this is *far* from a rigorous test
1973 # this is *far* from a rigorous test
1932 raise OSError("Background processes not supported.")
1974 raise OSError("Background processes not supported.")
1933 out = getoutput(self.var_expand(cmd, depth=2))
1975 out = getoutput(self.var_expand(cmd, depth=2))
1934 if split:
1976 if split:
1935 out = SList(out.splitlines())
1977 out = SList(out.splitlines())
1936 else:
1978 else:
1937 out = LSString(out)
1979 out = LSString(out)
1938 return out
1980 return out
1939
1981
1940 #-------------------------------------------------------------------------
1982 #-------------------------------------------------------------------------
1941 # Things related to aliases
1983 # Things related to aliases
1942 #-------------------------------------------------------------------------
1984 #-------------------------------------------------------------------------
1943
1985
1944 def init_alias(self):
1986 def init_alias(self):
1945 self.alias_manager = AliasManager(shell=self, config=self.config)
1987 self.alias_manager = AliasManager(shell=self, config=self.config)
1946 self.ns_table['alias'] = self.alias_manager.alias_table,
1988 self.ns_table['alias'] = self.alias_manager.alias_table,
1947
1989
1948 #-------------------------------------------------------------------------
1990 #-------------------------------------------------------------------------
1949 # Things related to extensions and plugins
1991 # Things related to extensions and plugins
1950 #-------------------------------------------------------------------------
1992 #-------------------------------------------------------------------------
1951
1993
1952 def init_extension_manager(self):
1994 def init_extension_manager(self):
1953 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1995 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1954
1996
1955 def init_plugin_manager(self):
1997 def init_plugin_manager(self):
1956 self.plugin_manager = PluginManager(config=self.config)
1998 self.plugin_manager = PluginManager(config=self.config)
1957
1999
1958 #-------------------------------------------------------------------------
2000 #-------------------------------------------------------------------------
1959 # Things related to payloads
2001 # Things related to payloads
1960 #-------------------------------------------------------------------------
2002 #-------------------------------------------------------------------------
1961
2003
1962 def init_payload(self):
2004 def init_payload(self):
1963 self.payload_manager = PayloadManager(config=self.config)
2005 self.payload_manager = PayloadManager(config=self.config)
1964
2006
1965 #-------------------------------------------------------------------------
2007 #-------------------------------------------------------------------------
1966 # Things related to the prefilter
2008 # Things related to the prefilter
1967 #-------------------------------------------------------------------------
2009 #-------------------------------------------------------------------------
1968
2010
1969 def init_prefilter(self):
2011 def init_prefilter(self):
1970 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2012 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1971 # Ultimately this will be refactored in the new interpreter code, but
2013 # Ultimately this will be refactored in the new interpreter code, but
1972 # for now, we should expose the main prefilter method (there's legacy
2014 # for now, we should expose the main prefilter method (there's legacy
1973 # code out there that may rely on this).
2015 # code out there that may rely on this).
1974 self.prefilter = self.prefilter_manager.prefilter_lines
2016 self.prefilter = self.prefilter_manager.prefilter_lines
1975
2017
1976 def auto_rewrite_input(self, cmd):
2018 def auto_rewrite_input(self, cmd):
1977 """Print to the screen the rewritten form of the user's command.
2019 """Print to the screen the rewritten form of the user's command.
1978
2020
1979 This shows visual feedback by rewriting input lines that cause
2021 This shows visual feedback by rewriting input lines that cause
1980 automatic calling to kick in, like::
2022 automatic calling to kick in, like::
1981
2023
1982 /f x
2024 /f x
1983
2025
1984 into::
2026 into::
1985
2027
1986 ------> f(x)
2028 ------> f(x)
1987
2029
1988 after the user's input prompt. This helps the user understand that the
2030 after the user's input prompt. This helps the user understand that the
1989 input line was transformed automatically by IPython.
2031 input line was transformed automatically by IPython.
1990 """
2032 """
1991 rw = self.displayhook.prompt1.auto_rewrite() + cmd
2033 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1992
2034
1993 try:
2035 try:
1994 # plain ascii works better w/ pyreadline, on some machines, so
2036 # plain ascii works better w/ pyreadline, on some machines, so
1995 # we use it and only print uncolored rewrite if we have unicode
2037 # we use it and only print uncolored rewrite if we have unicode
1996 rw = str(rw)
2038 rw = str(rw)
1997 print >> io.stdout, rw
2039 print >> io.stdout, rw
1998 except UnicodeEncodeError:
2040 except UnicodeEncodeError:
1999 print "------> " + cmd
2041 print "------> " + cmd
2000
2042
2001 #-------------------------------------------------------------------------
2043 #-------------------------------------------------------------------------
2002 # Things related to extracting values/expressions from kernel and user_ns
2044 # Things related to extracting values/expressions from kernel and user_ns
2003 #-------------------------------------------------------------------------
2045 #-------------------------------------------------------------------------
2004
2046
2005 def _simple_error(self):
2047 def _simple_error(self):
2006 etype, value = sys.exc_info()[:2]
2048 etype, value = sys.exc_info()[:2]
2007 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2049 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2008
2050
2009 def user_variables(self, names):
2051 def user_variables(self, names):
2010 """Get a list of variable names from the user's namespace.
2052 """Get a list of variable names from the user's namespace.
2011
2053
2012 Parameters
2054 Parameters
2013 ----------
2055 ----------
2014 names : list of strings
2056 names : list of strings
2015 A list of names of variables to be read from the user namespace.
2057 A list of names of variables to be read from the user namespace.
2016
2058
2017 Returns
2059 Returns
2018 -------
2060 -------
2019 A dict, keyed by the input names and with the repr() of each value.
2061 A dict, keyed by the input names and with the repr() of each value.
2020 """
2062 """
2021 out = {}
2063 out = {}
2022 user_ns = self.user_ns
2064 user_ns = self.user_ns
2023 for varname in names:
2065 for varname in names:
2024 try:
2066 try:
2025 value = repr(user_ns[varname])
2067 value = repr(user_ns[varname])
2026 except:
2068 except:
2027 value = self._simple_error()
2069 value = self._simple_error()
2028 out[varname] = value
2070 out[varname] = value
2029 return out
2071 return out
2030
2072
2031 def user_expressions(self, expressions):
2073 def user_expressions(self, expressions):
2032 """Evaluate a dict of expressions in the user's namespace.
2074 """Evaluate a dict of expressions in the user's namespace.
2033
2075
2034 Parameters
2076 Parameters
2035 ----------
2077 ----------
2036 expressions : dict
2078 expressions : dict
2037 A dict with string keys and string values. The expression values
2079 A dict with string keys and string values. The expression values
2038 should be valid Python expressions, each of which will be evaluated
2080 should be valid Python expressions, each of which will be evaluated
2039 in the user namespace.
2081 in the user namespace.
2040
2082
2041 Returns
2083 Returns
2042 -------
2084 -------
2043 A dict, keyed like the input expressions dict, with the repr() of each
2085 A dict, keyed like the input expressions dict, with the repr() of each
2044 value.
2086 value.
2045 """
2087 """
2046 out = {}
2088 out = {}
2047 user_ns = self.user_ns
2089 user_ns = self.user_ns
2048 global_ns = self.user_global_ns
2090 global_ns = self.user_global_ns
2049 for key, expr in expressions.iteritems():
2091 for key, expr in expressions.iteritems():
2050 try:
2092 try:
2051 value = repr(eval(expr, global_ns, user_ns))
2093 value = repr(eval(expr, global_ns, user_ns))
2052 except:
2094 except:
2053 value = self._simple_error()
2095 value = self._simple_error()
2054 out[key] = value
2096 out[key] = value
2055 return out
2097 return out
2056
2098
2057 #-------------------------------------------------------------------------
2099 #-------------------------------------------------------------------------
2058 # Things related to the running of code
2100 # Things related to the running of code
2059 #-------------------------------------------------------------------------
2101 #-------------------------------------------------------------------------
2060
2102
2061 def ex(self, cmd):
2103 def ex(self, cmd):
2062 """Execute a normal python statement in user namespace."""
2104 """Execute a normal python statement in user namespace."""
2063 with self.builtin_trap:
2105 with self.builtin_trap:
2064 exec cmd in self.user_global_ns, self.user_ns
2106 exec cmd in self.user_global_ns, self.user_ns
2065
2107
2066 def ev(self, expr):
2108 def ev(self, expr):
2067 """Evaluate python expression expr in user namespace.
2109 """Evaluate python expression expr in user namespace.
2068
2110
2069 Returns the result of evaluation
2111 Returns the result of evaluation
2070 """
2112 """
2071 with self.builtin_trap:
2113 with self.builtin_trap:
2072 return eval(expr, self.user_global_ns, self.user_ns)
2114 return eval(expr, self.user_global_ns, self.user_ns)
2073
2115
2074 def safe_execfile(self, fname, *where, **kw):
2116 def safe_execfile(self, fname, *where, **kw):
2075 """A safe version of the builtin execfile().
2117 """A safe version of the builtin execfile().
2076
2118
2077 This version will never throw an exception, but instead print
2119 This version will never throw an exception, but instead print
2078 helpful error messages to the screen. This only works on pure
2120 helpful error messages to the screen. This only works on pure
2079 Python files with the .py extension.
2121 Python files with the .py extension.
2080
2122
2081 Parameters
2123 Parameters
2082 ----------
2124 ----------
2083 fname : string
2125 fname : string
2084 The name of the file to be executed.
2126 The name of the file to be executed.
2085 where : tuple
2127 where : tuple
2086 One or two namespaces, passed to execfile() as (globals,locals).
2128 One or two namespaces, passed to execfile() as (globals,locals).
2087 If only one is given, it is passed as both.
2129 If only one is given, it is passed as both.
2088 exit_ignore : bool (False)
2130 exit_ignore : bool (False)
2089 If True, then silence SystemExit for non-zero status (it is always
2131 If True, then silence SystemExit for non-zero status (it is always
2090 silenced for zero status, as it is so common).
2132 silenced for zero status, as it is so common).
2091 """
2133 """
2092 kw.setdefault('exit_ignore', False)
2134 kw.setdefault('exit_ignore', False)
2093
2135
2094 fname = os.path.abspath(os.path.expanduser(fname))
2136 fname = os.path.abspath(os.path.expanduser(fname))
2095 # Make sure we have a .py file
2137 # Make sure we have a .py file
2096 if not fname.endswith('.py'):
2138 if not fname.endswith('.py'):
2097 warn('File must end with .py to be run using execfile: <%s>' % fname)
2139 warn('File must end with .py to be run using execfile: <%s>' % fname)
2098
2140
2099 # Make sure we can open the file
2141 # Make sure we can open the file
2100 try:
2142 try:
2101 with open(fname) as thefile:
2143 with open(fname) as thefile:
2102 pass
2144 pass
2103 except:
2145 except:
2104 warn('Could not open file <%s> for safe execution.' % fname)
2146 warn('Could not open file <%s> for safe execution.' % fname)
2105 return
2147 return
2106
2148
2107 # Find things also in current directory. This is needed to mimic the
2149 # Find things also in current directory. This is needed to mimic the
2108 # behavior of running a script from the system command line, where
2150 # behavior of running a script from the system command line, where
2109 # Python inserts the script's directory into sys.path
2151 # Python inserts the script's directory into sys.path
2110 dname = os.path.dirname(fname)
2152 dname = os.path.dirname(fname)
2111
2153
2112 if isinstance(fname, unicode):
2154 if isinstance(fname, unicode):
2113 # execfile uses default encoding instead of filesystem encoding
2155 # execfile uses default encoding instead of filesystem encoding
2114 # so unicode filenames will fail
2156 # so unicode filenames will fail
2115 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2157 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2116
2158
2117 with prepended_to_syspath(dname):
2159 with prepended_to_syspath(dname):
2118 try:
2160 try:
2119 execfile(fname,*where)
2161 execfile(fname,*where)
2120 except SystemExit, status:
2162 except SystemExit, status:
2121 # If the call was made with 0 or None exit status (sys.exit(0)
2163 # If the call was made with 0 or None exit status (sys.exit(0)
2122 # or sys.exit() ), don't bother showing a traceback, as both of
2164 # or sys.exit() ), don't bother showing a traceback, as both of
2123 # these are considered normal by the OS:
2165 # these are considered normal by the OS:
2124 # > python -c'import sys;sys.exit(0)'; echo $?
2166 # > python -c'import sys;sys.exit(0)'; echo $?
2125 # 0
2167 # 0
2126 # > python -c'import sys;sys.exit()'; echo $?
2168 # > python -c'import sys;sys.exit()'; echo $?
2127 # 0
2169 # 0
2128 # For other exit status, we show the exception unless
2170 # For other exit status, we show the exception unless
2129 # explicitly silenced, but only in short form.
2171 # explicitly silenced, but only in short form.
2130 if status.code not in (0, None) and not kw['exit_ignore']:
2172 if status.code not in (0, None) and not kw['exit_ignore']:
2131 self.showtraceback(exception_only=True)
2173 self.showtraceback(exception_only=True)
2132 except:
2174 except:
2133 self.showtraceback()
2175 self.showtraceback()
2134
2176
2135 def safe_execfile_ipy(self, fname):
2177 def safe_execfile_ipy(self, fname):
2136 """Like safe_execfile, but for .ipy files with IPython syntax.
2178 """Like safe_execfile, but for .ipy files with IPython syntax.
2137
2179
2138 Parameters
2180 Parameters
2139 ----------
2181 ----------
2140 fname : str
2182 fname : str
2141 The name of the file to execute. The filename must have a
2183 The name of the file to execute. The filename must have a
2142 .ipy extension.
2184 .ipy extension.
2143 """
2185 """
2144 fname = os.path.abspath(os.path.expanduser(fname))
2186 fname = os.path.abspath(os.path.expanduser(fname))
2145
2187
2146 # Make sure we have a .py file
2188 # Make sure we have a .py file
2147 if not fname.endswith('.ipy'):
2189 if not fname.endswith('.ipy'):
2148 warn('File must end with .py to be run using execfile: <%s>' % fname)
2190 warn('File must end with .py to be run using execfile: <%s>' % fname)
2149
2191
2150 # Make sure we can open the file
2192 # Make sure we can open the file
2151 try:
2193 try:
2152 with open(fname) as thefile:
2194 with open(fname) as thefile:
2153 pass
2195 pass
2154 except:
2196 except:
2155 warn('Could not open file <%s> for safe execution.' % fname)
2197 warn('Could not open file <%s> for safe execution.' % fname)
2156 return
2198 return
2157
2199
2158 # Find things also in current directory. This is needed to mimic the
2200 # Find things also in current directory. This is needed to mimic the
2159 # behavior of running a script from the system command line, where
2201 # behavior of running a script from the system command line, where
2160 # Python inserts the script's directory into sys.path
2202 # Python inserts the script's directory into sys.path
2161 dname = os.path.dirname(fname)
2203 dname = os.path.dirname(fname)
2162
2204
2163 with prepended_to_syspath(dname):
2205 with prepended_to_syspath(dname):
2164 try:
2206 try:
2165 with open(fname) as thefile:
2207 with open(fname) as thefile:
2166 # self.run_cell currently captures all exceptions
2208 # self.run_cell currently captures all exceptions
2167 # raised in user code. It would be nice if there were
2209 # raised in user code. It would be nice if there were
2168 # versions of runlines, execfile that did raise, so
2210 # versions of runlines, execfile that did raise, so
2169 # we could catch the errors.
2211 # we could catch the errors.
2170 self.run_cell(thefile.read(), store_history=False)
2212 self.run_cell(thefile.read(), store_history=False)
2171 except:
2213 except:
2172 self.showtraceback()
2214 self.showtraceback()
2173 warn('Unknown failure executing file: <%s>' % fname)
2215 warn('Unknown failure executing file: <%s>' % fname)
2174
2216
2175 def run_cell(self, raw_cell, store_history=True):
2217 def run_cell(self, raw_cell, store_history=True):
2176 """Run a complete IPython cell.
2218 """Run a complete IPython cell.
2177
2219
2178 Parameters
2220 Parameters
2179 ----------
2221 ----------
2180 raw_cell : str
2222 raw_cell : str
2181 The code (including IPython code such as %magic functions) to run.
2223 The code (including IPython code such as %magic functions) to run.
2182 store_history : bool
2224 store_history : bool
2183 If True, the raw and translated cell will be stored in IPython's
2225 If True, the raw and translated cell will be stored in IPython's
2184 history. For user code calling back into IPython's machinery, this
2226 history. For user code calling back into IPython's machinery, this
2185 should be set to False.
2227 should be set to False.
2186 """
2228 """
2187 if (not raw_cell) or raw_cell.isspace():
2229 if (not raw_cell) or raw_cell.isspace():
2188 return
2230 return
2189
2231
2190 for line in raw_cell.splitlines():
2232 for line in raw_cell.splitlines():
2191 self.input_splitter.push(line)
2233 self.input_splitter.push(line)
2192 cell = self.input_splitter.source_reset()
2234 cell = self.input_splitter.source_reset()
2193
2235
2194 with self.builtin_trap:
2236 with self.builtin_trap:
2195 prefilter_failed = False
2237 prefilter_failed = False
2196 if len(cell.splitlines()) == 1:
2238 if len(cell.splitlines()) == 1:
2197 try:
2239 try:
2198 # use prefilter_lines to handle trailing newlines
2240 # use prefilter_lines to handle trailing newlines
2199 # restore trailing newline for ast.parse
2241 # restore trailing newline for ast.parse
2200 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2242 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2201 except AliasError as e:
2243 except AliasError as e:
2202 error(e)
2244 error(e)
2203 prefilter_failed=True
2245 prefilter_failed=True
2204 except Exception:
2246 except Exception:
2205 # don't allow prefilter errors to crash IPython
2247 # don't allow prefilter errors to crash IPython
2206 self.showtraceback()
2248 self.showtraceback()
2207 prefilter_failed = True
2249 prefilter_failed = True
2208
2250
2209 # Store raw and processed history
2251 # Store raw and processed history
2210 if store_history:
2252 if store_history:
2211 self.history_manager.store_inputs(self.execution_count,
2253 self.history_manager.store_inputs(self.execution_count,
2212 cell, raw_cell)
2254 cell, raw_cell)
2213
2255
2214 self.logger.log(cell, raw_cell)
2256 self.logger.log(cell, raw_cell)
2215
2257
2216 if not prefilter_failed:
2258 if not prefilter_failed:
2217 # don't run if prefilter failed
2259 # don't run if prefilter failed
2218 cell_name = self.compile.cache(cell, self.execution_count)
2260 cell_name = self.compile.cache(cell, self.execution_count)
2219
2261
2220 with self.display_trap:
2262 with self.display_trap:
2221 try:
2263 try:
2222 code_ast = ast.parse(cell, filename=cell_name)
2264 code_ast = ast.parse(cell, filename=cell_name)
2223 except (OverflowError, SyntaxError, ValueError, TypeError,
2265 except (OverflowError, SyntaxError, ValueError, TypeError,
2224 MemoryError):
2266 MemoryError):
2225 self.showsyntaxerror()
2267 self.showsyntaxerror()
2226 self.execution_count += 1
2268 self.execution_count += 1
2227 return None
2269 return None
2228
2270
2229 self.run_ast_nodes(code_ast.body, cell_name,
2271 self.run_ast_nodes(code_ast.body, cell_name,
2230 interactivity="last_expr")
2272 interactivity="last_expr")
2231
2273
2232 # Execute any registered post-execution functions.
2274 # Execute any registered post-execution functions.
2233 for func, status in self._post_execute.iteritems():
2275 for func, status in self._post_execute.iteritems():
2234 if not status:
2276 if not status:
2235 continue
2277 continue
2236 try:
2278 try:
2237 func()
2279 func()
2238 except:
2280 except:
2239 self.showtraceback()
2281 self.showtraceback()
2240 # Deactivate failing function
2282 # Deactivate failing function
2241 self._post_execute[func] = False
2283 self._post_execute[func] = False
2242
2284
2243 if store_history:
2285 if store_history:
2244 # Write output to the database. Does nothing unless
2286 # Write output to the database. Does nothing unless
2245 # history output logging is enabled.
2287 # history output logging is enabled.
2246 self.history_manager.store_output(self.execution_count)
2288 self.history_manager.store_output(self.execution_count)
2247 # Each cell is a *single* input, regardless of how many lines it has
2289 # Each cell is a *single* input, regardless of how many lines it has
2248 self.execution_count += 1
2290 self.execution_count += 1
2249
2291
2250 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2292 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2251 """Run a sequence of AST nodes. The execution mode depends on the
2293 """Run a sequence of AST nodes. The execution mode depends on the
2252 interactivity parameter.
2294 interactivity parameter.
2253
2295
2254 Parameters
2296 Parameters
2255 ----------
2297 ----------
2256 nodelist : list
2298 nodelist : list
2257 A sequence of AST nodes to run.
2299 A sequence of AST nodes to run.
2258 cell_name : str
2300 cell_name : str
2259 Will be passed to the compiler as the filename of the cell. Typically
2301 Will be passed to the compiler as the filename of the cell. Typically
2260 the value returned by ip.compile.cache(cell).
2302 the value returned by ip.compile.cache(cell).
2261 interactivity : str
2303 interactivity : str
2262 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2304 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2263 run interactively (displaying output from expressions). 'last_expr'
2305 run interactively (displaying output from expressions). 'last_expr'
2264 will run the last node interactively only if it is an expression (i.e.
2306 will run the last node interactively only if it is an expression (i.e.
2265 expressions in loops or other blocks are not displayed. Other values
2307 expressions in loops or other blocks are not displayed. Other values
2266 for this parameter will raise a ValueError.
2308 for this parameter will raise a ValueError.
2267 """
2309 """
2268 if not nodelist:
2310 if not nodelist:
2269 return
2311 return
2270
2312
2271 if interactivity == 'last_expr':
2313 if interactivity == 'last_expr':
2272 if isinstance(nodelist[-1], ast.Expr):
2314 if isinstance(nodelist[-1], ast.Expr):
2273 interactivity = "last"
2315 interactivity = "last"
2274 else:
2316 else:
2275 interactivity = "none"
2317 interactivity = "none"
2276
2318
2277 if interactivity == 'none':
2319 if interactivity == 'none':
2278 to_run_exec, to_run_interactive = nodelist, []
2320 to_run_exec, to_run_interactive = nodelist, []
2279 elif interactivity == 'last':
2321 elif interactivity == 'last':
2280 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2322 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2281 elif interactivity == 'all':
2323 elif interactivity == 'all':
2282 to_run_exec, to_run_interactive = [], nodelist
2324 to_run_exec, to_run_interactive = [], nodelist
2283 else:
2325 else:
2284 raise ValueError("Interactivity was %r" % interactivity)
2326 raise ValueError("Interactivity was %r" % interactivity)
2285
2327
2286 exec_count = self.execution_count
2328 exec_count = self.execution_count
2287
2329
2288 for i, node in enumerate(to_run_exec):
2330 for i, node in enumerate(to_run_exec):
2289 mod = ast.Module([node])
2331 mod = ast.Module([node])
2290 code = self.compile(mod, cell_name, "exec")
2332 code = self.compile(mod, cell_name, "exec")
2291 if self.run_code(code):
2333 if self.run_code(code):
2292 return True
2334 return True
2293
2335
2294 for i, node in enumerate(to_run_interactive):
2336 for i, node in enumerate(to_run_interactive):
2295 mod = ast.Interactive([node])
2337 mod = ast.Interactive([node])
2296 code = self.compile(mod, cell_name, "single")
2338 code = self.compile(mod, cell_name, "single")
2297 if self.run_code(code):
2339 if self.run_code(code):
2298 return True
2340 return True
2299
2341
2300 return False
2342 return False
2301
2343
2302 def run_code(self, code_obj):
2344 def run_code(self, code_obj):
2303 """Execute a code object.
2345 """Execute a code object.
2304
2346
2305 When an exception occurs, self.showtraceback() is called to display a
2347 When an exception occurs, self.showtraceback() is called to display a
2306 traceback.
2348 traceback.
2307
2349
2308 Parameters
2350 Parameters
2309 ----------
2351 ----------
2310 code_obj : code object
2352 code_obj : code object
2311 A compiled code object, to be executed
2353 A compiled code object, to be executed
2312 post_execute : bool [default: True]
2354 post_execute : bool [default: True]
2313 whether to call post_execute hooks after this particular execution.
2355 whether to call post_execute hooks after this particular execution.
2314
2356
2315 Returns
2357 Returns
2316 -------
2358 -------
2317 False : successful execution.
2359 False : successful execution.
2318 True : an error occurred.
2360 True : an error occurred.
2319 """
2361 """
2320
2362
2321 # Set our own excepthook in case the user code tries to call it
2363 # Set our own excepthook in case the user code tries to call it
2322 # directly, so that the IPython crash handler doesn't get triggered
2364 # directly, so that the IPython crash handler doesn't get triggered
2323 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2365 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2324
2366
2325 # we save the original sys.excepthook in the instance, in case config
2367 # we save the original sys.excepthook in the instance, in case config
2326 # code (such as magics) needs access to it.
2368 # code (such as magics) needs access to it.
2327 self.sys_excepthook = old_excepthook
2369 self.sys_excepthook = old_excepthook
2328 outflag = 1 # happens in more places, so it's easier as default
2370 outflag = 1 # happens in more places, so it's easier as default
2329 try:
2371 try:
2330 try:
2372 try:
2331 self.hooks.pre_run_code_hook()
2373 self.hooks.pre_run_code_hook()
2332 #rprint('Running code', repr(code_obj)) # dbg
2374 #rprint('Running code', repr(code_obj)) # dbg
2333 exec code_obj in self.user_global_ns, self.user_ns
2375 exec code_obj in self.user_global_ns, self.user_ns
2334 finally:
2376 finally:
2335 # Reset our crash handler in place
2377 # Reset our crash handler in place
2336 sys.excepthook = old_excepthook
2378 sys.excepthook = old_excepthook
2337 except SystemExit:
2379 except SystemExit:
2338 self.showtraceback(exception_only=True)
2380 self.showtraceback(exception_only=True)
2339 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2381 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2340 except self.custom_exceptions:
2382 except self.custom_exceptions:
2341 etype,value,tb = sys.exc_info()
2383 etype,value,tb = sys.exc_info()
2342 self.CustomTB(etype,value,tb)
2384 self.CustomTB(etype,value,tb)
2343 except:
2385 except:
2344 self.showtraceback()
2386 self.showtraceback()
2345 else:
2387 else:
2346 outflag = 0
2388 outflag = 0
2347 if softspace(sys.stdout, 0):
2389 if softspace(sys.stdout, 0):
2348 print
2390 print
2349
2391
2350 return outflag
2392 return outflag
2351
2393
2352 # For backwards compatibility
2394 # For backwards compatibility
2353 runcode = run_code
2395 runcode = run_code
2354
2396
2355 #-------------------------------------------------------------------------
2397 #-------------------------------------------------------------------------
2356 # Things related to GUI support and pylab
2398 # Things related to GUI support and pylab
2357 #-------------------------------------------------------------------------
2399 #-------------------------------------------------------------------------
2358
2400
2359 def enable_pylab(self, gui=None):
2401 def enable_pylab(self, gui=None):
2360 raise NotImplementedError('Implement enable_pylab in a subclass')
2402 raise NotImplementedError('Implement enable_pylab in a subclass')
2361
2403
2362 #-------------------------------------------------------------------------
2404 #-------------------------------------------------------------------------
2363 # Utilities
2405 # Utilities
2364 #-------------------------------------------------------------------------
2406 #-------------------------------------------------------------------------
2365
2407
2366 def var_expand(self,cmd,depth=0):
2408 def var_expand(self,cmd,depth=0):
2367 """Expand python variables in a string.
2409 """Expand python variables in a string.
2368
2410
2369 The depth argument indicates how many frames above the caller should
2411 The depth argument indicates how many frames above the caller should
2370 be walked to look for the local namespace where to expand variables.
2412 be walked to look for the local namespace where to expand variables.
2371
2413
2372 The global namespace for expansion is always the user's interactive
2414 The global namespace for expansion is always the user's interactive
2373 namespace.
2415 namespace.
2374 """
2416 """
2375 res = ItplNS(cmd, self.user_ns, # globals
2417 res = ItplNS(cmd, self.user_ns, # globals
2376 # Skip our own frame in searching for locals:
2418 # Skip our own frame in searching for locals:
2377 sys._getframe(depth+1).f_locals # locals
2419 sys._getframe(depth+1).f_locals # locals
2378 )
2420 )
2379 return str(res).decode(res.codec)
2421 return str(res).decode(res.codec)
2380
2422
2381 def mktempfile(self, data=None, prefix='ipython_edit_'):
2423 def mktempfile(self, data=None, prefix='ipython_edit_'):
2382 """Make a new tempfile and return its filename.
2424 """Make a new tempfile and return its filename.
2383
2425
2384 This makes a call to tempfile.mktemp, but it registers the created
2426 This makes a call to tempfile.mktemp, but it registers the created
2385 filename internally so ipython cleans it up at exit time.
2427 filename internally so ipython cleans it up at exit time.
2386
2428
2387 Optional inputs:
2429 Optional inputs:
2388
2430
2389 - data(None): if data is given, it gets written out to the temp file
2431 - data(None): if data is given, it gets written out to the temp file
2390 immediately, and the file is closed again."""
2432 immediately, and the file is closed again."""
2391
2433
2392 filename = tempfile.mktemp('.py', prefix)
2434 filename = tempfile.mktemp('.py', prefix)
2393 self.tempfiles.append(filename)
2435 self.tempfiles.append(filename)
2394
2436
2395 if data:
2437 if data:
2396 tmp_file = open(filename,'w')
2438 tmp_file = open(filename,'w')
2397 tmp_file.write(data)
2439 tmp_file.write(data)
2398 tmp_file.close()
2440 tmp_file.close()
2399 return filename
2441 return filename
2400
2442
2401 # TODO: This should be removed when Term is refactored.
2443 # TODO: This should be removed when Term is refactored.
2402 def write(self,data):
2444 def write(self,data):
2403 """Write a string to the default output"""
2445 """Write a string to the default output"""
2404 io.stdout.write(data)
2446 io.stdout.write(data)
2405
2447
2406 # TODO: This should be removed when Term is refactored.
2448 # TODO: This should be removed when Term is refactored.
2407 def write_err(self,data):
2449 def write_err(self,data):
2408 """Write a string to the default error output"""
2450 """Write a string to the default error output"""
2409 io.stderr.write(data)
2451 io.stderr.write(data)
2410
2452
2411 def ask_yes_no(self,prompt,default=True):
2453 def ask_yes_no(self,prompt,default=True):
2412 if self.quiet:
2454 if self.quiet:
2413 return True
2455 return True
2414 return ask_yes_no(prompt,default)
2456 return ask_yes_no(prompt,default)
2415
2457
2416 def show_usage(self):
2458 def show_usage(self):
2417 """Show a usage message"""
2459 """Show a usage message"""
2418 page.page(IPython.core.usage.interactive_usage)
2460 page.page(IPython.core.usage.interactive_usage)
2419
2461
2420 def find_user_code(self, target, raw=True):
2462 def find_user_code(self, target, raw=True):
2421 """Get a code string from history, file, or a string or macro.
2463 """Get a code string from history, file, or a string or macro.
2422
2464
2423 This is mainly used by magic functions.
2465 This is mainly used by magic functions.
2424
2466
2425 Parameters
2467 Parameters
2426 ----------
2468 ----------
2427 target : str
2469 target : str
2428 A string specifying code to retrieve. This will be tried respectively
2470 A string specifying code to retrieve. This will be tried respectively
2429 as: ranges of input history (see %history for syntax), a filename, or
2471 as: ranges of input history (see %history for syntax), a filename, or
2430 an expression evaluating to a string or Macro in the user namespace.
2472 an expression evaluating to a string or Macro in the user namespace.
2431 raw : bool
2473 raw : bool
2432 If true (default), retrieve raw history. Has no effect on the other
2474 If true (default), retrieve raw history. Has no effect on the other
2433 retrieval mechanisms.
2475 retrieval mechanisms.
2434
2476
2435 Returns
2477 Returns
2436 -------
2478 -------
2437 A string of code.
2479 A string of code.
2438
2480
2439 ValueError is raised if nothing is found, and TypeError if it evaluates
2481 ValueError is raised if nothing is found, and TypeError if it evaluates
2440 to an object of another type. In each case, .args[0] is a printable
2482 to an object of another type. In each case, .args[0] is a printable
2441 message.
2483 message.
2442 """
2484 """
2443 code = self.extract_input_lines(target, raw=raw) # Grab history
2485 code = self.extract_input_lines(target, raw=raw) # Grab history
2444 if code:
2486 if code:
2445 return code
2487 return code
2446 if os.path.isfile(target): # Read file
2488 if os.path.isfile(target): # Read file
2447 return open(target, "r").read()
2489 return open(target, "r").read()
2448
2490
2449 try: # User namespace
2491 try: # User namespace
2450 codeobj = eval(target, self.user_ns)
2492 codeobj = eval(target, self.user_ns)
2451 except Exception:
2493 except Exception:
2452 raise ValueError(("'%s' was not found in history, as a file, nor in"
2494 raise ValueError(("'%s' was not found in history, as a file, nor in"
2453 " the user namespace.") % target)
2495 " the user namespace.") % target)
2454 if isinstance(codeobj, basestring):
2496 if isinstance(codeobj, basestring):
2455 return codeobj
2497 return codeobj
2456 elif isinstance(codeobj, Macro):
2498 elif isinstance(codeobj, Macro):
2457 return codeobj.value
2499 return codeobj.value
2458
2500
2459 raise TypeError("%s is neither a string nor a macro." % target,
2501 raise TypeError("%s is neither a string nor a macro." % target,
2460 codeobj)
2502 codeobj)
2461
2503
2462 #-------------------------------------------------------------------------
2504 #-------------------------------------------------------------------------
2463 # Things related to IPython exiting
2505 # Things related to IPython exiting
2464 #-------------------------------------------------------------------------
2506 #-------------------------------------------------------------------------
2465 def atexit_operations(self):
2507 def atexit_operations(self):
2466 """This will be executed at the time of exit.
2508 """This will be executed at the time of exit.
2467
2509
2468 Cleanup operations and saving of persistent data that is done
2510 Cleanup operations and saving of persistent data that is done
2469 unconditionally by IPython should be performed here.
2511 unconditionally by IPython should be performed here.
2470
2512
2471 For things that may depend on startup flags or platform specifics (such
2513 For things that may depend on startup flags or platform specifics (such
2472 as having readline or not), register a separate atexit function in the
2514 as having readline or not), register a separate atexit function in the
2473 code that has the appropriate information, rather than trying to
2515 code that has the appropriate information, rather than trying to
2474 clutter
2516 clutter
2475 """
2517 """
2476 # Cleanup all tempfiles left around
2518 # Cleanup all tempfiles left around
2477 for tfile in self.tempfiles:
2519 for tfile in self.tempfiles:
2478 try:
2520 try:
2479 os.unlink(tfile)
2521 os.unlink(tfile)
2480 except OSError:
2522 except OSError:
2481 pass
2523 pass
2482
2524
2483 # Close the history session (this stores the end time and line count)
2525 # Close the history session (this stores the end time and line count)
2484 self.history_manager.end_session()
2526 self.history_manager.end_session()
2485
2527
2486 # Clear all user namespaces to release all references cleanly.
2528 # Clear all user namespaces to release all references cleanly.
2487 self.reset(new_session=False)
2529 self.reset(new_session=False)
2488
2530
2489 # Run user hooks
2531 # Run user hooks
2490 self.hooks.shutdown_hook()
2532 self.hooks.shutdown_hook()
2491
2533
2492 def cleanup(self):
2534 def cleanup(self):
2493 self.restore_sys_module_state()
2535 self.restore_sys_module_state()
2494
2536
2495
2537
2496 class InteractiveShellABC(object):
2538 class InteractiveShellABC(object):
2497 """An abstract base class for InteractiveShell."""
2539 """An abstract base class for InteractiveShell."""
2498 __metaclass__ = abc.ABCMeta
2540 __metaclass__ = abc.ABCMeta
2499
2541
2500 InteractiveShellABC.register(InteractiveShell)
2542 InteractiveShellABC.register(InteractiveShell)
@@ -1,3501 +1,3518 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 from cStringIO import StringIO
28 from cStringIO import StringIO
29 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
30 from pprint import pformat
30 from pprint import pformat
31 from xmlrpclib import ServerProxy
31 from xmlrpclib import ServerProxy
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 import IPython
44 import IPython
45 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.macro import Macro
49 from IPython.core.macro import Macro
50 from IPython.core import page
50 from IPython.core import page
51 from IPython.core.prefilter import ESC_MAGIC
51 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.lib.pylabtools import mpl_runner
52 from IPython.lib.pylabtools import mpl_runner
53 from IPython.external.Itpl import itpl, printpl
53 from IPython.external.Itpl import itpl, printpl
54 from IPython.testing.skipdoctest import skip_doctest
54 from IPython.testing.skipdoctest import skip_doctest
55 from IPython.utils.io import file_read, nlprint
55 from IPython.utils.io import file_read, nlprint
56 from IPython.utils.path import get_py_filename
56 from IPython.utils.path import get_py_filename
57 from IPython.utils.process import arg_split, abbrev_cwd
57 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.terminal import set_term_title
58 from IPython.utils.terminal import set_term_title
59 from IPython.utils.text import LSString, SList, format_screen
59 from IPython.utils.text import LSString, SList, format_screen
60 from IPython.utils.timing import clock, clock2
60 from IPython.utils.timing import clock, clock2
61 from IPython.utils.warn import warn, error
61 from IPython.utils.warn import warn, error
62 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
63 import IPython.utils.generics
63 import IPython.utils.generics
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Utility functions
66 # Utility functions
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 def on_off(tag):
69 def on_off(tag):
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
71 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
72
72
73 class Bunch: pass
73 class Bunch: pass
74
74
75 def compress_dhist(dh):
75 def compress_dhist(dh):
76 head, tail = dh[:-10], dh[-10:]
76 head, tail = dh[:-10], dh[-10:]
77
77
78 newhead = []
78 newhead = []
79 done = set()
79 done = set()
80 for h in head:
80 for h in head:
81 if h in done:
81 if h in done:
82 continue
82 continue
83 newhead.append(h)
83 newhead.append(h)
84 done.add(h)
84 done.add(h)
85
85
86 return newhead + tail
86 return newhead + tail
87
87
88 def needs_local_scope(func):
88 def needs_local_scope(func):
89 """Decorator to mark magic functions which need to local scope to run."""
89 """Decorator to mark magic functions which need to local scope to run."""
90 func.needs_local_scope = True
90 func.needs_local_scope = True
91 return func
91 return func
92
92
93 # Used for exception handling in magic_edit
93 # Used for exception handling in magic_edit
94 class MacroToEdit(ValueError): pass
94 class MacroToEdit(ValueError): pass
95
95
96 #***************************************************************************
96 #***************************************************************************
97 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
98
98
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
106
106
107 class Magic:
107 class Magic:
108 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
109
109
110 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
113 vs. `%cd("../")`
114
114
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
117
117
118 # class globals
118 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121
121
122 #......................................................................
122 #......................................................................
123 # some utility functions
123 # some utility functions
124
124
125 def __init__(self,shell):
125 def __init__(self,shell):
126
126
127 self.options_table = {}
127 self.options_table = {}
128 if profile is None:
128 if profile is None:
129 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
130 self.shell = shell
131
131
132 # namespace for holding state we may need
132 # namespace for holding state we may need
133 self._magic_state = Bunch()
133 self._magic_state = Bunch()
134
134
135 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
136 error("""\
137 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
140
140
141 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
143
143
144 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
147
147
148 def lsmagic(self):
148 def lsmagic(self):
149 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
150
150
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
153
153
154 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155
155
156 # magics in class definition
156 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
168 out = []
169 for fn in set(magics):
169 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
171 out.sort()
171 out.sort()
172 return out
172 return out
173
173
174 def extract_input_lines(self, range_str, raw=False):
174 def extract_input_lines(self, range_str, raw=False):
175 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
176
176
177 Inputs:
177 Inputs:
178
178
179 - range_str: the set of slices is given as a string, like
179 - range_str: the set of slices is given as a string, like
180 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
180 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
181 which get their arguments as strings. The number before the / is the
181 which get their arguments as strings. The number before the / is the
182 session number: ~n goes n back from the current session.
182 session number: ~n goes n back from the current session.
183
183
184 Optional inputs:
184 Optional inputs:
185
185
186 - raw(False): by default, the processed input is used. If this is
186 - raw(False): by default, the processed input is used. If this is
187 true, the raw input history is used instead.
187 true, the raw input history is used instead.
188
188
189 Note that slices can be called with two notations:
189 Note that slices can be called with two notations:
190
190
191 N:M -> standard python form, means including items N...(M-1).
191 N:M -> standard python form, means including items N...(M-1).
192
192
193 N-M -> include items N..M (closed endpoint)."""
193 N-M -> include items N..M (closed endpoint)."""
194 lines = self.shell.history_manager.\
194 lines = self.shell.history_manager.\
195 get_range_by_str(range_str, raw=raw)
195 get_range_by_str(range_str, raw=raw)
196 return "\n".join(x for _, _, x in lines)
196 return "\n".join(x for _, _, x in lines)
197
197
198 def arg_err(self,func):
198 def arg_err(self,func):
199 """Print docstring if incorrect arguments were passed"""
199 """Print docstring if incorrect arguments were passed"""
200 print 'Error in arguments:'
200 print 'Error in arguments:'
201 print oinspect.getdoc(func)
201 print oinspect.getdoc(func)
202
202
203 def format_latex(self,strng):
203 def format_latex(self,strng):
204 """Format a string for latex inclusion."""
204 """Format a string for latex inclusion."""
205
205
206 # Characters that need to be escaped for latex:
206 # Characters that need to be escaped for latex:
207 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
207 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
208 # Magic command names as headers:
208 # Magic command names as headers:
209 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
209 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
210 re.MULTILINE)
210 re.MULTILINE)
211 # Magic commands
211 # Magic commands
212 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
212 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
213 re.MULTILINE)
213 re.MULTILINE)
214 # Paragraph continue
214 # Paragraph continue
215 par_re = re.compile(r'\\$',re.MULTILINE)
215 par_re = re.compile(r'\\$',re.MULTILINE)
216
216
217 # The "\n" symbol
217 # The "\n" symbol
218 newline_re = re.compile(r'\\n')
218 newline_re = re.compile(r'\\n')
219
219
220 # Now build the string for output:
220 # Now build the string for output:
221 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
221 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
222 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
222 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
223 strng)
223 strng)
224 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
224 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
225 strng = par_re.sub(r'\\\\',strng)
225 strng = par_re.sub(r'\\\\',strng)
226 strng = escape_re.sub(r'\\\1',strng)
226 strng = escape_re.sub(r'\\\1',strng)
227 strng = newline_re.sub(r'\\textbackslash{}n',strng)
227 strng = newline_re.sub(r'\\textbackslash{}n',strng)
228 return strng
228 return strng
229
229
230 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
230 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
231 """Parse options passed to an argument string.
231 """Parse options passed to an argument string.
232
232
233 The interface is similar to that of getopt(), but it returns back a
233 The interface is similar to that of getopt(), but it returns back a
234 Struct with the options as keys and the stripped argument string still
234 Struct with the options as keys and the stripped argument string still
235 as a string.
235 as a string.
236
236
237 arg_str is quoted as a true sys.argv vector by using shlex.split.
237 arg_str is quoted as a true sys.argv vector by using shlex.split.
238 This allows us to easily expand variables, glob files, quote
238 This allows us to easily expand variables, glob files, quote
239 arguments, etc.
239 arguments, etc.
240
240
241 Options:
241 Options:
242 -mode: default 'string'. If given as 'list', the argument string is
242 -mode: default 'string'. If given as 'list', the argument string is
243 returned as a list (split on whitespace) instead of a string.
243 returned as a list (split on whitespace) instead of a string.
244
244
245 -list_all: put all option values in lists. Normally only options
245 -list_all: put all option values in lists. Normally only options
246 appearing more than once are put in a list.
246 appearing more than once are put in a list.
247
247
248 -posix (True): whether to split the input line in POSIX mode or not,
248 -posix (True): whether to split the input line in POSIX mode or not,
249 as per the conventions outlined in the shlex module from the
249 as per the conventions outlined in the shlex module from the
250 standard library."""
250 standard library."""
251
251
252 # inject default options at the beginning of the input line
252 # inject default options at the beginning of the input line
253 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
253 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
254 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
254 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
255
255
256 mode = kw.get('mode','string')
256 mode = kw.get('mode','string')
257 if mode not in ['string','list']:
257 if mode not in ['string','list']:
258 raise ValueError,'incorrect mode given: %s' % mode
258 raise ValueError,'incorrect mode given: %s' % mode
259 # Get options
259 # Get options
260 list_all = kw.get('list_all',0)
260 list_all = kw.get('list_all',0)
261 posix = kw.get('posix', os.name == 'posix')
261 posix = kw.get('posix', os.name == 'posix')
262
262
263 # Check if we have more than one argument to warrant extra processing:
263 # Check if we have more than one argument to warrant extra processing:
264 odict = {} # Dictionary with options
264 odict = {} # Dictionary with options
265 args = arg_str.split()
265 args = arg_str.split()
266 if len(args) >= 1:
266 if len(args) >= 1:
267 # If the list of inputs only has 0 or 1 thing in it, there's no
267 # If the list of inputs only has 0 or 1 thing in it, there's no
268 # need to look for options
268 # need to look for options
269 argv = arg_split(arg_str,posix)
269 argv = arg_split(arg_str,posix)
270 # Do regular option processing
270 # Do regular option processing
271 try:
271 try:
272 opts,args = getopt(argv,opt_str,*long_opts)
272 opts,args = getopt(argv,opt_str,*long_opts)
273 except GetoptError,e:
273 except GetoptError,e:
274 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
274 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
275 " ".join(long_opts)))
275 " ".join(long_opts)))
276 for o,a in opts:
276 for o,a in opts:
277 if o.startswith('--'):
277 if o.startswith('--'):
278 o = o[2:]
278 o = o[2:]
279 else:
279 else:
280 o = o[1:]
280 o = o[1:]
281 try:
281 try:
282 odict[o].append(a)
282 odict[o].append(a)
283 except AttributeError:
283 except AttributeError:
284 odict[o] = [odict[o],a]
284 odict[o] = [odict[o],a]
285 except KeyError:
285 except KeyError:
286 if list_all:
286 if list_all:
287 odict[o] = [a]
287 odict[o] = [a]
288 else:
288 else:
289 odict[o] = a
289 odict[o] = a
290
290
291 # Prepare opts,args for return
291 # Prepare opts,args for return
292 opts = Struct(odict)
292 opts = Struct(odict)
293 if mode == 'string':
293 if mode == 'string':
294 args = ' '.join(args)
294 args = ' '.join(args)
295
295
296 return opts,args
296 return opts,args
297
297
298 #......................................................................
298 #......................................................................
299 # And now the actual magic functions
299 # And now the actual magic functions
300
300
301 # Functions for IPython shell work (vars,funcs, config, etc)
301 # Functions for IPython shell work (vars,funcs, config, etc)
302 def magic_lsmagic(self, parameter_s = ''):
302 def magic_lsmagic(self, parameter_s = ''):
303 """List currently available magic functions."""
303 """List currently available magic functions."""
304 mesc = ESC_MAGIC
304 mesc = ESC_MAGIC
305 print 'Available magic functions:\n'+mesc+\
305 print 'Available magic functions:\n'+mesc+\
306 (' '+mesc).join(self.lsmagic())
306 (' '+mesc).join(self.lsmagic())
307 print '\n' + Magic.auto_status[self.shell.automagic]
307 print '\n' + Magic.auto_status[self.shell.automagic]
308 return None
308 return None
309
309
310 def magic_magic(self, parameter_s = ''):
310 def magic_magic(self, parameter_s = ''):
311 """Print information about the magic function system.
311 """Print information about the magic function system.
312
312
313 Supported formats: -latex, -brief, -rest
313 Supported formats: -latex, -brief, -rest
314 """
314 """
315
315
316 mode = ''
316 mode = ''
317 try:
317 try:
318 if parameter_s.split()[0] == '-latex':
318 if parameter_s.split()[0] == '-latex':
319 mode = 'latex'
319 mode = 'latex'
320 if parameter_s.split()[0] == '-brief':
320 if parameter_s.split()[0] == '-brief':
321 mode = 'brief'
321 mode = 'brief'
322 if parameter_s.split()[0] == '-rest':
322 if parameter_s.split()[0] == '-rest':
323 mode = 'rest'
323 mode = 'rest'
324 rest_docs = []
324 rest_docs = []
325 except:
325 except:
326 pass
326 pass
327
327
328 magic_docs = []
328 magic_docs = []
329 for fname in self.lsmagic():
329 for fname in self.lsmagic():
330 mname = 'magic_' + fname
330 mname = 'magic_' + fname
331 for space in (Magic,self,self.__class__):
331 for space in (Magic,self,self.__class__):
332 try:
332 try:
333 fn = space.__dict__[mname]
333 fn = space.__dict__[mname]
334 except KeyError:
334 except KeyError:
335 pass
335 pass
336 else:
336 else:
337 break
337 break
338 if mode == 'brief':
338 if mode == 'brief':
339 # only first line
339 # only first line
340 if fn.__doc__:
340 if fn.__doc__:
341 fndoc = fn.__doc__.split('\n',1)[0]
341 fndoc = fn.__doc__.split('\n',1)[0]
342 else:
342 else:
343 fndoc = 'No documentation'
343 fndoc = 'No documentation'
344 else:
344 else:
345 if fn.__doc__:
345 if fn.__doc__:
346 fndoc = fn.__doc__.rstrip()
346 fndoc = fn.__doc__.rstrip()
347 else:
347 else:
348 fndoc = 'No documentation'
348 fndoc = 'No documentation'
349
349
350
350
351 if mode == 'rest':
351 if mode == 'rest':
352 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
352 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
353 fname,fndoc))
353 fname,fndoc))
354
354
355 else:
355 else:
356 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
356 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
357 fname,fndoc))
357 fname,fndoc))
358
358
359 magic_docs = ''.join(magic_docs)
359 magic_docs = ''.join(magic_docs)
360
360
361 if mode == 'rest':
361 if mode == 'rest':
362 return "".join(rest_docs)
362 return "".join(rest_docs)
363
363
364 if mode == 'latex':
364 if mode == 'latex':
365 print self.format_latex(magic_docs)
365 print self.format_latex(magic_docs)
366 return
366 return
367 else:
367 else:
368 magic_docs = format_screen(magic_docs)
368 magic_docs = format_screen(magic_docs)
369 if mode == 'brief':
369 if mode == 'brief':
370 return magic_docs
370 return magic_docs
371
371
372 outmsg = """
372 outmsg = """
373 IPython's 'magic' functions
373 IPython's 'magic' functions
374 ===========================
374 ===========================
375
375
376 The magic function system provides a series of functions which allow you to
376 The magic function system provides a series of functions which allow you to
377 control the behavior of IPython itself, plus a lot of system-type
377 control the behavior of IPython itself, plus a lot of system-type
378 features. All these functions are prefixed with a % character, but parameters
378 features. All these functions are prefixed with a % character, but parameters
379 are given without parentheses or quotes.
379 are given without parentheses or quotes.
380
380
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
382 %automagic function), you don't need to type in the % explicitly. By default,
382 %automagic function), you don't need to type in the % explicitly. By default,
383 IPython ships with automagic on, so you should only rarely need the % escape.
383 IPython ships with automagic on, so you should only rarely need the % escape.
384
384
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
386 to 'mydir', if it exists.
386 to 'mydir', if it exists.
387
387
388 You can define your own magic functions to extend the system. See the supplied
388 You can define your own magic functions to extend the system. See the supplied
389 ipythonrc and example-magic.py files for details (in your ipython
389 ipythonrc and example-magic.py files for details (in your ipython
390 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
390 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
391
391
392 You can also define your own aliased names for magic functions. In your
392 You can also define your own aliased names for magic functions. In your
393 ipythonrc file, placing a line like:
393 ipythonrc file, placing a line like:
394
394
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
396
396
397 will define %pf as a new name for %profile.
397 will define %pf as a new name for %profile.
398
398
399 You can also call magics in code using the magic() function, which IPython
399 You can also call magics in code using the magic() function, which IPython
400 automatically adds to the builtin namespace. Type 'magic?' for details.
400 automatically adds to the builtin namespace. Type 'magic?' for details.
401
401
402 For a list of the available magic functions, use %lsmagic. For a description
402 For a list of the available magic functions, use %lsmagic. For a description
403 of any of them, type %magic_name?, e.g. '%cd?'.
403 of any of them, type %magic_name?, e.g. '%cd?'.
404
404
405 Currently the magic system has the following functions:\n"""
405 Currently the magic system has the following functions:\n"""
406
406
407 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
409 "\n\n%s%s\n\n%s" % (outmsg,
409 "\n\n%s%s\n\n%s" % (outmsg,
410 magic_docs,mesc,mesc,
410 magic_docs,mesc,mesc,
411 (' '+mesc).join(self.lsmagic()),
411 (' '+mesc).join(self.lsmagic()),
412 Magic.auto_status[self.shell.automagic] ) )
412 Magic.auto_status[self.shell.automagic] ) )
413 page.page(outmsg)
413 page.page(outmsg)
414
414
415 def magic_automagic(self, parameter_s = ''):
415 def magic_automagic(self, parameter_s = ''):
416 """Make magic functions callable without having to type the initial %.
416 """Make magic functions callable without having to type the initial %.
417
417
418 Without argumentsl toggles on/off (when off, you must call it as
418 Without argumentsl toggles on/off (when off, you must call it as
419 %automagic, of course). With arguments it sets the value, and you can
419 %automagic, of course). With arguments it sets the value, and you can
420 use any of (case insensitive):
420 use any of (case insensitive):
421
421
422 - on,1,True: to activate
422 - on,1,True: to activate
423
423
424 - off,0,False: to deactivate.
424 - off,0,False: to deactivate.
425
425
426 Note that magic functions have lowest priority, so if there's a
426 Note that magic functions have lowest priority, so if there's a
427 variable whose name collides with that of a magic fn, automagic won't
427 variable whose name collides with that of a magic fn, automagic won't
428 work for that function (you get the variable instead). However, if you
428 work for that function (you get the variable instead). However, if you
429 delete the variable (del var), the previously shadowed magic function
429 delete the variable (del var), the previously shadowed magic function
430 becomes visible to automagic again."""
430 becomes visible to automagic again."""
431
431
432 arg = parameter_s.lower()
432 arg = parameter_s.lower()
433 if parameter_s in ('on','1','true'):
433 if parameter_s in ('on','1','true'):
434 self.shell.automagic = True
434 self.shell.automagic = True
435 elif parameter_s in ('off','0','false'):
435 elif parameter_s in ('off','0','false'):
436 self.shell.automagic = False
436 self.shell.automagic = False
437 else:
437 else:
438 self.shell.automagic = not self.shell.automagic
438 self.shell.automagic = not self.shell.automagic
439 print '\n' + Magic.auto_status[self.shell.automagic]
439 print '\n' + Magic.auto_status[self.shell.automagic]
440
440
441 @skip_doctest
441 @skip_doctest
442 def magic_autocall(self, parameter_s = ''):
442 def magic_autocall(self, parameter_s = ''):
443 """Make functions callable without having to type parentheses.
443 """Make functions callable without having to type parentheses.
444
444
445 Usage:
445 Usage:
446
446
447 %autocall [mode]
447 %autocall [mode]
448
448
449 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
449 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
450 value is toggled on and off (remembering the previous state).
450 value is toggled on and off (remembering the previous state).
451
451
452 In more detail, these values mean:
452 In more detail, these values mean:
453
453
454 0 -> fully disabled
454 0 -> fully disabled
455
455
456 1 -> active, but do not apply if there are no arguments on the line.
456 1 -> active, but do not apply if there are no arguments on the line.
457
457
458 In this mode, you get:
458 In this mode, you get:
459
459
460 In [1]: callable
460 In [1]: callable
461 Out[1]: <built-in function callable>
461 Out[1]: <built-in function callable>
462
462
463 In [2]: callable 'hello'
463 In [2]: callable 'hello'
464 ------> callable('hello')
464 ------> callable('hello')
465 Out[2]: False
465 Out[2]: False
466
466
467 2 -> Active always. Even if no arguments are present, the callable
467 2 -> Active always. Even if no arguments are present, the callable
468 object is called:
468 object is called:
469
469
470 In [2]: float
470 In [2]: float
471 ------> float()
471 ------> float()
472 Out[2]: 0.0
472 Out[2]: 0.0
473
473
474 Note that even with autocall off, you can still use '/' at the start of
474 Note that even with autocall off, you can still use '/' at the start of
475 a line to treat the first argument on the command line as a function
475 a line to treat the first argument on the command line as a function
476 and add parentheses to it:
476 and add parentheses to it:
477
477
478 In [8]: /str 43
478 In [8]: /str 43
479 ------> str(43)
479 ------> str(43)
480 Out[8]: '43'
480 Out[8]: '43'
481
481
482 # all-random (note for auto-testing)
482 # all-random (note for auto-testing)
483 """
483 """
484
484
485 if parameter_s:
485 if parameter_s:
486 arg = int(parameter_s)
486 arg = int(parameter_s)
487 else:
487 else:
488 arg = 'toggle'
488 arg = 'toggle'
489
489
490 if not arg in (0,1,2,'toggle'):
490 if not arg in (0,1,2,'toggle'):
491 error('Valid modes: (0->Off, 1->Smart, 2->Full')
491 error('Valid modes: (0->Off, 1->Smart, 2->Full')
492 return
492 return
493
493
494 if arg in (0,1,2):
494 if arg in (0,1,2):
495 self.shell.autocall = arg
495 self.shell.autocall = arg
496 else: # toggle
496 else: # toggle
497 if self.shell.autocall:
497 if self.shell.autocall:
498 self._magic_state.autocall_save = self.shell.autocall
498 self._magic_state.autocall_save = self.shell.autocall
499 self.shell.autocall = 0
499 self.shell.autocall = 0
500 else:
500 else:
501 try:
501 try:
502 self.shell.autocall = self._magic_state.autocall_save
502 self.shell.autocall = self._magic_state.autocall_save
503 except AttributeError:
503 except AttributeError:
504 self.shell.autocall = self._magic_state.autocall_save = 1
504 self.shell.autocall = self._magic_state.autocall_save = 1
505
505
506 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
506 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
507
507
508
508
509 def magic_page(self, parameter_s=''):
509 def magic_page(self, parameter_s=''):
510 """Pretty print the object and display it through a pager.
510 """Pretty print the object and display it through a pager.
511
511
512 %page [options] OBJECT
512 %page [options] OBJECT
513
513
514 If no object is given, use _ (last output).
514 If no object is given, use _ (last output).
515
515
516 Options:
516 Options:
517
517
518 -r: page str(object), don't pretty-print it."""
518 -r: page str(object), don't pretty-print it."""
519
519
520 # After a function contributed by Olivier Aubert, slightly modified.
520 # After a function contributed by Olivier Aubert, slightly modified.
521
521
522 # Process options/args
522 # Process options/args
523 opts,args = self.parse_options(parameter_s,'r')
523 opts,args = self.parse_options(parameter_s,'r')
524 raw = 'r' in opts
524 raw = 'r' in opts
525
525
526 oname = args and args or '_'
526 oname = args and args or '_'
527 info = self._ofind(oname)
527 info = self._ofind(oname)
528 if info['found']:
528 if info['found']:
529 txt = (raw and str or pformat)( info['obj'] )
529 txt = (raw and str or pformat)( info['obj'] )
530 page.page(txt)
530 page.page(txt)
531 else:
531 else:
532 print 'Object `%s` not found' % oname
532 print 'Object `%s` not found' % oname
533
533
534 def magic_profile(self, parameter_s=''):
534 def magic_profile(self, parameter_s=''):
535 """Print your currently active IPython profile."""
535 """Print your currently active IPython profile."""
536 if self.shell.profile:
536 if self.shell.profile:
537 printpl('Current IPython profile: $self.shell.profile.')
537 printpl('Current IPython profile: $self.shell.profile.')
538 else:
538 else:
539 print 'No profile active.'
539 print 'No profile active.'
540
540
541 def magic_pinfo(self, parameter_s='', namespaces=None):
541 def magic_pinfo(self, parameter_s='', namespaces=None):
542 """Provide detailed information about an object.
542 """Provide detailed information about an object.
543
543
544 '%pinfo object' is just a synonym for object? or ?object."""
544 '%pinfo object' is just a synonym for object? or ?object."""
545
545
546 #print 'pinfo par: <%s>' % parameter_s # dbg
546 #print 'pinfo par: <%s>' % parameter_s # dbg
547
547
548
548
549 # detail_level: 0 -> obj? , 1 -> obj??
549 # detail_level: 0 -> obj? , 1 -> obj??
550 detail_level = 0
550 detail_level = 0
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
551 # We need to detect if we got called as 'pinfo pinfo foo', which can
552 # happen if the user types 'pinfo foo?' at the cmd line.
552 # happen if the user types 'pinfo foo?' at the cmd line.
553 pinfo,qmark1,oname,qmark2 = \
553 pinfo,qmark1,oname,qmark2 = \
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
554 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
555 if pinfo or qmark1 or qmark2:
555 if pinfo or qmark1 or qmark2:
556 detail_level = 1
556 detail_level = 1
557 if "*" in oname:
557 if "*" in oname:
558 self.magic_psearch(oname)
558 self.magic_psearch(oname)
559 else:
559 else:
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
560 self.shell._inspect('pinfo', oname, detail_level=detail_level,
561 namespaces=namespaces)
561 namespaces=namespaces)
562
562
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
563 def magic_pinfo2(self, parameter_s='', namespaces=None):
564 """Provide extra detailed information about an object.
564 """Provide extra detailed information about an object.
565
565
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
566 '%pinfo2 object' is just a synonym for object?? or ??object."""
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
567 self.shell._inspect('pinfo', parameter_s, detail_level=1,
568 namespaces=namespaces)
568 namespaces=namespaces)
569
569
570 @skip_doctest
570 @skip_doctest
571 def magic_pdef(self, parameter_s='', namespaces=None):
571 def magic_pdef(self, parameter_s='', namespaces=None):
572 """Print the definition header for any callable object.
572 """Print the definition header for any callable object.
573
573
574 If the object is a class, print the constructor information.
574 If the object is a class, print the constructor information.
575
575
576 Examples
576 Examples
577 --------
577 --------
578 ::
578 ::
579
579
580 In [3]: %pdef urllib.urlopen
580 In [3]: %pdef urllib.urlopen
581 urllib.urlopen(url, data=None, proxies=None)
581 urllib.urlopen(url, data=None, proxies=None)
582 """
582 """
583 self._inspect('pdef',parameter_s, namespaces)
583 self._inspect('pdef',parameter_s, namespaces)
584
584
585 def magic_pdoc(self, parameter_s='', namespaces=None):
585 def magic_pdoc(self, parameter_s='', namespaces=None):
586 """Print the docstring for an object.
586 """Print the docstring for an object.
587
587
588 If the given object is a class, it will print both the class and the
588 If the given object is a class, it will print both the class and the
589 constructor docstrings."""
589 constructor docstrings."""
590 self._inspect('pdoc',parameter_s, namespaces)
590 self._inspect('pdoc',parameter_s, namespaces)
591
591
592 def magic_psource(self, parameter_s='', namespaces=None):
592 def magic_psource(self, parameter_s='', namespaces=None):
593 """Print (or run through pager) the source code for an object."""
593 """Print (or run through pager) the source code for an object."""
594 self._inspect('psource',parameter_s, namespaces)
594 self._inspect('psource',parameter_s, namespaces)
595
595
596 def magic_pfile(self, parameter_s=''):
596 def magic_pfile(self, parameter_s=''):
597 """Print (or run through pager) the file where an object is defined.
597 """Print (or run through pager) the file where an object is defined.
598
598
599 The file opens at the line where the object definition begins. IPython
599 The file opens at the line where the object definition begins. IPython
600 will honor the environment variable PAGER if set, and otherwise will
600 will honor the environment variable PAGER if set, and otherwise will
601 do its best to print the file in a convenient form.
601 do its best to print the file in a convenient form.
602
602
603 If the given argument is not an object currently defined, IPython will
603 If the given argument is not an object currently defined, IPython will
604 try to interpret it as a filename (automatically adding a .py extension
604 try to interpret it as a filename (automatically adding a .py extension
605 if needed). You can thus use %pfile as a syntax highlighting code
605 if needed). You can thus use %pfile as a syntax highlighting code
606 viewer."""
606 viewer."""
607
607
608 # first interpret argument as an object name
608 # first interpret argument as an object name
609 out = self._inspect('pfile',parameter_s)
609 out = self._inspect('pfile',parameter_s)
610 # if not, try the input as a filename
610 # if not, try the input as a filename
611 if out == 'not found':
611 if out == 'not found':
612 try:
612 try:
613 filename = get_py_filename(parameter_s)
613 filename = get_py_filename(parameter_s)
614 except IOError,msg:
614 except IOError,msg:
615 print msg
615 print msg
616 return
616 return
617 page.page(self.shell.inspector.format(file(filename).read()))
617 page.page(self.shell.inspector.format(file(filename).read()))
618
618
619 def magic_psearch(self, parameter_s=''):
619 def magic_psearch(self, parameter_s=''):
620 """Search for object in namespaces by wildcard.
620 """Search for object in namespaces by wildcard.
621
621
622 %psearch [options] PATTERN [OBJECT TYPE]
622 %psearch [options] PATTERN [OBJECT TYPE]
623
623
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
624 Note: ? can be used as a synonym for %psearch, at the beginning or at
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
625 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
626 rest of the command line must be unchanged (options come first), so
626 rest of the command line must be unchanged (options come first), so
627 for example the following forms are equivalent
627 for example the following forms are equivalent
628
628
629 %psearch -i a* function
629 %psearch -i a* function
630 -i a* function?
630 -i a* function?
631 ?-i a* function
631 ?-i a* function
632
632
633 Arguments:
633 Arguments:
634
634
635 PATTERN
635 PATTERN
636
636
637 where PATTERN is a string containing * as a wildcard similar to its
637 where PATTERN is a string containing * as a wildcard similar to its
638 use in a shell. The pattern is matched in all namespaces on the
638 use in a shell. The pattern is matched in all namespaces on the
639 search path. By default objects starting with a single _ are not
639 search path. By default objects starting with a single _ are not
640 matched, many IPython generated objects have a single
640 matched, many IPython generated objects have a single
641 underscore. The default is case insensitive matching. Matching is
641 underscore. The default is case insensitive matching. Matching is
642 also done on the attributes of objects and not only on the objects
642 also done on the attributes of objects and not only on the objects
643 in a module.
643 in a module.
644
644
645 [OBJECT TYPE]
645 [OBJECT TYPE]
646
646
647 Is the name of a python type from the types module. The name is
647 Is the name of a python type from the types module. The name is
648 given in lowercase without the ending type, ex. StringType is
648 given in lowercase without the ending type, ex. StringType is
649 written string. By adding a type here only objects matching the
649 written string. By adding a type here only objects matching the
650 given type are matched. Using all here makes the pattern match all
650 given type are matched. Using all here makes the pattern match all
651 types (this is the default).
651 types (this is the default).
652
652
653 Options:
653 Options:
654
654
655 -a: makes the pattern match even objects whose names start with a
655 -a: makes the pattern match even objects whose names start with a
656 single underscore. These names are normally ommitted from the
656 single underscore. These names are normally ommitted from the
657 search.
657 search.
658
658
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
659 -i/-c: make the pattern case insensitive/sensitive. If neither of
660 these options is given, the default is read from your ipythonrc
660 these options is given, the default is read from your ipythonrc
661 file. The option name which sets this value is
661 file. The option name which sets this value is
662 'wildcards_case_sensitive'. If this option is not specified in your
662 'wildcards_case_sensitive'. If this option is not specified in your
663 ipythonrc file, IPython's internal default is to do a case sensitive
663 ipythonrc file, IPython's internal default is to do a case sensitive
664 search.
664 search.
665
665
666 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
666 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
667 specifiy can be searched in any of the following namespaces:
667 specifiy can be searched in any of the following namespaces:
668 'builtin', 'user', 'user_global','internal', 'alias', where
668 'builtin', 'user', 'user_global','internal', 'alias', where
669 'builtin' and 'user' are the search defaults. Note that you should
669 'builtin' and 'user' are the search defaults. Note that you should
670 not use quotes when specifying namespaces.
670 not use quotes when specifying namespaces.
671
671
672 'Builtin' contains the python module builtin, 'user' contains all
672 'Builtin' contains the python module builtin, 'user' contains all
673 user data, 'alias' only contain the shell aliases and no python
673 user data, 'alias' only contain the shell aliases and no python
674 objects, 'internal' contains objects used by IPython. The
674 objects, 'internal' contains objects used by IPython. The
675 'user_global' namespace is only used by embedded IPython instances,
675 'user_global' namespace is only used by embedded IPython instances,
676 and it contains module-level globals. You can add namespaces to the
676 and it contains module-level globals. You can add namespaces to the
677 search with -s or exclude them with -e (these options can be given
677 search with -s or exclude them with -e (these options can be given
678 more than once).
678 more than once).
679
679
680 Examples:
680 Examples:
681
681
682 %psearch a* -> objects beginning with an a
682 %psearch a* -> objects beginning with an a
683 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
683 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
684 %psearch a* function -> all functions beginning with an a
684 %psearch a* function -> all functions beginning with an a
685 %psearch re.e* -> objects beginning with an e in module re
685 %psearch re.e* -> objects beginning with an e in module re
686 %psearch r*.e* -> objects that start with e in modules starting in r
686 %psearch r*.e* -> objects that start with e in modules starting in r
687 %psearch r*.* string -> all strings in modules beginning with r
687 %psearch r*.* string -> all strings in modules beginning with r
688
688
689 Case sensitve search:
689 Case sensitve search:
690
690
691 %psearch -c a* list all object beginning with lower case a
691 %psearch -c a* list all object beginning with lower case a
692
692
693 Show objects beginning with a single _:
693 Show objects beginning with a single _:
694
694
695 %psearch -a _* list objects beginning with a single underscore"""
695 %psearch -a _* list objects beginning with a single underscore"""
696 try:
696 try:
697 parameter_s = parameter_s.encode('ascii')
697 parameter_s = parameter_s.encode('ascii')
698 except UnicodeEncodeError:
698 except UnicodeEncodeError:
699 print 'Python identifiers can only contain ascii characters.'
699 print 'Python identifiers can only contain ascii characters.'
700 return
700 return
701
701
702 # default namespaces to be searched
702 # default namespaces to be searched
703 def_search = ['user','builtin']
703 def_search = ['user','builtin']
704
704
705 # Process options/args
705 # Process options/args
706 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
706 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
707 opt = opts.get
707 opt = opts.get
708 shell = self.shell
708 shell = self.shell
709 psearch = shell.inspector.psearch
709 psearch = shell.inspector.psearch
710
710
711 # select case options
711 # select case options
712 if opts.has_key('i'):
712 if opts.has_key('i'):
713 ignore_case = True
713 ignore_case = True
714 elif opts.has_key('c'):
714 elif opts.has_key('c'):
715 ignore_case = False
715 ignore_case = False
716 else:
716 else:
717 ignore_case = not shell.wildcards_case_sensitive
717 ignore_case = not shell.wildcards_case_sensitive
718
718
719 # Build list of namespaces to search from user options
719 # Build list of namespaces to search from user options
720 def_search.extend(opt('s',[]))
720 def_search.extend(opt('s',[]))
721 ns_exclude = ns_exclude=opt('e',[])
721 ns_exclude = ns_exclude=opt('e',[])
722 ns_search = [nm for nm in def_search if nm not in ns_exclude]
722 ns_search = [nm for nm in def_search if nm not in ns_exclude]
723
723
724 # Call the actual search
724 # Call the actual search
725 try:
725 try:
726 psearch(args,shell.ns_table,ns_search,
726 psearch(args,shell.ns_table,ns_search,
727 show_all=opt('a'),ignore_case=ignore_case)
727 show_all=opt('a'),ignore_case=ignore_case)
728 except:
728 except:
729 shell.showtraceback()
729 shell.showtraceback()
730
730
731 @skip_doctest
731 @skip_doctest
732 def magic_who_ls(self, parameter_s=''):
732 def magic_who_ls(self, parameter_s=''):
733 """Return a sorted list of all interactive variables.
733 """Return a sorted list of all interactive variables.
734
734
735 If arguments are given, only variables of types matching these
735 If arguments are given, only variables of types matching these
736 arguments are returned.
736 arguments are returned.
737
737
738 Examples
738 Examples
739 --------
739 --------
740
740
741 Define two variables and list them with who_ls::
741 Define two variables and list them with who_ls::
742
742
743 In [1]: alpha = 123
743 In [1]: alpha = 123
744
744
745 In [2]: beta = 'test'
745 In [2]: beta = 'test'
746
746
747 In [3]: %who_ls
747 In [3]: %who_ls
748 Out[3]: ['alpha', 'beta']
748 Out[3]: ['alpha', 'beta']
749
749
750 In [4]: %who_ls int
750 In [4]: %who_ls int
751 Out[4]: ['alpha']
751 Out[4]: ['alpha']
752
752
753 In [5]: %who_ls str
753 In [5]: %who_ls str
754 Out[5]: ['beta']
754 Out[5]: ['beta']
755 """
755 """
756
756
757 user_ns = self.shell.user_ns
757 user_ns = self.shell.user_ns
758 internal_ns = self.shell.internal_ns
758 internal_ns = self.shell.internal_ns
759 user_ns_hidden = self.shell.user_ns_hidden
759 user_ns_hidden = self.shell.user_ns_hidden
760 out = [ i for i in user_ns
760 out = [ i for i in user_ns
761 if not i.startswith('_') \
761 if not i.startswith('_') \
762 and not (i in internal_ns or i in user_ns_hidden) ]
762 and not (i in internal_ns or i in user_ns_hidden) ]
763
763
764 typelist = parameter_s.split()
764 typelist = parameter_s.split()
765 if typelist:
765 if typelist:
766 typeset = set(typelist)
766 typeset = set(typelist)
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
767 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
768
768
769 out.sort()
769 out.sort()
770 return out
770 return out
771
771
772 @skip_doctest
772 @skip_doctest
773 def magic_who(self, parameter_s=''):
773 def magic_who(self, parameter_s=''):
774 """Print all interactive variables, with some minimal formatting.
774 """Print all interactive variables, with some minimal formatting.
775
775
776 If any arguments are given, only variables whose type matches one of
776 If any arguments are given, only variables whose type matches one of
777 these are printed. For example:
777 these are printed. For example:
778
778
779 %who function str
779 %who function str
780
780
781 will only list functions and strings, excluding all other types of
781 will only list functions and strings, excluding all other types of
782 variables. To find the proper type names, simply use type(var) at a
782 variables. To find the proper type names, simply use type(var) at a
783 command line to see how python prints type names. For example:
783 command line to see how python prints type names. For example:
784
784
785 In [1]: type('hello')\\
785 In [1]: type('hello')\\
786 Out[1]: <type 'str'>
786 Out[1]: <type 'str'>
787
787
788 indicates that the type name for strings is 'str'.
788 indicates that the type name for strings is 'str'.
789
789
790 %who always excludes executed names loaded through your configuration
790 %who always excludes executed names loaded through your configuration
791 file and things which are internal to IPython.
791 file and things which are internal to IPython.
792
792
793 This is deliberate, as typically you may load many modules and the
793 This is deliberate, as typically you may load many modules and the
794 purpose of %who is to show you only what you've manually defined.
794 purpose of %who is to show you only what you've manually defined.
795
795
796 Examples
796 Examples
797 --------
797 --------
798
798
799 Define two variables and list them with who::
799 Define two variables and list them with who::
800
800
801 In [1]: alpha = 123
801 In [1]: alpha = 123
802
802
803 In [2]: beta = 'test'
803 In [2]: beta = 'test'
804
804
805 In [3]: %who
805 In [3]: %who
806 alpha beta
806 alpha beta
807
807
808 In [4]: %who int
808 In [4]: %who int
809 alpha
809 alpha
810
810
811 In [5]: %who str
811 In [5]: %who str
812 beta
812 beta
813 """
813 """
814
814
815 varlist = self.magic_who_ls(parameter_s)
815 varlist = self.magic_who_ls(parameter_s)
816 if not varlist:
816 if not varlist:
817 if parameter_s:
817 if parameter_s:
818 print 'No variables match your requested type.'
818 print 'No variables match your requested type.'
819 else:
819 else:
820 print 'Interactive namespace is empty.'
820 print 'Interactive namespace is empty.'
821 return
821 return
822
822
823 # if we have variables, move on...
823 # if we have variables, move on...
824 count = 0
824 count = 0
825 for i in varlist:
825 for i in varlist:
826 print i+'\t',
826 print i+'\t',
827 count += 1
827 count += 1
828 if count > 8:
828 if count > 8:
829 count = 0
829 count = 0
830 print
830 print
831 print
831 print
832
832
833 @skip_doctest
833 @skip_doctest
834 def magic_whos(self, parameter_s=''):
834 def magic_whos(self, parameter_s=''):
835 """Like %who, but gives some extra information about each variable.
835 """Like %who, but gives some extra information about each variable.
836
836
837 The same type filtering of %who can be applied here.
837 The same type filtering of %who can be applied here.
838
838
839 For all variables, the type is printed. Additionally it prints:
839 For all variables, the type is printed. Additionally it prints:
840
840
841 - For {},[],(): their length.
841 - For {},[],(): their length.
842
842
843 - For numpy arrays, a summary with shape, number of
843 - For numpy arrays, a summary with shape, number of
844 elements, typecode and size in memory.
844 elements, typecode and size in memory.
845
845
846 - Everything else: a string representation, snipping their middle if
846 - Everything else: a string representation, snipping their middle if
847 too long.
847 too long.
848
848
849 Examples
849 Examples
850 --------
850 --------
851
851
852 Define two variables and list them with whos::
852 Define two variables and list them with whos::
853
853
854 In [1]: alpha = 123
854 In [1]: alpha = 123
855
855
856 In [2]: beta = 'test'
856 In [2]: beta = 'test'
857
857
858 In [3]: %whos
858 In [3]: %whos
859 Variable Type Data/Info
859 Variable Type Data/Info
860 --------------------------------
860 --------------------------------
861 alpha int 123
861 alpha int 123
862 beta str test
862 beta str test
863 """
863 """
864
864
865 varnames = self.magic_who_ls(parameter_s)
865 varnames = self.magic_who_ls(parameter_s)
866 if not varnames:
866 if not varnames:
867 if parameter_s:
867 if parameter_s:
868 print 'No variables match your requested type.'
868 print 'No variables match your requested type.'
869 else:
869 else:
870 print 'Interactive namespace is empty.'
870 print 'Interactive namespace is empty.'
871 return
871 return
872
872
873 # if we have variables, move on...
873 # if we have variables, move on...
874
874
875 # for these types, show len() instead of data:
875 # for these types, show len() instead of data:
876 seq_types = ['dict', 'list', 'tuple']
876 seq_types = ['dict', 'list', 'tuple']
877
877
878 # for numpy/Numeric arrays, display summary info
878 # for numpy/Numeric arrays, display summary info
879 try:
879 try:
880 import numpy
880 import numpy
881 except ImportError:
881 except ImportError:
882 ndarray_type = None
882 ndarray_type = None
883 else:
883 else:
884 ndarray_type = numpy.ndarray.__name__
884 ndarray_type = numpy.ndarray.__name__
885 try:
885 try:
886 import Numeric
886 import Numeric
887 except ImportError:
887 except ImportError:
888 array_type = None
888 array_type = None
889 else:
889 else:
890 array_type = Numeric.ArrayType.__name__
890 array_type = Numeric.ArrayType.__name__
891
891
892 # Find all variable names and types so we can figure out column sizes
892 # Find all variable names and types so we can figure out column sizes
893 def get_vars(i):
893 def get_vars(i):
894 return self.shell.user_ns[i]
894 return self.shell.user_ns[i]
895
895
896 # some types are well known and can be shorter
896 # some types are well known and can be shorter
897 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
897 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
898 def type_name(v):
898 def type_name(v):
899 tn = type(v).__name__
899 tn = type(v).__name__
900 return abbrevs.get(tn,tn)
900 return abbrevs.get(tn,tn)
901
901
902 varlist = map(get_vars,varnames)
902 varlist = map(get_vars,varnames)
903
903
904 typelist = []
904 typelist = []
905 for vv in varlist:
905 for vv in varlist:
906 tt = type_name(vv)
906 tt = type_name(vv)
907
907
908 if tt=='instance':
908 if tt=='instance':
909 typelist.append( abbrevs.get(str(vv.__class__),
909 typelist.append( abbrevs.get(str(vv.__class__),
910 str(vv.__class__)))
910 str(vv.__class__)))
911 else:
911 else:
912 typelist.append(tt)
912 typelist.append(tt)
913
913
914 # column labels and # of spaces as separator
914 # column labels and # of spaces as separator
915 varlabel = 'Variable'
915 varlabel = 'Variable'
916 typelabel = 'Type'
916 typelabel = 'Type'
917 datalabel = 'Data/Info'
917 datalabel = 'Data/Info'
918 colsep = 3
918 colsep = 3
919 # variable format strings
919 # variable format strings
920 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
920 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
921 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
921 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
922 aformat = "%s: %s elems, type `%s`, %s bytes"
922 aformat = "%s: %s elems, type `%s`, %s bytes"
923 # find the size of the columns to format the output nicely
923 # find the size of the columns to format the output nicely
924 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
924 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
925 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
925 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
926 # table header
926 # table header
927 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
927 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
928 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
928 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
929 # and the table itself
929 # and the table itself
930 kb = 1024
930 kb = 1024
931 Mb = 1048576 # kb**2
931 Mb = 1048576 # kb**2
932 for vname,var,vtype in zip(varnames,varlist,typelist):
932 for vname,var,vtype in zip(varnames,varlist,typelist):
933 print itpl(vformat),
933 print itpl(vformat),
934 if vtype in seq_types:
934 if vtype in seq_types:
935 print "n="+str(len(var))
935 print "n="+str(len(var))
936 elif vtype in [array_type,ndarray_type]:
936 elif vtype in [array_type,ndarray_type]:
937 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
937 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
938 if vtype==ndarray_type:
938 if vtype==ndarray_type:
939 # numpy
939 # numpy
940 vsize = var.size
940 vsize = var.size
941 vbytes = vsize*var.itemsize
941 vbytes = vsize*var.itemsize
942 vdtype = var.dtype
942 vdtype = var.dtype
943 else:
943 else:
944 # Numeric
944 # Numeric
945 vsize = Numeric.size(var)
945 vsize = Numeric.size(var)
946 vbytes = vsize*var.itemsize()
946 vbytes = vsize*var.itemsize()
947 vdtype = var.typecode()
947 vdtype = var.typecode()
948
948
949 if vbytes < 100000:
949 if vbytes < 100000:
950 print aformat % (vshape,vsize,vdtype,vbytes)
950 print aformat % (vshape,vsize,vdtype,vbytes)
951 else:
951 else:
952 print aformat % (vshape,vsize,vdtype,vbytes),
952 print aformat % (vshape,vsize,vdtype,vbytes),
953 if vbytes < Mb:
953 if vbytes < Mb:
954 print '(%s kb)' % (vbytes/kb,)
954 print '(%s kb)' % (vbytes/kb,)
955 else:
955 else:
956 print '(%s Mb)' % (vbytes/Mb,)
956 print '(%s Mb)' % (vbytes/Mb,)
957 else:
957 else:
958 try:
958 try:
959 vstr = str(var)
959 vstr = str(var)
960 except UnicodeEncodeError:
960 except UnicodeEncodeError:
961 vstr = unicode(var).encode(sys.getdefaultencoding(),
961 vstr = unicode(var).encode(sys.getdefaultencoding(),
962 'backslashreplace')
962 'backslashreplace')
963 vstr = vstr.replace('\n','\\n')
963 vstr = vstr.replace('\n','\\n')
964 if len(vstr) < 50:
964 if len(vstr) < 50:
965 print vstr
965 print vstr
966 else:
966 else:
967 printpl(vfmt_short)
967 printpl(vfmt_short)
968
968
969 def magic_reset(self, parameter_s=''):
969 def magic_reset(self, parameter_s=''):
970 """Resets the namespace by removing all names defined by the user.
970 """Resets the namespace by removing all names defined by the user.
971
971
972 Parameters
972 Parameters
973 ----------
973 ----------
974 -f : force reset without asking for confirmation.
974 -f : force reset without asking for confirmation.
975
975
976 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
976 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
977 References to objects may be kept. By default (without this option),
977 References to objects may be kept. By default (without this option),
978 we do a 'hard' reset, giving you a new session and removing all
978 we do a 'hard' reset, giving you a new session and removing all
979 references to objects from the current session.
979 references to objects from the current session.
980
980
981 Examples
981 Examples
982 --------
982 --------
983 In [6]: a = 1
983 In [6]: a = 1
984
984
985 In [7]: a
985 In [7]: a
986 Out[7]: 1
986 Out[7]: 1
987
987
988 In [8]: 'a' in _ip.user_ns
988 In [8]: 'a' in _ip.user_ns
989 Out[8]: True
989 Out[8]: True
990
990
991 In [9]: %reset -f
991 In [9]: %reset -f
992
992
993 In [1]: 'a' in _ip.user_ns
993 In [1]: 'a' in _ip.user_ns
994 Out[1]: False
994 Out[1]: False
995 """
995 """
996 opts, args = self.parse_options(parameter_s,'sf')
996 opts, args = self.parse_options(parameter_s,'sf')
997 if 'f' in opts:
997 if 'f' in opts:
998 ans = True
998 ans = True
999 else:
999 else:
1000 ans = self.shell.ask_yes_no(
1000 ans = self.shell.ask_yes_no(
1001 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1001 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1002 if not ans:
1002 if not ans:
1003 print 'Nothing done.'
1003 print 'Nothing done.'
1004 return
1004 return
1005
1005
1006 if 's' in opts: # Soft reset
1006 if 's' in opts: # Soft reset
1007 user_ns = self.shell.user_ns
1007 user_ns = self.shell.user_ns
1008 for i in self.magic_who_ls():
1008 for i in self.magic_who_ls():
1009 del(user_ns[i])
1009 del(user_ns[i])
1010
1010
1011 else: # Hard reset
1011 else: # Hard reset
1012 self.shell.reset(new_session = False)
1012 self.shell.reset(new_session = False)
1013
1013
1014
1014
1015
1015
1016 def magic_reset_selective(self, parameter_s=''):
1016 def magic_reset_selective(self, parameter_s=''):
1017 """Resets the namespace by removing names defined by the user.
1017 """Resets the namespace by removing names defined by the user.
1018
1018
1019 Input/Output history are left around in case you need them.
1019 Input/Output history are left around in case you need them.
1020
1020
1021 %reset_selective [-f] regex
1021 %reset_selective [-f] regex
1022
1022
1023 No action is taken if regex is not included
1023 No action is taken if regex is not included
1024
1024
1025 Options
1025 Options
1026 -f : force reset without asking for confirmation.
1026 -f : force reset without asking for confirmation.
1027
1027
1028 Examples
1028 Examples
1029 --------
1029 --------
1030
1030
1031 We first fully reset the namespace so your output looks identical to
1031 We first fully reset the namespace so your output looks identical to
1032 this example for pedagogical reasons; in practice you do not need a
1032 this example for pedagogical reasons; in practice you do not need a
1033 full reset.
1033 full reset.
1034
1034
1035 In [1]: %reset -f
1035 In [1]: %reset -f
1036
1036
1037 Now, with a clean namespace we can make a few variables and use
1037 Now, with a clean namespace we can make a few variables and use
1038 %reset_selective to only delete names that match our regexp:
1038 %reset_selective to only delete names that match our regexp:
1039
1039
1040 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1040 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1041
1041
1042 In [3]: who_ls
1042 In [3]: who_ls
1043 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1043 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1044
1044
1045 In [4]: %reset_selective -f b[2-3]m
1045 In [4]: %reset_selective -f b[2-3]m
1046
1046
1047 In [5]: who_ls
1047 In [5]: who_ls
1048 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1048 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1049
1049
1050 In [6]: %reset_selective -f d
1050 In [6]: %reset_selective -f d
1051
1051
1052 In [7]: who_ls
1052 In [7]: who_ls
1053 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1053 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1054
1054
1055 In [8]: %reset_selective -f c
1055 In [8]: %reset_selective -f c
1056
1056
1057 In [9]: who_ls
1057 In [9]: who_ls
1058 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1058 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1059
1059
1060 In [10]: %reset_selective -f b
1060 In [10]: %reset_selective -f b
1061
1061
1062 In [11]: who_ls
1062 In [11]: who_ls
1063 Out[11]: ['a']
1063 Out[11]: ['a']
1064 """
1064 """
1065
1065
1066 opts, regex = self.parse_options(parameter_s,'f')
1066 opts, regex = self.parse_options(parameter_s,'f')
1067
1067
1068 if opts.has_key('f'):
1068 if opts.has_key('f'):
1069 ans = True
1069 ans = True
1070 else:
1070 else:
1071 ans = self.shell.ask_yes_no(
1071 ans = self.shell.ask_yes_no(
1072 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1072 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1073 if not ans:
1073 if not ans:
1074 print 'Nothing done.'
1074 print 'Nothing done.'
1075 return
1075 return
1076 user_ns = self.shell.user_ns
1076 user_ns = self.shell.user_ns
1077 if not regex:
1077 if not regex:
1078 print 'No regex pattern specified. Nothing done.'
1078 print 'No regex pattern specified. Nothing done.'
1079 return
1079 return
1080 else:
1080 else:
1081 try:
1081 try:
1082 m = re.compile(regex)
1082 m = re.compile(regex)
1083 except TypeError:
1083 except TypeError:
1084 raise TypeError('regex must be a string or compiled pattern')
1084 raise TypeError('regex must be a string or compiled pattern')
1085 for i in self.magic_who_ls():
1085 for i in self.magic_who_ls():
1086 if m.search(i):
1086 if m.search(i):
1087 del(user_ns[i])
1087 del(user_ns[i])
1088
1089 def magic_xdel(self, parameter_s=''):
1090 """Delete a variable, trying to clear it from anywhere that
1091 IPython's machinery has references to it. By default, this uses
1092 the identity of the named object in the user namespace to remove
1093 references held under other names. The object is also removed
1094 from the output history.
1095
1096 Options
1097 -n : Delete the specified name from all namespaces, without
1098 checking their identity.
1099 """
1100 opts, varname = self.parse_options(parameter_s,'n')
1101 try:
1102 self.shell.del_var(varname, ('n' in opts))
1103 except (NameError, ValueError) as e:
1104 print type(e).__name__ +": "+ str(e)
1088
1105
1089 def magic_logstart(self,parameter_s=''):
1106 def magic_logstart(self,parameter_s=''):
1090 """Start logging anywhere in a session.
1107 """Start logging anywhere in a session.
1091
1108
1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1109 %logstart [-o|-r|-t] [log_name [log_mode]]
1093
1110
1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1111 If no name is given, it defaults to a file named 'ipython_log.py' in your
1095 current directory, in 'rotate' mode (see below).
1112 current directory, in 'rotate' mode (see below).
1096
1113
1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1114 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1098 history up to that point and then continues logging.
1115 history up to that point and then continues logging.
1099
1116
1100 %logstart takes a second optional parameter: logging mode. This can be one
1117 %logstart takes a second optional parameter: logging mode. This can be one
1101 of (note that the modes are given unquoted):\\
1118 of (note that the modes are given unquoted):\\
1102 append: well, that says it.\\
1119 append: well, that says it.\\
1103 backup: rename (if exists) to name~ and start name.\\
1120 backup: rename (if exists) to name~ and start name.\\
1104 global: single logfile in your home dir, appended to.\\
1121 global: single logfile in your home dir, appended to.\\
1105 over : overwrite existing log.\\
1122 over : overwrite existing log.\\
1106 rotate: create rotating logs name.1~, name.2~, etc.
1123 rotate: create rotating logs name.1~, name.2~, etc.
1107
1124
1108 Options:
1125 Options:
1109
1126
1110 -o: log also IPython's output. In this mode, all commands which
1127 -o: log also IPython's output. In this mode, all commands which
1111 generate an Out[NN] prompt are recorded to the logfile, right after
1128 generate an Out[NN] prompt are recorded to the logfile, right after
1112 their corresponding input line. The output lines are always
1129 their corresponding input line. The output lines are always
1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1130 prepended with a '#[Out]# ' marker, so that the log remains valid
1114 Python code.
1131 Python code.
1115
1132
1116 Since this marker is always the same, filtering only the output from
1133 Since this marker is always the same, filtering only the output from
1117 a log is very easy, using for example a simple awk call:
1134 a log is very easy, using for example a simple awk call:
1118
1135
1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1136 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1120
1137
1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1138 -r: log 'raw' input. Normally, IPython's logs contain the processed
1122 input, so that user lines are logged in their final form, converted
1139 input, so that user lines are logged in their final form, converted
1123 into valid Python. For example, %Exit is logged as
1140 into valid Python. For example, %Exit is logged as
1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1141 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1125 exactly as typed, with no transformations applied.
1142 exactly as typed, with no transformations applied.
1126
1143
1127 -t: put timestamps before each input line logged (these are put in
1144 -t: put timestamps before each input line logged (these are put in
1128 comments)."""
1145 comments)."""
1129
1146
1130 opts,par = self.parse_options(parameter_s,'ort')
1147 opts,par = self.parse_options(parameter_s,'ort')
1131 log_output = 'o' in opts
1148 log_output = 'o' in opts
1132 log_raw_input = 'r' in opts
1149 log_raw_input = 'r' in opts
1133 timestamp = 't' in opts
1150 timestamp = 't' in opts
1134
1151
1135 logger = self.shell.logger
1152 logger = self.shell.logger
1136
1153
1137 # if no args are given, the defaults set in the logger constructor by
1154 # if no args are given, the defaults set in the logger constructor by
1138 # ipytohn remain valid
1155 # ipytohn remain valid
1139 if par:
1156 if par:
1140 try:
1157 try:
1141 logfname,logmode = par.split()
1158 logfname,logmode = par.split()
1142 except:
1159 except:
1143 logfname = par
1160 logfname = par
1144 logmode = 'backup'
1161 logmode = 'backup'
1145 else:
1162 else:
1146 logfname = logger.logfname
1163 logfname = logger.logfname
1147 logmode = logger.logmode
1164 logmode = logger.logmode
1148 # put logfname into rc struct as if it had been called on the command
1165 # put logfname into rc struct as if it had been called on the command
1149 # line, so it ends up saved in the log header Save it in case we need
1166 # line, so it ends up saved in the log header Save it in case we need
1150 # to restore it...
1167 # to restore it...
1151 old_logfile = self.shell.logfile
1168 old_logfile = self.shell.logfile
1152 if logfname:
1169 if logfname:
1153 logfname = os.path.expanduser(logfname)
1170 logfname = os.path.expanduser(logfname)
1154 self.shell.logfile = logfname
1171 self.shell.logfile = logfname
1155
1172
1156 loghead = '# IPython log file\n\n'
1173 loghead = '# IPython log file\n\n'
1157 try:
1174 try:
1158 started = logger.logstart(logfname,loghead,logmode,
1175 started = logger.logstart(logfname,loghead,logmode,
1159 log_output,timestamp,log_raw_input)
1176 log_output,timestamp,log_raw_input)
1160 except:
1177 except:
1161 self.shell.logfile = old_logfile
1178 self.shell.logfile = old_logfile
1162 warn("Couldn't start log: %s" % sys.exc_info()[1])
1179 warn("Couldn't start log: %s" % sys.exc_info()[1])
1163 else:
1180 else:
1164 # log input history up to this point, optionally interleaving
1181 # log input history up to this point, optionally interleaving
1165 # output if requested
1182 # output if requested
1166
1183
1167 if timestamp:
1184 if timestamp:
1168 # disable timestamping for the previous history, since we've
1185 # disable timestamping for the previous history, since we've
1169 # lost those already (no time machine here).
1186 # lost those already (no time machine here).
1170 logger.timestamp = False
1187 logger.timestamp = False
1171
1188
1172 if log_raw_input:
1189 if log_raw_input:
1173 input_hist = self.shell.history_manager.input_hist_raw
1190 input_hist = self.shell.history_manager.input_hist_raw
1174 else:
1191 else:
1175 input_hist = self.shell.history_manager.input_hist_parsed
1192 input_hist = self.shell.history_manager.input_hist_parsed
1176
1193
1177 if log_output:
1194 if log_output:
1178 log_write = logger.log_write
1195 log_write = logger.log_write
1179 output_hist = self.shell.history_manager.output_hist
1196 output_hist = self.shell.history_manager.output_hist
1180 for n in range(1,len(input_hist)-1):
1197 for n in range(1,len(input_hist)-1):
1181 log_write(input_hist[n].rstrip() + '\n')
1198 log_write(input_hist[n].rstrip() + '\n')
1182 if n in output_hist:
1199 if n in output_hist:
1183 log_write(repr(output_hist[n]),'output')
1200 log_write(repr(output_hist[n]),'output')
1184 else:
1201 else:
1185 logger.log_write('\n'.join(input_hist[1:]))
1202 logger.log_write('\n'.join(input_hist[1:]))
1186 logger.log_write('\n')
1203 logger.log_write('\n')
1187 if timestamp:
1204 if timestamp:
1188 # re-enable timestamping
1205 # re-enable timestamping
1189 logger.timestamp = True
1206 logger.timestamp = True
1190
1207
1191 print ('Activating auto-logging. '
1208 print ('Activating auto-logging. '
1192 'Current session state plus future input saved.')
1209 'Current session state plus future input saved.')
1193 logger.logstate()
1210 logger.logstate()
1194
1211
1195 def magic_logstop(self,parameter_s=''):
1212 def magic_logstop(self,parameter_s=''):
1196 """Fully stop logging and close log file.
1213 """Fully stop logging and close log file.
1197
1214
1198 In order to start logging again, a new %logstart call needs to be made,
1215 In order to start logging again, a new %logstart call needs to be made,
1199 possibly (though not necessarily) with a new filename, mode and other
1216 possibly (though not necessarily) with a new filename, mode and other
1200 options."""
1217 options."""
1201 self.logger.logstop()
1218 self.logger.logstop()
1202
1219
1203 def magic_logoff(self,parameter_s=''):
1220 def magic_logoff(self,parameter_s=''):
1204 """Temporarily stop logging.
1221 """Temporarily stop logging.
1205
1222
1206 You must have previously started logging."""
1223 You must have previously started logging."""
1207 self.shell.logger.switch_log(0)
1224 self.shell.logger.switch_log(0)
1208
1225
1209 def magic_logon(self,parameter_s=''):
1226 def magic_logon(self,parameter_s=''):
1210 """Restart logging.
1227 """Restart logging.
1211
1228
1212 This function is for restarting logging which you've temporarily
1229 This function is for restarting logging which you've temporarily
1213 stopped with %logoff. For starting logging for the first time, you
1230 stopped with %logoff. For starting logging for the first time, you
1214 must use the %logstart function, which allows you to specify an
1231 must use the %logstart function, which allows you to specify an
1215 optional log filename."""
1232 optional log filename."""
1216
1233
1217 self.shell.logger.switch_log(1)
1234 self.shell.logger.switch_log(1)
1218
1235
1219 def magic_logstate(self,parameter_s=''):
1236 def magic_logstate(self,parameter_s=''):
1220 """Print the status of the logging system."""
1237 """Print the status of the logging system."""
1221
1238
1222 self.shell.logger.logstate()
1239 self.shell.logger.logstate()
1223
1240
1224 def magic_pdb(self, parameter_s=''):
1241 def magic_pdb(self, parameter_s=''):
1225 """Control the automatic calling of the pdb interactive debugger.
1242 """Control the automatic calling of the pdb interactive debugger.
1226
1243
1227 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1244 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 argument it works as a toggle.
1245 argument it works as a toggle.
1229
1246
1230 When an exception is triggered, IPython can optionally call the
1247 When an exception is triggered, IPython can optionally call the
1231 interactive pdb debugger after the traceback printout. %pdb toggles
1248 interactive pdb debugger after the traceback printout. %pdb toggles
1232 this feature on and off.
1249 this feature on and off.
1233
1250
1234 The initial state of this feature is set in your ipythonrc
1251 The initial state of this feature is set in your ipythonrc
1235 configuration file (the variable is called 'pdb').
1252 configuration file (the variable is called 'pdb').
1236
1253
1237 If you want to just activate the debugger AFTER an exception has fired,
1254 If you want to just activate the debugger AFTER an exception has fired,
1238 without having to type '%pdb on' and rerunning your code, you can use
1255 without having to type '%pdb on' and rerunning your code, you can use
1239 the %debug magic."""
1256 the %debug magic."""
1240
1257
1241 par = parameter_s.strip().lower()
1258 par = parameter_s.strip().lower()
1242
1259
1243 if par:
1260 if par:
1244 try:
1261 try:
1245 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1262 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 except KeyError:
1263 except KeyError:
1247 print ('Incorrect argument. Use on/1, off/0, '
1264 print ('Incorrect argument. Use on/1, off/0, '
1248 'or nothing for a toggle.')
1265 'or nothing for a toggle.')
1249 return
1266 return
1250 else:
1267 else:
1251 # toggle
1268 # toggle
1252 new_pdb = not self.shell.call_pdb
1269 new_pdb = not self.shell.call_pdb
1253
1270
1254 # set on the shell
1271 # set on the shell
1255 self.shell.call_pdb = new_pdb
1272 self.shell.call_pdb = new_pdb
1256 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1273 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257
1274
1258 def magic_debug(self, parameter_s=''):
1275 def magic_debug(self, parameter_s=''):
1259 """Activate the interactive debugger in post-mortem mode.
1276 """Activate the interactive debugger in post-mortem mode.
1260
1277
1261 If an exception has just occurred, this lets you inspect its stack
1278 If an exception has just occurred, this lets you inspect its stack
1262 frames interactively. Note that this will always work only on the last
1279 frames interactively. Note that this will always work only on the last
1263 traceback that occurred, so you must call this quickly after an
1280 traceback that occurred, so you must call this quickly after an
1264 exception that you wish to inspect has fired, because if another one
1281 exception that you wish to inspect has fired, because if another one
1265 occurs, it clobbers the previous one.
1282 occurs, it clobbers the previous one.
1266
1283
1267 If you want IPython to automatically do this on every exception, see
1284 If you want IPython to automatically do this on every exception, see
1268 the %pdb magic for more details.
1285 the %pdb magic for more details.
1269 """
1286 """
1270 self.shell.debugger(force=True)
1287 self.shell.debugger(force=True)
1271
1288
1272 @skip_doctest
1289 @skip_doctest
1273 def magic_prun(self, parameter_s ='',user_mode=1,
1290 def magic_prun(self, parameter_s ='',user_mode=1,
1274 opts=None,arg_lst=None,prog_ns=None):
1291 opts=None,arg_lst=None,prog_ns=None):
1275
1292
1276 """Run a statement through the python code profiler.
1293 """Run a statement through the python code profiler.
1277
1294
1278 Usage:
1295 Usage:
1279 %prun [options] statement
1296 %prun [options] statement
1280
1297
1281 The given statement (which doesn't require quote marks) is run via the
1298 The given statement (which doesn't require quote marks) is run via the
1282 python profiler in a manner similar to the profile.run() function.
1299 python profiler in a manner similar to the profile.run() function.
1283 Namespaces are internally managed to work correctly; profile.run
1300 Namespaces are internally managed to work correctly; profile.run
1284 cannot be used in IPython because it makes certain assumptions about
1301 cannot be used in IPython because it makes certain assumptions about
1285 namespaces which do not hold under IPython.
1302 namespaces which do not hold under IPython.
1286
1303
1287 Options:
1304 Options:
1288
1305
1289 -l <limit>: you can place restrictions on what or how much of the
1306 -l <limit>: you can place restrictions on what or how much of the
1290 profile gets printed. The limit value can be:
1307 profile gets printed. The limit value can be:
1291
1308
1292 * A string: only information for function names containing this string
1309 * A string: only information for function names containing this string
1293 is printed.
1310 is printed.
1294
1311
1295 * An integer: only these many lines are printed.
1312 * An integer: only these many lines are printed.
1296
1313
1297 * A float (between 0 and 1): this fraction of the report is printed
1314 * A float (between 0 and 1): this fraction of the report is printed
1298 (for example, use a limit of 0.4 to see the topmost 40% only).
1315 (for example, use a limit of 0.4 to see the topmost 40% only).
1299
1316
1300 You can combine several limits with repeated use of the option. For
1317 You can combine several limits with repeated use of the option. For
1301 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1318 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1302 information about class constructors.
1319 information about class constructors.
1303
1320
1304 -r: return the pstats.Stats object generated by the profiling. This
1321 -r: return the pstats.Stats object generated by the profiling. This
1305 object has all the information about the profile in it, and you can
1322 object has all the information about the profile in it, and you can
1306 later use it for further analysis or in other functions.
1323 later use it for further analysis or in other functions.
1307
1324
1308 -s <key>: sort profile by given key. You can provide more than one key
1325 -s <key>: sort profile by given key. You can provide more than one key
1309 by using the option several times: '-s key1 -s key2 -s key3...'. The
1326 by using the option several times: '-s key1 -s key2 -s key3...'. The
1310 default sorting key is 'time'.
1327 default sorting key is 'time'.
1311
1328
1312 The following is copied verbatim from the profile documentation
1329 The following is copied verbatim from the profile documentation
1313 referenced below:
1330 referenced below:
1314
1331
1315 When more than one key is provided, additional keys are used as
1332 When more than one key is provided, additional keys are used as
1316 secondary criteria when the there is equality in all keys selected
1333 secondary criteria when the there is equality in all keys selected
1317 before them.
1334 before them.
1318
1335
1319 Abbreviations can be used for any key names, as long as the
1336 Abbreviations can be used for any key names, as long as the
1320 abbreviation is unambiguous. The following are the keys currently
1337 abbreviation is unambiguous. The following are the keys currently
1321 defined:
1338 defined:
1322
1339
1323 Valid Arg Meaning
1340 Valid Arg Meaning
1324 "calls" call count
1341 "calls" call count
1325 "cumulative" cumulative time
1342 "cumulative" cumulative time
1326 "file" file name
1343 "file" file name
1327 "module" file name
1344 "module" file name
1328 "pcalls" primitive call count
1345 "pcalls" primitive call count
1329 "line" line number
1346 "line" line number
1330 "name" function name
1347 "name" function name
1331 "nfl" name/file/line
1348 "nfl" name/file/line
1332 "stdname" standard name
1349 "stdname" standard name
1333 "time" internal time
1350 "time" internal time
1334
1351
1335 Note that all sorts on statistics are in descending order (placing
1352 Note that all sorts on statistics are in descending order (placing
1336 most time consuming items first), where as name, file, and line number
1353 most time consuming items first), where as name, file, and line number
1337 searches are in ascending order (i.e., alphabetical). The subtle
1354 searches are in ascending order (i.e., alphabetical). The subtle
1338 distinction between "nfl" and "stdname" is that the standard name is a
1355 distinction between "nfl" and "stdname" is that the standard name is a
1339 sort of the name as printed, which means that the embedded line
1356 sort of the name as printed, which means that the embedded line
1340 numbers get compared in an odd way. For example, lines 3, 20, and 40
1357 numbers get compared in an odd way. For example, lines 3, 20, and 40
1341 would (if the file names were the same) appear in the string order
1358 would (if the file names were the same) appear in the string order
1342 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1359 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1343 line numbers. In fact, sort_stats("nfl") is the same as
1360 line numbers. In fact, sort_stats("nfl") is the same as
1344 sort_stats("name", "file", "line").
1361 sort_stats("name", "file", "line").
1345
1362
1346 -T <filename>: save profile results as shown on screen to a text
1363 -T <filename>: save profile results as shown on screen to a text
1347 file. The profile is still shown on screen.
1364 file. The profile is still shown on screen.
1348
1365
1349 -D <filename>: save (via dump_stats) profile statistics to given
1366 -D <filename>: save (via dump_stats) profile statistics to given
1350 filename. This data is in a format understod by the pstats module, and
1367 filename. This data is in a format understod by the pstats module, and
1351 is generated by a call to the dump_stats() method of profile
1368 is generated by a call to the dump_stats() method of profile
1352 objects. The profile is still shown on screen.
1369 objects. The profile is still shown on screen.
1353
1370
1354 If you want to run complete programs under the profiler's control, use
1371 If you want to run complete programs under the profiler's control, use
1355 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1372 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1356 contains profiler specific options as described here.
1373 contains profiler specific options as described here.
1357
1374
1358 You can read the complete documentation for the profile module with::
1375 You can read the complete documentation for the profile module with::
1359
1376
1360 In [1]: import profile; profile.help()
1377 In [1]: import profile; profile.help()
1361 """
1378 """
1362
1379
1363 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1380 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1364 # protect user quote marks
1381 # protect user quote marks
1365 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1382 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1366
1383
1367 if user_mode: # regular user call
1384 if user_mode: # regular user call
1368 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1385 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1369 list_all=1)
1386 list_all=1)
1370 namespace = self.shell.user_ns
1387 namespace = self.shell.user_ns
1371 else: # called to run a program by %run -p
1388 else: # called to run a program by %run -p
1372 try:
1389 try:
1373 filename = get_py_filename(arg_lst[0])
1390 filename = get_py_filename(arg_lst[0])
1374 except IOError,msg:
1391 except IOError,msg:
1375 error(msg)
1392 error(msg)
1376 return
1393 return
1377
1394
1378 arg_str = 'execfile(filename,prog_ns)'
1395 arg_str = 'execfile(filename,prog_ns)'
1379 namespace = locals()
1396 namespace = locals()
1380
1397
1381 opts.merge(opts_def)
1398 opts.merge(opts_def)
1382
1399
1383 prof = profile.Profile()
1400 prof = profile.Profile()
1384 try:
1401 try:
1385 prof = prof.runctx(arg_str,namespace,namespace)
1402 prof = prof.runctx(arg_str,namespace,namespace)
1386 sys_exit = ''
1403 sys_exit = ''
1387 except SystemExit:
1404 except SystemExit:
1388 sys_exit = """*** SystemExit exception caught in code being profiled."""
1405 sys_exit = """*** SystemExit exception caught in code being profiled."""
1389
1406
1390 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1407 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1391
1408
1392 lims = opts.l
1409 lims = opts.l
1393 if lims:
1410 if lims:
1394 lims = [] # rebuild lims with ints/floats/strings
1411 lims = [] # rebuild lims with ints/floats/strings
1395 for lim in opts.l:
1412 for lim in opts.l:
1396 try:
1413 try:
1397 lims.append(int(lim))
1414 lims.append(int(lim))
1398 except ValueError:
1415 except ValueError:
1399 try:
1416 try:
1400 lims.append(float(lim))
1417 lims.append(float(lim))
1401 except ValueError:
1418 except ValueError:
1402 lims.append(lim)
1419 lims.append(lim)
1403
1420
1404 # Trap output.
1421 # Trap output.
1405 stdout_trap = StringIO()
1422 stdout_trap = StringIO()
1406
1423
1407 if hasattr(stats,'stream'):
1424 if hasattr(stats,'stream'):
1408 # In newer versions of python, the stats object has a 'stream'
1425 # In newer versions of python, the stats object has a 'stream'
1409 # attribute to write into.
1426 # attribute to write into.
1410 stats.stream = stdout_trap
1427 stats.stream = stdout_trap
1411 stats.print_stats(*lims)
1428 stats.print_stats(*lims)
1412 else:
1429 else:
1413 # For older versions, we manually redirect stdout during printing
1430 # For older versions, we manually redirect stdout during printing
1414 sys_stdout = sys.stdout
1431 sys_stdout = sys.stdout
1415 try:
1432 try:
1416 sys.stdout = stdout_trap
1433 sys.stdout = stdout_trap
1417 stats.print_stats(*lims)
1434 stats.print_stats(*lims)
1418 finally:
1435 finally:
1419 sys.stdout = sys_stdout
1436 sys.stdout = sys_stdout
1420
1437
1421 output = stdout_trap.getvalue()
1438 output = stdout_trap.getvalue()
1422 output = output.rstrip()
1439 output = output.rstrip()
1423
1440
1424 page.page(output)
1441 page.page(output)
1425 print sys_exit,
1442 print sys_exit,
1426
1443
1427 dump_file = opts.D[0]
1444 dump_file = opts.D[0]
1428 text_file = opts.T[0]
1445 text_file = opts.T[0]
1429 if dump_file:
1446 if dump_file:
1430 prof.dump_stats(dump_file)
1447 prof.dump_stats(dump_file)
1431 print '\n*** Profile stats marshalled to file',\
1448 print '\n*** Profile stats marshalled to file',\
1432 `dump_file`+'.',sys_exit
1449 `dump_file`+'.',sys_exit
1433 if text_file:
1450 if text_file:
1434 pfile = file(text_file,'w')
1451 pfile = file(text_file,'w')
1435 pfile.write(output)
1452 pfile.write(output)
1436 pfile.close()
1453 pfile.close()
1437 print '\n*** Profile printout saved to text file',\
1454 print '\n*** Profile printout saved to text file',\
1438 `text_file`+'.',sys_exit
1455 `text_file`+'.',sys_exit
1439
1456
1440 if opts.has_key('r'):
1457 if opts.has_key('r'):
1441 return stats
1458 return stats
1442 else:
1459 else:
1443 return None
1460 return None
1444
1461
1445 @skip_doctest
1462 @skip_doctest
1446 def magic_run(self, parameter_s ='',runner=None,
1463 def magic_run(self, parameter_s ='',runner=None,
1447 file_finder=get_py_filename):
1464 file_finder=get_py_filename):
1448 """Run the named file inside IPython as a program.
1465 """Run the named file inside IPython as a program.
1449
1466
1450 Usage:\\
1467 Usage:\\
1451 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1468 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1452
1469
1453 Parameters after the filename are passed as command-line arguments to
1470 Parameters after the filename are passed as command-line arguments to
1454 the program (put in sys.argv). Then, control returns to IPython's
1471 the program (put in sys.argv). Then, control returns to IPython's
1455 prompt.
1472 prompt.
1456
1473
1457 This is similar to running at a system prompt:\\
1474 This is similar to running at a system prompt:\\
1458 $ python file args\\
1475 $ python file args\\
1459 but with the advantage of giving you IPython's tracebacks, and of
1476 but with the advantage of giving you IPython's tracebacks, and of
1460 loading all variables into your interactive namespace for further use
1477 loading all variables into your interactive namespace for further use
1461 (unless -p is used, see below).
1478 (unless -p is used, see below).
1462
1479
1463 The file is executed in a namespace initially consisting only of
1480 The file is executed in a namespace initially consisting only of
1464 __name__=='__main__' and sys.argv constructed as indicated. It thus
1481 __name__=='__main__' and sys.argv constructed as indicated. It thus
1465 sees its environment as if it were being run as a stand-alone program
1482 sees its environment as if it were being run as a stand-alone program
1466 (except for sharing global objects such as previously imported
1483 (except for sharing global objects such as previously imported
1467 modules). But after execution, the IPython interactive namespace gets
1484 modules). But after execution, the IPython interactive namespace gets
1468 updated with all variables defined in the program (except for __name__
1485 updated with all variables defined in the program (except for __name__
1469 and sys.argv). This allows for very convenient loading of code for
1486 and sys.argv). This allows for very convenient loading of code for
1470 interactive work, while giving each program a 'clean sheet' to run in.
1487 interactive work, while giving each program a 'clean sheet' to run in.
1471
1488
1472 Options:
1489 Options:
1473
1490
1474 -n: __name__ is NOT set to '__main__', but to the running file's name
1491 -n: __name__ is NOT set to '__main__', but to the running file's name
1475 without extension (as python does under import). This allows running
1492 without extension (as python does under import). This allows running
1476 scripts and reloading the definitions in them without calling code
1493 scripts and reloading the definitions in them without calling code
1477 protected by an ' if __name__ == "__main__" ' clause.
1494 protected by an ' if __name__ == "__main__" ' clause.
1478
1495
1479 -i: run the file in IPython's namespace instead of an empty one. This
1496 -i: run the file in IPython's namespace instead of an empty one. This
1480 is useful if you are experimenting with code written in a text editor
1497 is useful if you are experimenting with code written in a text editor
1481 which depends on variables defined interactively.
1498 which depends on variables defined interactively.
1482
1499
1483 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1500 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1484 being run. This is particularly useful if IPython is being used to
1501 being run. This is particularly useful if IPython is being used to
1485 run unittests, which always exit with a sys.exit() call. In such
1502 run unittests, which always exit with a sys.exit() call. In such
1486 cases you are interested in the output of the test results, not in
1503 cases you are interested in the output of the test results, not in
1487 seeing a traceback of the unittest module.
1504 seeing a traceback of the unittest module.
1488
1505
1489 -t: print timing information at the end of the run. IPython will give
1506 -t: print timing information at the end of the run. IPython will give
1490 you an estimated CPU time consumption for your script, which under
1507 you an estimated CPU time consumption for your script, which under
1491 Unix uses the resource module to avoid the wraparound problems of
1508 Unix uses the resource module to avoid the wraparound problems of
1492 time.clock(). Under Unix, an estimate of time spent on system tasks
1509 time.clock(). Under Unix, an estimate of time spent on system tasks
1493 is also given (for Windows platforms this is reported as 0.0).
1510 is also given (for Windows platforms this is reported as 0.0).
1494
1511
1495 If -t is given, an additional -N<N> option can be given, where <N>
1512 If -t is given, an additional -N<N> option can be given, where <N>
1496 must be an integer indicating how many times you want the script to
1513 must be an integer indicating how many times you want the script to
1497 run. The final timing report will include total and per run results.
1514 run. The final timing report will include total and per run results.
1498
1515
1499 For example (testing the script uniq_stable.py):
1516 For example (testing the script uniq_stable.py):
1500
1517
1501 In [1]: run -t uniq_stable
1518 In [1]: run -t uniq_stable
1502
1519
1503 IPython CPU timings (estimated):\\
1520 IPython CPU timings (estimated):\\
1504 User : 0.19597 s.\\
1521 User : 0.19597 s.\\
1505 System: 0.0 s.\\
1522 System: 0.0 s.\\
1506
1523
1507 In [2]: run -t -N5 uniq_stable
1524 In [2]: run -t -N5 uniq_stable
1508
1525
1509 IPython CPU timings (estimated):\\
1526 IPython CPU timings (estimated):\\
1510 Total runs performed: 5\\
1527 Total runs performed: 5\\
1511 Times : Total Per run\\
1528 Times : Total Per run\\
1512 User : 0.910862 s, 0.1821724 s.\\
1529 User : 0.910862 s, 0.1821724 s.\\
1513 System: 0.0 s, 0.0 s.
1530 System: 0.0 s, 0.0 s.
1514
1531
1515 -d: run your program under the control of pdb, the Python debugger.
1532 -d: run your program under the control of pdb, the Python debugger.
1516 This allows you to execute your program step by step, watch variables,
1533 This allows you to execute your program step by step, watch variables,
1517 etc. Internally, what IPython does is similar to calling:
1534 etc. Internally, what IPython does is similar to calling:
1518
1535
1519 pdb.run('execfile("YOURFILENAME")')
1536 pdb.run('execfile("YOURFILENAME")')
1520
1537
1521 with a breakpoint set on line 1 of your file. You can change the line
1538 with a breakpoint set on line 1 of your file. You can change the line
1522 number for this automatic breakpoint to be <N> by using the -bN option
1539 number for this automatic breakpoint to be <N> by using the -bN option
1523 (where N must be an integer). For example:
1540 (where N must be an integer). For example:
1524
1541
1525 %run -d -b40 myscript
1542 %run -d -b40 myscript
1526
1543
1527 will set the first breakpoint at line 40 in myscript.py. Note that
1544 will set the first breakpoint at line 40 in myscript.py. Note that
1528 the first breakpoint must be set on a line which actually does
1545 the first breakpoint must be set on a line which actually does
1529 something (not a comment or docstring) for it to stop execution.
1546 something (not a comment or docstring) for it to stop execution.
1530
1547
1531 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1548 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1532 first enter 'c' (without qoutes) to start execution up to the first
1549 first enter 'c' (without qoutes) to start execution up to the first
1533 breakpoint.
1550 breakpoint.
1534
1551
1535 Entering 'help' gives information about the use of the debugger. You
1552 Entering 'help' gives information about the use of the debugger. You
1536 can easily see pdb's full documentation with "import pdb;pdb.help()"
1553 can easily see pdb's full documentation with "import pdb;pdb.help()"
1537 at a prompt.
1554 at a prompt.
1538
1555
1539 -p: run program under the control of the Python profiler module (which
1556 -p: run program under the control of the Python profiler module (which
1540 prints a detailed report of execution times, function calls, etc).
1557 prints a detailed report of execution times, function calls, etc).
1541
1558
1542 You can pass other options after -p which affect the behavior of the
1559 You can pass other options after -p which affect the behavior of the
1543 profiler itself. See the docs for %prun for details.
1560 profiler itself. See the docs for %prun for details.
1544
1561
1545 In this mode, the program's variables do NOT propagate back to the
1562 In this mode, the program's variables do NOT propagate back to the
1546 IPython interactive namespace (because they remain in the namespace
1563 IPython interactive namespace (because they remain in the namespace
1547 where the profiler executes them).
1564 where the profiler executes them).
1548
1565
1549 Internally this triggers a call to %prun, see its documentation for
1566 Internally this triggers a call to %prun, see its documentation for
1550 details on the options available specifically for profiling.
1567 details on the options available specifically for profiling.
1551
1568
1552 There is one special usage for which the text above doesn't apply:
1569 There is one special usage for which the text above doesn't apply:
1553 if the filename ends with .ipy, the file is run as ipython script,
1570 if the filename ends with .ipy, the file is run as ipython script,
1554 just as if the commands were written on IPython prompt.
1571 just as if the commands were written on IPython prompt.
1555 """
1572 """
1556
1573
1557 # get arguments and set sys.argv for program to be run.
1574 # get arguments and set sys.argv for program to be run.
1558 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1575 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1559 mode='list',list_all=1)
1576 mode='list',list_all=1)
1560
1577
1561 try:
1578 try:
1562 filename = file_finder(arg_lst[0])
1579 filename = file_finder(arg_lst[0])
1563 except IndexError:
1580 except IndexError:
1564 warn('you must provide at least a filename.')
1581 warn('you must provide at least a filename.')
1565 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1582 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1566 return
1583 return
1567 except IOError,msg:
1584 except IOError,msg:
1568 error(msg)
1585 error(msg)
1569 return
1586 return
1570
1587
1571 if filename.lower().endswith('.ipy'):
1588 if filename.lower().endswith('.ipy'):
1572 self.shell.safe_execfile_ipy(filename)
1589 self.shell.safe_execfile_ipy(filename)
1573 return
1590 return
1574
1591
1575 # Control the response to exit() calls made by the script being run
1592 # Control the response to exit() calls made by the script being run
1576 exit_ignore = opts.has_key('e')
1593 exit_ignore = opts.has_key('e')
1577
1594
1578 # Make sure that the running script gets a proper sys.argv as if it
1595 # Make sure that the running script gets a proper sys.argv as if it
1579 # were run from a system shell.
1596 # were run from a system shell.
1580 save_argv = sys.argv # save it for later restoring
1597 save_argv = sys.argv # save it for later restoring
1581 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1598 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1582
1599
1583 if opts.has_key('i'):
1600 if opts.has_key('i'):
1584 # Run in user's interactive namespace
1601 # Run in user's interactive namespace
1585 prog_ns = self.shell.user_ns
1602 prog_ns = self.shell.user_ns
1586 __name__save = self.shell.user_ns['__name__']
1603 __name__save = self.shell.user_ns['__name__']
1587 prog_ns['__name__'] = '__main__'
1604 prog_ns['__name__'] = '__main__'
1588 main_mod = self.shell.new_main_mod(prog_ns)
1605 main_mod = self.shell.new_main_mod(prog_ns)
1589 else:
1606 else:
1590 # Run in a fresh, empty namespace
1607 # Run in a fresh, empty namespace
1591 if opts.has_key('n'):
1608 if opts.has_key('n'):
1592 name = os.path.splitext(os.path.basename(filename))[0]
1609 name = os.path.splitext(os.path.basename(filename))[0]
1593 else:
1610 else:
1594 name = '__main__'
1611 name = '__main__'
1595
1612
1596 main_mod = self.shell.new_main_mod()
1613 main_mod = self.shell.new_main_mod()
1597 prog_ns = main_mod.__dict__
1614 prog_ns = main_mod.__dict__
1598 prog_ns['__name__'] = name
1615 prog_ns['__name__'] = name
1599
1616
1600 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1617 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1601 # set the __file__ global in the script's namespace
1618 # set the __file__ global in the script's namespace
1602 prog_ns['__file__'] = filename
1619 prog_ns['__file__'] = filename
1603
1620
1604 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1621 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1605 # that, if we overwrite __main__, we replace it at the end
1622 # that, if we overwrite __main__, we replace it at the end
1606 main_mod_name = prog_ns['__name__']
1623 main_mod_name = prog_ns['__name__']
1607
1624
1608 if main_mod_name == '__main__':
1625 if main_mod_name == '__main__':
1609 restore_main = sys.modules['__main__']
1626 restore_main = sys.modules['__main__']
1610 else:
1627 else:
1611 restore_main = False
1628 restore_main = False
1612
1629
1613 # This needs to be undone at the end to prevent holding references to
1630 # This needs to be undone at the end to prevent holding references to
1614 # every single object ever created.
1631 # every single object ever created.
1615 sys.modules[main_mod_name] = main_mod
1632 sys.modules[main_mod_name] = main_mod
1616
1633
1617 try:
1634 try:
1618 stats = None
1635 stats = None
1619 with self.readline_no_record:
1636 with self.readline_no_record:
1620 if opts.has_key('p'):
1637 if opts.has_key('p'):
1621 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1638 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1622 else:
1639 else:
1623 if opts.has_key('d'):
1640 if opts.has_key('d'):
1624 deb = debugger.Pdb(self.shell.colors)
1641 deb = debugger.Pdb(self.shell.colors)
1625 # reset Breakpoint state, which is moronically kept
1642 # reset Breakpoint state, which is moronically kept
1626 # in a class
1643 # in a class
1627 bdb.Breakpoint.next = 1
1644 bdb.Breakpoint.next = 1
1628 bdb.Breakpoint.bplist = {}
1645 bdb.Breakpoint.bplist = {}
1629 bdb.Breakpoint.bpbynumber = [None]
1646 bdb.Breakpoint.bpbynumber = [None]
1630 # Set an initial breakpoint to stop execution
1647 # Set an initial breakpoint to stop execution
1631 maxtries = 10
1648 maxtries = 10
1632 bp = int(opts.get('b',[1])[0])
1649 bp = int(opts.get('b',[1])[0])
1633 checkline = deb.checkline(filename,bp)
1650 checkline = deb.checkline(filename,bp)
1634 if not checkline:
1651 if not checkline:
1635 for bp in range(bp+1,bp+maxtries+1):
1652 for bp in range(bp+1,bp+maxtries+1):
1636 if deb.checkline(filename,bp):
1653 if deb.checkline(filename,bp):
1637 break
1654 break
1638 else:
1655 else:
1639 msg = ("\nI failed to find a valid line to set "
1656 msg = ("\nI failed to find a valid line to set "
1640 "a breakpoint\n"
1657 "a breakpoint\n"
1641 "after trying up to line: %s.\n"
1658 "after trying up to line: %s.\n"
1642 "Please set a valid breakpoint manually "
1659 "Please set a valid breakpoint manually "
1643 "with the -b option." % bp)
1660 "with the -b option." % bp)
1644 error(msg)
1661 error(msg)
1645 return
1662 return
1646 # if we find a good linenumber, set the breakpoint
1663 # if we find a good linenumber, set the breakpoint
1647 deb.do_break('%s:%s' % (filename,bp))
1664 deb.do_break('%s:%s' % (filename,bp))
1648 # Start file run
1665 # Start file run
1649 print "NOTE: Enter 'c' at the",
1666 print "NOTE: Enter 'c' at the",
1650 print "%s prompt to start your script." % deb.prompt
1667 print "%s prompt to start your script." % deb.prompt
1651 try:
1668 try:
1652 deb.run('execfile("%s")' % filename,prog_ns)
1669 deb.run('execfile("%s")' % filename,prog_ns)
1653
1670
1654 except:
1671 except:
1655 etype, value, tb = sys.exc_info()
1672 etype, value, tb = sys.exc_info()
1656 # Skip three frames in the traceback: the %run one,
1673 # Skip three frames in the traceback: the %run one,
1657 # one inside bdb.py, and the command-line typed by the
1674 # one inside bdb.py, and the command-line typed by the
1658 # user (run by exec in pdb itself).
1675 # user (run by exec in pdb itself).
1659 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1676 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1660 else:
1677 else:
1661 if runner is None:
1678 if runner is None:
1662 runner = self.shell.safe_execfile
1679 runner = self.shell.safe_execfile
1663 if opts.has_key('t'):
1680 if opts.has_key('t'):
1664 # timed execution
1681 # timed execution
1665 try:
1682 try:
1666 nruns = int(opts['N'][0])
1683 nruns = int(opts['N'][0])
1667 if nruns < 1:
1684 if nruns < 1:
1668 error('Number of runs must be >=1')
1685 error('Number of runs must be >=1')
1669 return
1686 return
1670 except (KeyError):
1687 except (KeyError):
1671 nruns = 1
1688 nruns = 1
1672 if nruns == 1:
1689 if nruns == 1:
1673 t0 = clock2()
1690 t0 = clock2()
1674 runner(filename,prog_ns,prog_ns,
1691 runner(filename,prog_ns,prog_ns,
1675 exit_ignore=exit_ignore)
1692 exit_ignore=exit_ignore)
1676 t1 = clock2()
1693 t1 = clock2()
1677 t_usr = t1[0]-t0[0]
1694 t_usr = t1[0]-t0[0]
1678 t_sys = t1[1]-t0[1]
1695 t_sys = t1[1]-t0[1]
1679 print "\nIPython CPU timings (estimated):"
1696 print "\nIPython CPU timings (estimated):"
1680 print " User : %10s s." % t_usr
1697 print " User : %10s s." % t_usr
1681 print " System: %10s s." % t_sys
1698 print " System: %10s s." % t_sys
1682 else:
1699 else:
1683 runs = range(nruns)
1700 runs = range(nruns)
1684 t0 = clock2()
1701 t0 = clock2()
1685 for nr in runs:
1702 for nr in runs:
1686 runner(filename,prog_ns,prog_ns,
1703 runner(filename,prog_ns,prog_ns,
1687 exit_ignore=exit_ignore)
1704 exit_ignore=exit_ignore)
1688 t1 = clock2()
1705 t1 = clock2()
1689 t_usr = t1[0]-t0[0]
1706 t_usr = t1[0]-t0[0]
1690 t_sys = t1[1]-t0[1]
1707 t_sys = t1[1]-t0[1]
1691 print "\nIPython CPU timings (estimated):"
1708 print "\nIPython CPU timings (estimated):"
1692 print "Total runs performed:",nruns
1709 print "Total runs performed:",nruns
1693 print " Times : %10s %10s" % ('Total','Per run')
1710 print " Times : %10s %10s" % ('Total','Per run')
1694 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1711 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1695 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1712 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1696
1713
1697 else:
1714 else:
1698 # regular execution
1715 # regular execution
1699 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1716 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1700
1717
1701 if opts.has_key('i'):
1718 if opts.has_key('i'):
1702 self.shell.user_ns['__name__'] = __name__save
1719 self.shell.user_ns['__name__'] = __name__save
1703 else:
1720 else:
1704 # The shell MUST hold a reference to prog_ns so after %run
1721 # The shell MUST hold a reference to prog_ns so after %run
1705 # exits, the python deletion mechanism doesn't zero it out
1722 # exits, the python deletion mechanism doesn't zero it out
1706 # (leaving dangling references).
1723 # (leaving dangling references).
1707 self.shell.cache_main_mod(prog_ns,filename)
1724 self.shell.cache_main_mod(prog_ns,filename)
1708 # update IPython interactive namespace
1725 # update IPython interactive namespace
1709
1726
1710 # Some forms of read errors on the file may mean the
1727 # Some forms of read errors on the file may mean the
1711 # __name__ key was never set; using pop we don't have to
1728 # __name__ key was never set; using pop we don't have to
1712 # worry about a possible KeyError.
1729 # worry about a possible KeyError.
1713 prog_ns.pop('__name__', None)
1730 prog_ns.pop('__name__', None)
1714
1731
1715 self.shell.user_ns.update(prog_ns)
1732 self.shell.user_ns.update(prog_ns)
1716 finally:
1733 finally:
1717 # It's a bit of a mystery why, but __builtins__ can change from
1734 # It's a bit of a mystery why, but __builtins__ can change from
1718 # being a module to becoming a dict missing some key data after
1735 # being a module to becoming a dict missing some key data after
1719 # %run. As best I can see, this is NOT something IPython is doing
1736 # %run. As best I can see, this is NOT something IPython is doing
1720 # at all, and similar problems have been reported before:
1737 # at all, and similar problems have been reported before:
1721 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1738 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1722 # Since this seems to be done by the interpreter itself, the best
1739 # Since this seems to be done by the interpreter itself, the best
1723 # we can do is to at least restore __builtins__ for the user on
1740 # we can do is to at least restore __builtins__ for the user on
1724 # exit.
1741 # exit.
1725 self.shell.user_ns['__builtins__'] = __builtin__
1742 self.shell.user_ns['__builtins__'] = __builtin__
1726
1743
1727 # Ensure key global structures are restored
1744 # Ensure key global structures are restored
1728 sys.argv = save_argv
1745 sys.argv = save_argv
1729 if restore_main:
1746 if restore_main:
1730 sys.modules['__main__'] = restore_main
1747 sys.modules['__main__'] = restore_main
1731 else:
1748 else:
1732 # Remove from sys.modules the reference to main_mod we'd
1749 # Remove from sys.modules the reference to main_mod we'd
1733 # added. Otherwise it will trap references to objects
1750 # added. Otherwise it will trap references to objects
1734 # contained therein.
1751 # contained therein.
1735 del sys.modules[main_mod_name]
1752 del sys.modules[main_mod_name]
1736
1753
1737 return stats
1754 return stats
1738
1755
1739 @skip_doctest
1756 @skip_doctest
1740 def magic_timeit(self, parameter_s =''):
1757 def magic_timeit(self, parameter_s =''):
1741 """Time execution of a Python statement or expression
1758 """Time execution of a Python statement or expression
1742
1759
1743 Usage:\\
1760 Usage:\\
1744 %timeit [-n<N> -r<R> [-t|-c]] statement
1761 %timeit [-n<N> -r<R> [-t|-c]] statement
1745
1762
1746 Time execution of a Python statement or expression using the timeit
1763 Time execution of a Python statement or expression using the timeit
1747 module.
1764 module.
1748
1765
1749 Options:
1766 Options:
1750 -n<N>: execute the given statement <N> times in a loop. If this value
1767 -n<N>: execute the given statement <N> times in a loop. If this value
1751 is not given, a fitting value is chosen.
1768 is not given, a fitting value is chosen.
1752
1769
1753 -r<R>: repeat the loop iteration <R> times and take the best result.
1770 -r<R>: repeat the loop iteration <R> times and take the best result.
1754 Default: 3
1771 Default: 3
1755
1772
1756 -t: use time.time to measure the time, which is the default on Unix.
1773 -t: use time.time to measure the time, which is the default on Unix.
1757 This function measures wall time.
1774 This function measures wall time.
1758
1775
1759 -c: use time.clock to measure the time, which is the default on
1776 -c: use time.clock to measure the time, which is the default on
1760 Windows and measures wall time. On Unix, resource.getrusage is used
1777 Windows and measures wall time. On Unix, resource.getrusage is used
1761 instead and returns the CPU user time.
1778 instead and returns the CPU user time.
1762
1779
1763 -p<P>: use a precision of <P> digits to display the timing result.
1780 -p<P>: use a precision of <P> digits to display the timing result.
1764 Default: 3
1781 Default: 3
1765
1782
1766
1783
1767 Examples:
1784 Examples:
1768
1785
1769 In [1]: %timeit pass
1786 In [1]: %timeit pass
1770 10000000 loops, best of 3: 53.3 ns per loop
1787 10000000 loops, best of 3: 53.3 ns per loop
1771
1788
1772 In [2]: u = None
1789 In [2]: u = None
1773
1790
1774 In [3]: %timeit u is None
1791 In [3]: %timeit u is None
1775 10000000 loops, best of 3: 184 ns per loop
1792 10000000 loops, best of 3: 184 ns per loop
1776
1793
1777 In [4]: %timeit -r 4 u == None
1794 In [4]: %timeit -r 4 u == None
1778 1000000 loops, best of 4: 242 ns per loop
1795 1000000 loops, best of 4: 242 ns per loop
1779
1796
1780 In [5]: import time
1797 In [5]: import time
1781
1798
1782 In [6]: %timeit -n1 time.sleep(2)
1799 In [6]: %timeit -n1 time.sleep(2)
1783 1 loops, best of 3: 2 s per loop
1800 1 loops, best of 3: 2 s per loop
1784
1801
1785
1802
1786 The times reported by %timeit will be slightly higher than those
1803 The times reported by %timeit will be slightly higher than those
1787 reported by the timeit.py script when variables are accessed. This is
1804 reported by the timeit.py script when variables are accessed. This is
1788 due to the fact that %timeit executes the statement in the namespace
1805 due to the fact that %timeit executes the statement in the namespace
1789 of the shell, compared with timeit.py, which uses a single setup
1806 of the shell, compared with timeit.py, which uses a single setup
1790 statement to import function or create variables. Generally, the bias
1807 statement to import function or create variables. Generally, the bias
1791 does not matter as long as results from timeit.py are not mixed with
1808 does not matter as long as results from timeit.py are not mixed with
1792 those from %timeit."""
1809 those from %timeit."""
1793
1810
1794 import timeit
1811 import timeit
1795 import math
1812 import math
1796
1813
1797 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1814 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1798 # certain terminals. Until we figure out a robust way of
1815 # certain terminals. Until we figure out a robust way of
1799 # auto-detecting if the terminal can deal with it, use plain 'us' for
1816 # auto-detecting if the terminal can deal with it, use plain 'us' for
1800 # microseconds. I am really NOT happy about disabling the proper
1817 # microseconds. I am really NOT happy about disabling the proper
1801 # 'micro' prefix, but crashing is worse... If anyone knows what the
1818 # 'micro' prefix, but crashing is worse... If anyone knows what the
1802 # right solution for this is, I'm all ears...
1819 # right solution for this is, I'm all ears...
1803 #
1820 #
1804 # Note: using
1821 # Note: using
1805 #
1822 #
1806 # s = u'\xb5'
1823 # s = u'\xb5'
1807 # s.encode(sys.getdefaultencoding())
1824 # s.encode(sys.getdefaultencoding())
1808 #
1825 #
1809 # is not sufficient, as I've seen terminals where that fails but
1826 # is not sufficient, as I've seen terminals where that fails but
1810 # print s
1827 # print s
1811 #
1828 #
1812 # succeeds
1829 # succeeds
1813 #
1830 #
1814 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1831 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1815
1832
1816 #units = [u"s", u"ms",u'\xb5',"ns"]
1833 #units = [u"s", u"ms",u'\xb5',"ns"]
1817 units = [u"s", u"ms",u'us',"ns"]
1834 units = [u"s", u"ms",u'us',"ns"]
1818
1835
1819 scaling = [1, 1e3, 1e6, 1e9]
1836 scaling = [1, 1e3, 1e6, 1e9]
1820
1837
1821 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1838 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1822 posix=False)
1839 posix=False)
1823 if stmt == "":
1840 if stmt == "":
1824 return
1841 return
1825 timefunc = timeit.default_timer
1842 timefunc = timeit.default_timer
1826 number = int(getattr(opts, "n", 0))
1843 number = int(getattr(opts, "n", 0))
1827 repeat = int(getattr(opts, "r", timeit.default_repeat))
1844 repeat = int(getattr(opts, "r", timeit.default_repeat))
1828 precision = int(getattr(opts, "p", 3))
1845 precision = int(getattr(opts, "p", 3))
1829 if hasattr(opts, "t"):
1846 if hasattr(opts, "t"):
1830 timefunc = time.time
1847 timefunc = time.time
1831 if hasattr(opts, "c"):
1848 if hasattr(opts, "c"):
1832 timefunc = clock
1849 timefunc = clock
1833
1850
1834 timer = timeit.Timer(timer=timefunc)
1851 timer = timeit.Timer(timer=timefunc)
1835 # this code has tight coupling to the inner workings of timeit.Timer,
1852 # this code has tight coupling to the inner workings of timeit.Timer,
1836 # but is there a better way to achieve that the code stmt has access
1853 # but is there a better way to achieve that the code stmt has access
1837 # to the shell namespace?
1854 # to the shell namespace?
1838
1855
1839 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1856 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1840 'setup': "pass"}
1857 'setup': "pass"}
1841 # Track compilation time so it can be reported if too long
1858 # Track compilation time so it can be reported if too long
1842 # Minimum time above which compilation time will be reported
1859 # Minimum time above which compilation time will be reported
1843 tc_min = 0.1
1860 tc_min = 0.1
1844
1861
1845 t0 = clock()
1862 t0 = clock()
1846 code = compile(src, "<magic-timeit>", "exec")
1863 code = compile(src, "<magic-timeit>", "exec")
1847 tc = clock()-t0
1864 tc = clock()-t0
1848
1865
1849 ns = {}
1866 ns = {}
1850 exec code in self.shell.user_ns, ns
1867 exec code in self.shell.user_ns, ns
1851 timer.inner = ns["inner"]
1868 timer.inner = ns["inner"]
1852
1869
1853 if number == 0:
1870 if number == 0:
1854 # determine number so that 0.2 <= total time < 2.0
1871 # determine number so that 0.2 <= total time < 2.0
1855 number = 1
1872 number = 1
1856 for i in range(1, 10):
1873 for i in range(1, 10):
1857 if timer.timeit(number) >= 0.2:
1874 if timer.timeit(number) >= 0.2:
1858 break
1875 break
1859 number *= 10
1876 number *= 10
1860
1877
1861 best = min(timer.repeat(repeat, number)) / number
1878 best = min(timer.repeat(repeat, number)) / number
1862
1879
1863 if best > 0.0 and best < 1000.0:
1880 if best > 0.0 and best < 1000.0:
1864 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1881 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1865 elif best >= 1000.0:
1882 elif best >= 1000.0:
1866 order = 0
1883 order = 0
1867 else:
1884 else:
1868 order = 3
1885 order = 3
1869 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1886 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1870 precision,
1887 precision,
1871 best * scaling[order],
1888 best * scaling[order],
1872 units[order])
1889 units[order])
1873 if tc > tc_min:
1890 if tc > tc_min:
1874 print "Compiler time: %.2f s" % tc
1891 print "Compiler time: %.2f s" % tc
1875
1892
1876 @skip_doctest
1893 @skip_doctest
1877 @needs_local_scope
1894 @needs_local_scope
1878 def magic_time(self,parameter_s = ''):
1895 def magic_time(self,parameter_s = ''):
1879 """Time execution of a Python statement or expression.
1896 """Time execution of a Python statement or expression.
1880
1897
1881 The CPU and wall clock times are printed, and the value of the
1898 The CPU and wall clock times are printed, and the value of the
1882 expression (if any) is returned. Note that under Win32, system time
1899 expression (if any) is returned. Note that under Win32, system time
1883 is always reported as 0, since it can not be measured.
1900 is always reported as 0, since it can not be measured.
1884
1901
1885 This function provides very basic timing functionality. In Python
1902 This function provides very basic timing functionality. In Python
1886 2.3, the timeit module offers more control and sophistication, so this
1903 2.3, the timeit module offers more control and sophistication, so this
1887 could be rewritten to use it (patches welcome).
1904 could be rewritten to use it (patches welcome).
1888
1905
1889 Some examples:
1906 Some examples:
1890
1907
1891 In [1]: time 2**128
1908 In [1]: time 2**128
1892 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1893 Wall time: 0.00
1910 Wall time: 0.00
1894 Out[1]: 340282366920938463463374607431768211456L
1911 Out[1]: 340282366920938463463374607431768211456L
1895
1912
1896 In [2]: n = 1000000
1913 In [2]: n = 1000000
1897
1914
1898 In [3]: time sum(range(n))
1915 In [3]: time sum(range(n))
1899 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1916 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1900 Wall time: 1.37
1917 Wall time: 1.37
1901 Out[3]: 499999500000L
1918 Out[3]: 499999500000L
1902
1919
1903 In [4]: time print 'hello world'
1920 In [4]: time print 'hello world'
1904 hello world
1921 hello world
1905 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1906 Wall time: 0.00
1923 Wall time: 0.00
1907
1924
1908 Note that the time needed by Python to compile the given expression
1925 Note that the time needed by Python to compile the given expression
1909 will be reported if it is more than 0.1s. In this example, the
1926 will be reported if it is more than 0.1s. In this example, the
1910 actual exponentiation is done by Python at compilation time, so while
1927 actual exponentiation is done by Python at compilation time, so while
1911 the expression can take a noticeable amount of time to compute, that
1928 the expression can take a noticeable amount of time to compute, that
1912 time is purely due to the compilation:
1929 time is purely due to the compilation:
1913
1930
1914 In [5]: time 3**9999;
1931 In [5]: time 3**9999;
1915 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1932 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1916 Wall time: 0.00 s
1933 Wall time: 0.00 s
1917
1934
1918 In [6]: time 3**999999;
1935 In [6]: time 3**999999;
1919 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1920 Wall time: 0.00 s
1937 Wall time: 0.00 s
1921 Compiler : 0.78 s
1938 Compiler : 0.78 s
1922 """
1939 """
1923
1940
1924 # fail immediately if the given expression can't be compiled
1941 # fail immediately if the given expression can't be compiled
1925
1942
1926 expr = self.shell.prefilter(parameter_s,False)
1943 expr = self.shell.prefilter(parameter_s,False)
1927
1944
1928 # Minimum time above which compilation time will be reported
1945 # Minimum time above which compilation time will be reported
1929 tc_min = 0.1
1946 tc_min = 0.1
1930
1947
1931 try:
1948 try:
1932 mode = 'eval'
1949 mode = 'eval'
1933 t0 = clock()
1950 t0 = clock()
1934 code = compile(expr,'<timed eval>',mode)
1951 code = compile(expr,'<timed eval>',mode)
1935 tc = clock()-t0
1952 tc = clock()-t0
1936 except SyntaxError:
1953 except SyntaxError:
1937 mode = 'exec'
1954 mode = 'exec'
1938 t0 = clock()
1955 t0 = clock()
1939 code = compile(expr,'<timed exec>',mode)
1956 code = compile(expr,'<timed exec>',mode)
1940 tc = clock()-t0
1957 tc = clock()-t0
1941 # skew measurement as little as possible
1958 # skew measurement as little as possible
1942 glob = self.shell.user_ns
1959 glob = self.shell.user_ns
1943 locs = self._magic_locals
1960 locs = self._magic_locals
1944 clk = clock2
1961 clk = clock2
1945 wtime = time.time
1962 wtime = time.time
1946 # time execution
1963 # time execution
1947 wall_st = wtime()
1964 wall_st = wtime()
1948 if mode=='eval':
1965 if mode=='eval':
1949 st = clk()
1966 st = clk()
1950 out = eval(code, glob, locs)
1967 out = eval(code, glob, locs)
1951 end = clk()
1968 end = clk()
1952 else:
1969 else:
1953 st = clk()
1970 st = clk()
1954 exec code in glob, locs
1971 exec code in glob, locs
1955 end = clk()
1972 end = clk()
1956 out = None
1973 out = None
1957 wall_end = wtime()
1974 wall_end = wtime()
1958 # Compute actual times and report
1975 # Compute actual times and report
1959 wall_time = wall_end-wall_st
1976 wall_time = wall_end-wall_st
1960 cpu_user = end[0]-st[0]
1977 cpu_user = end[0]-st[0]
1961 cpu_sys = end[1]-st[1]
1978 cpu_sys = end[1]-st[1]
1962 cpu_tot = cpu_user+cpu_sys
1979 cpu_tot = cpu_user+cpu_sys
1963 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1980 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1964 (cpu_user,cpu_sys,cpu_tot)
1981 (cpu_user,cpu_sys,cpu_tot)
1965 print "Wall time: %.2f s" % wall_time
1982 print "Wall time: %.2f s" % wall_time
1966 if tc > tc_min:
1983 if tc > tc_min:
1967 print "Compiler : %.2f s" % tc
1984 print "Compiler : %.2f s" % tc
1968 return out
1985 return out
1969
1986
1970 @skip_doctest
1987 @skip_doctest
1971 def magic_macro(self,parameter_s = ''):
1988 def magic_macro(self,parameter_s = ''):
1972 """Define a macro for future re-execution. It accepts ranges of history,
1989 """Define a macro for future re-execution. It accepts ranges of history,
1973 filenames or string objects.
1990 filenames or string objects.
1974
1991
1975 Usage:\\
1992 Usage:\\
1976 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1993 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1977
1994
1978 Options:
1995 Options:
1979
1996
1980 -r: use 'raw' input. By default, the 'processed' history is used,
1997 -r: use 'raw' input. By default, the 'processed' history is used,
1981 so that magics are loaded in their transformed version to valid
1998 so that magics are loaded in their transformed version to valid
1982 Python. If this option is given, the raw input as typed as the
1999 Python. If this option is given, the raw input as typed as the
1983 command line is used instead.
2000 command line is used instead.
1984
2001
1985 This will define a global variable called `name` which is a string
2002 This will define a global variable called `name` which is a string
1986 made of joining the slices and lines you specify (n1,n2,... numbers
2003 made of joining the slices and lines you specify (n1,n2,... numbers
1987 above) from your input history into a single string. This variable
2004 above) from your input history into a single string. This variable
1988 acts like an automatic function which re-executes those lines as if
2005 acts like an automatic function which re-executes those lines as if
1989 you had typed them. You just type 'name' at the prompt and the code
2006 you had typed them. You just type 'name' at the prompt and the code
1990 executes.
2007 executes.
1991
2008
1992 The syntax for indicating input ranges is described in %history.
2009 The syntax for indicating input ranges is described in %history.
1993
2010
1994 Note: as a 'hidden' feature, you can also use traditional python slice
2011 Note: as a 'hidden' feature, you can also use traditional python slice
1995 notation, where N:M means numbers N through M-1.
2012 notation, where N:M means numbers N through M-1.
1996
2013
1997 For example, if your history contains (%hist prints it):
2014 For example, if your history contains (%hist prints it):
1998
2015
1999 44: x=1
2016 44: x=1
2000 45: y=3
2017 45: y=3
2001 46: z=x+y
2018 46: z=x+y
2002 47: print x
2019 47: print x
2003 48: a=5
2020 48: a=5
2004 49: print 'x',x,'y',y
2021 49: print 'x',x,'y',y
2005
2022
2006 you can create a macro with lines 44 through 47 (included) and line 49
2023 you can create a macro with lines 44 through 47 (included) and line 49
2007 called my_macro with:
2024 called my_macro with:
2008
2025
2009 In [55]: %macro my_macro 44-47 49
2026 In [55]: %macro my_macro 44-47 49
2010
2027
2011 Now, typing `my_macro` (without quotes) will re-execute all this code
2028 Now, typing `my_macro` (without quotes) will re-execute all this code
2012 in one pass.
2029 in one pass.
2013
2030
2014 You don't need to give the line-numbers in order, and any given line
2031 You don't need to give the line-numbers in order, and any given line
2015 number can appear multiple times. You can assemble macros with any
2032 number can appear multiple times. You can assemble macros with any
2016 lines from your input history in any order.
2033 lines from your input history in any order.
2017
2034
2018 The macro is a simple object which holds its value in an attribute,
2035 The macro is a simple object which holds its value in an attribute,
2019 but IPython's display system checks for macros and executes them as
2036 but IPython's display system checks for macros and executes them as
2020 code instead of printing them when you type their name.
2037 code instead of printing them when you type their name.
2021
2038
2022 You can view a macro's contents by explicitly printing it with:
2039 You can view a macro's contents by explicitly printing it with:
2023
2040
2024 'print macro_name'.
2041 'print macro_name'.
2025
2042
2026 """
2043 """
2027 opts,args = self.parse_options(parameter_s,'r',mode='list')
2044 opts,args = self.parse_options(parameter_s,'r',mode='list')
2028 if not args: # List existing macros
2045 if not args: # List existing macros
2029 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2046 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2030 isinstance(v, Macro))
2047 isinstance(v, Macro))
2031 if len(args) == 1:
2048 if len(args) == 1:
2032 raise UsageError(
2049 raise UsageError(
2033 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2050 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2034 name, codefrom = args[0], " ".join(args[1:])
2051 name, codefrom = args[0], " ".join(args[1:])
2035
2052
2036 #print 'rng',ranges # dbg
2053 #print 'rng',ranges # dbg
2037 try:
2054 try:
2038 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2055 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2039 except (ValueError, TypeError) as e:
2056 except (ValueError, TypeError) as e:
2040 print e.args[0]
2057 print e.args[0]
2041 return
2058 return
2042 macro = Macro(lines)
2059 macro = Macro(lines)
2043 self.shell.define_macro(name, macro)
2060 self.shell.define_macro(name, macro)
2044 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2061 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2045 print '=== Macro contents: ==='
2062 print '=== Macro contents: ==='
2046 print macro,
2063 print macro,
2047
2064
2048 def magic_save(self,parameter_s = ''):
2065 def magic_save(self,parameter_s = ''):
2049 """Save a set of lines or a macro to a given filename.
2066 """Save a set of lines or a macro to a given filename.
2050
2067
2051 Usage:\\
2068 Usage:\\
2052 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2069 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2053
2070
2054 Options:
2071 Options:
2055
2072
2056 -r: use 'raw' input. By default, the 'processed' history is used,
2073 -r: use 'raw' input. By default, the 'processed' history is used,
2057 so that magics are loaded in their transformed version to valid
2074 so that magics are loaded in their transformed version to valid
2058 Python. If this option is given, the raw input as typed as the
2075 Python. If this option is given, the raw input as typed as the
2059 command line is used instead.
2076 command line is used instead.
2060
2077
2061 This function uses the same syntax as %history for input ranges,
2078 This function uses the same syntax as %history for input ranges,
2062 then saves the lines to the filename you specify.
2079 then saves the lines to the filename you specify.
2063
2080
2064 It adds a '.py' extension to the file if you don't do so yourself, and
2081 It adds a '.py' extension to the file if you don't do so yourself, and
2065 it asks for confirmation before overwriting existing files."""
2082 it asks for confirmation before overwriting existing files."""
2066
2083
2067 opts,args = self.parse_options(parameter_s,'r',mode='list')
2084 opts,args = self.parse_options(parameter_s,'r',mode='list')
2068 fname, codefrom = args[0], " ".join(args[1:])
2085 fname, codefrom = args[0], " ".join(args[1:])
2069 if not fname.endswith('.py'):
2086 if not fname.endswith('.py'):
2070 fname += '.py'
2087 fname += '.py'
2071 if os.path.isfile(fname):
2088 if os.path.isfile(fname):
2072 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2089 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2073 if ans.lower() not in ['y','yes']:
2090 if ans.lower() not in ['y','yes']:
2074 print 'Operation cancelled.'
2091 print 'Operation cancelled.'
2075 return
2092 return
2076 try:
2093 try:
2077 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2094 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2078 except (TypeError, ValueError) as e:
2095 except (TypeError, ValueError) as e:
2079 print e.args[0]
2096 print e.args[0]
2080 return
2097 return
2081 if isinstance(cmds, unicode):
2098 if isinstance(cmds, unicode):
2082 cmds = cmds.encode("utf-8")
2099 cmds = cmds.encode("utf-8")
2083 with open(fname,'w') as f:
2100 with open(fname,'w') as f:
2084 f.write("# coding: utf-8\n")
2101 f.write("# coding: utf-8\n")
2085 f.write(cmds)
2102 f.write(cmds)
2086 print 'The following commands were written to file `%s`:' % fname
2103 print 'The following commands were written to file `%s`:' % fname
2087 print cmds
2104 print cmds
2088
2105
2089 def magic_pastebin(self, parameter_s = ''):
2106 def magic_pastebin(self, parameter_s = ''):
2090 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2107 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2091 try:
2108 try:
2092 code = self.shell.find_user_code(parameter_s)
2109 code = self.shell.find_user_code(parameter_s)
2093 except (ValueError, TypeError) as e:
2110 except (ValueError, TypeError) as e:
2094 print e.args[0]
2111 print e.args[0]
2095 return
2112 return
2096 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2113 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2097 id = pbserver.pastes.newPaste("python", code)
2114 id = pbserver.pastes.newPaste("python", code)
2098 return "http://paste.pocoo.org/show/" + id
2115 return "http://paste.pocoo.org/show/" + id
2099
2116
2100 def magic_loadpy(self, arg_s):
2117 def magic_loadpy(self, arg_s):
2101 """Load a .py python script into the GUI console.
2118 """Load a .py python script into the GUI console.
2102
2119
2103 This magic command can either take a local filename or a url::
2120 This magic command can either take a local filename or a url::
2104
2121
2105 %loadpy myscript.py
2122 %loadpy myscript.py
2106 %loadpy http://www.example.com/myscript.py
2123 %loadpy http://www.example.com/myscript.py
2107 """
2124 """
2108 if not arg_s.endswith('.py'):
2125 if not arg_s.endswith('.py'):
2109 raise ValueError('%%load only works with .py files: %s' % arg_s)
2126 raise ValueError('%%load only works with .py files: %s' % arg_s)
2110 if arg_s.startswith('http'):
2127 if arg_s.startswith('http'):
2111 import urllib2
2128 import urllib2
2112 response = urllib2.urlopen(arg_s)
2129 response = urllib2.urlopen(arg_s)
2113 content = response.read()
2130 content = response.read()
2114 else:
2131 else:
2115 content = open(arg_s).read()
2132 content = open(arg_s).read()
2116 self.set_next_input(content)
2133 self.set_next_input(content)
2117
2134
2118 def _find_edit_target(self, args, opts, last_call):
2135 def _find_edit_target(self, args, opts, last_call):
2119 """Utility method used by magic_edit to find what to edit."""
2136 """Utility method used by magic_edit to find what to edit."""
2120
2137
2121 def make_filename(arg):
2138 def make_filename(arg):
2122 "Make a filename from the given args"
2139 "Make a filename from the given args"
2123 try:
2140 try:
2124 filename = get_py_filename(arg)
2141 filename = get_py_filename(arg)
2125 except IOError:
2142 except IOError:
2126 # If it ends with .py but doesn't already exist, assume we want
2143 # If it ends with .py but doesn't already exist, assume we want
2127 # a new file.
2144 # a new file.
2128 if args.endswith('.py'):
2145 if args.endswith('.py'):
2129 filename = arg
2146 filename = arg
2130 else:
2147 else:
2131 filename = None
2148 filename = None
2132 return filename
2149 return filename
2133
2150
2134 # Set a few locals from the options for convenience:
2151 # Set a few locals from the options for convenience:
2135 opts_prev = 'p' in opts
2152 opts_prev = 'p' in opts
2136 opts_raw = 'r' in opts
2153 opts_raw = 'r' in opts
2137
2154
2138 # custom exceptions
2155 # custom exceptions
2139 class DataIsObject(Exception): pass
2156 class DataIsObject(Exception): pass
2140
2157
2141 # Default line number value
2158 # Default line number value
2142 lineno = opts.get('n',None)
2159 lineno = opts.get('n',None)
2143
2160
2144 if opts_prev:
2161 if opts_prev:
2145 args = '_%s' % last_call[0]
2162 args = '_%s' % last_call[0]
2146 if not self.shell.user_ns.has_key(args):
2163 if not self.shell.user_ns.has_key(args):
2147 args = last_call[1]
2164 args = last_call[1]
2148
2165
2149 # use last_call to remember the state of the previous call, but don't
2166 # use last_call to remember the state of the previous call, but don't
2150 # let it be clobbered by successive '-p' calls.
2167 # let it be clobbered by successive '-p' calls.
2151 try:
2168 try:
2152 last_call[0] = self.shell.displayhook.prompt_count
2169 last_call[0] = self.shell.displayhook.prompt_count
2153 if not opts_prev:
2170 if not opts_prev:
2154 last_call[1] = parameter_s
2171 last_call[1] = parameter_s
2155 except:
2172 except:
2156 pass
2173 pass
2157
2174
2158 # by default this is done with temp files, except when the given
2175 # by default this is done with temp files, except when the given
2159 # arg is a filename
2176 # arg is a filename
2160 use_temp = True
2177 use_temp = True
2161
2178
2162 data = ''
2179 data = ''
2163
2180
2164 # First, see if the arguments should be a filename.
2181 # First, see if the arguments should be a filename.
2165 filename = make_filename(args)
2182 filename = make_filename(args)
2166 if filename:
2183 if filename:
2167 use_temp = False
2184 use_temp = False
2168 elif args:
2185 elif args:
2169 # Mode where user specifies ranges of lines, like in %macro.
2186 # Mode where user specifies ranges of lines, like in %macro.
2170 data = self.extract_input_lines(args, opts_raw)
2187 data = self.extract_input_lines(args, opts_raw)
2171 if not data:
2188 if not data:
2172 try:
2189 try:
2173 # Load the parameter given as a variable. If not a string,
2190 # Load the parameter given as a variable. If not a string,
2174 # process it as an object instead (below)
2191 # process it as an object instead (below)
2175
2192
2176 #print '*** args',args,'type',type(args) # dbg
2193 #print '*** args',args,'type',type(args) # dbg
2177 data = eval(args, self.shell.user_ns)
2194 data = eval(args, self.shell.user_ns)
2178 if not isinstance(data, basestring):
2195 if not isinstance(data, basestring):
2179 raise DataIsObject
2196 raise DataIsObject
2180
2197
2181 except (NameError,SyntaxError):
2198 except (NameError,SyntaxError):
2182 # given argument is not a variable, try as a filename
2199 # given argument is not a variable, try as a filename
2183 filename = make_filename(args)
2200 filename = make_filename(args)
2184 if filename is None:
2201 if filename is None:
2185 warn("Argument given (%s) can't be found as a variable "
2202 warn("Argument given (%s) can't be found as a variable "
2186 "or as a filename." % args)
2203 "or as a filename." % args)
2187 return
2204 return
2188 use_temp = False
2205 use_temp = False
2189
2206
2190 except DataIsObject:
2207 except DataIsObject:
2191 # macros have a special edit function
2208 # macros have a special edit function
2192 if isinstance(data, Macro):
2209 if isinstance(data, Macro):
2193 raise MacroToEdit(data)
2210 raise MacroToEdit(data)
2194
2211
2195 # For objects, try to edit the file where they are defined
2212 # For objects, try to edit the file where they are defined
2196 try:
2213 try:
2197 filename = inspect.getabsfile(data)
2214 filename = inspect.getabsfile(data)
2198 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2215 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2199 # class created by %edit? Try to find source
2216 # class created by %edit? Try to find source
2200 # by looking for method definitions instead, the
2217 # by looking for method definitions instead, the
2201 # __module__ in those classes is FakeModule.
2218 # __module__ in those classes is FakeModule.
2202 attrs = [getattr(data, aname) for aname in dir(data)]
2219 attrs = [getattr(data, aname) for aname in dir(data)]
2203 for attr in attrs:
2220 for attr in attrs:
2204 if not inspect.ismethod(attr):
2221 if not inspect.ismethod(attr):
2205 continue
2222 continue
2206 filename = inspect.getabsfile(attr)
2223 filename = inspect.getabsfile(attr)
2207 if filename and 'fakemodule' not in filename.lower():
2224 if filename and 'fakemodule' not in filename.lower():
2208 # change the attribute to be the edit target instead
2225 # change the attribute to be the edit target instead
2209 data = attr
2226 data = attr
2210 break
2227 break
2211
2228
2212 datafile = 1
2229 datafile = 1
2213 except TypeError:
2230 except TypeError:
2214 filename = make_filename(args)
2231 filename = make_filename(args)
2215 datafile = 1
2232 datafile = 1
2216 warn('Could not find file where `%s` is defined.\n'
2233 warn('Could not find file where `%s` is defined.\n'
2217 'Opening a file named `%s`' % (args,filename))
2234 'Opening a file named `%s`' % (args,filename))
2218 # Now, make sure we can actually read the source (if it was in
2235 # Now, make sure we can actually read the source (if it was in
2219 # a temp file it's gone by now).
2236 # a temp file it's gone by now).
2220 if datafile:
2237 if datafile:
2221 try:
2238 try:
2222 if lineno is None:
2239 if lineno is None:
2223 lineno = inspect.getsourcelines(data)[1]
2240 lineno = inspect.getsourcelines(data)[1]
2224 except IOError:
2241 except IOError:
2225 filename = make_filename(args)
2242 filename = make_filename(args)
2226 if filename is None:
2243 if filename is None:
2227 warn('The file `%s` where `%s` was defined cannot '
2244 warn('The file `%s` where `%s` was defined cannot '
2228 'be read.' % (filename,data))
2245 'be read.' % (filename,data))
2229 return
2246 return
2230 use_temp = False
2247 use_temp = False
2231
2248
2232 if use_temp:
2249 if use_temp:
2233 filename = self.shell.mktempfile(data)
2250 filename = self.shell.mktempfile(data)
2234 print 'IPython will make a temporary file named:',filename
2251 print 'IPython will make a temporary file named:',filename
2235
2252
2236 return filename, lineno, use_temp
2253 return filename, lineno, use_temp
2237
2254
2238 def _edit_macro(self,mname,macro):
2255 def _edit_macro(self,mname,macro):
2239 """open an editor with the macro data in a file"""
2256 """open an editor with the macro data in a file"""
2240 filename = self.shell.mktempfile(macro.value)
2257 filename = self.shell.mktempfile(macro.value)
2241 self.shell.hooks.editor(filename)
2258 self.shell.hooks.editor(filename)
2242
2259
2243 # and make a new macro object, to replace the old one
2260 # and make a new macro object, to replace the old one
2244 mfile = open(filename)
2261 mfile = open(filename)
2245 mvalue = mfile.read()
2262 mvalue = mfile.read()
2246 mfile.close()
2263 mfile.close()
2247 self.shell.user_ns[mname] = Macro(mvalue)
2264 self.shell.user_ns[mname] = Macro(mvalue)
2248
2265
2249 def magic_ed(self,parameter_s=''):
2266 def magic_ed(self,parameter_s=''):
2250 """Alias to %edit."""
2267 """Alias to %edit."""
2251 return self.magic_edit(parameter_s)
2268 return self.magic_edit(parameter_s)
2252
2269
2253 @skip_doctest
2270 @skip_doctest
2254 def magic_edit(self,parameter_s='',last_call=['','']):
2271 def magic_edit(self,parameter_s='',last_call=['','']):
2255 """Bring up an editor and execute the resulting code.
2272 """Bring up an editor and execute the resulting code.
2256
2273
2257 Usage:
2274 Usage:
2258 %edit [options] [args]
2275 %edit [options] [args]
2259
2276
2260 %edit runs IPython's editor hook. The default version of this hook is
2277 %edit runs IPython's editor hook. The default version of this hook is
2261 set to call the __IPYTHON__.rc.editor command. This is read from your
2278 set to call the __IPYTHON__.rc.editor command. This is read from your
2262 environment variable $EDITOR. If this isn't found, it will default to
2279 environment variable $EDITOR. If this isn't found, it will default to
2263 vi under Linux/Unix and to notepad under Windows. See the end of this
2280 vi under Linux/Unix and to notepad under Windows. See the end of this
2264 docstring for how to change the editor hook.
2281 docstring for how to change the editor hook.
2265
2282
2266 You can also set the value of this editor via the command line option
2283 You can also set the value of this editor via the command line option
2267 '-editor' or in your ipythonrc file. This is useful if you wish to use
2284 '-editor' or in your ipythonrc file. This is useful if you wish to use
2268 specifically for IPython an editor different from your typical default
2285 specifically for IPython an editor different from your typical default
2269 (and for Windows users who typically don't set environment variables).
2286 (and for Windows users who typically don't set environment variables).
2270
2287
2271 This command allows you to conveniently edit multi-line code right in
2288 This command allows you to conveniently edit multi-line code right in
2272 your IPython session.
2289 your IPython session.
2273
2290
2274 If called without arguments, %edit opens up an empty editor with a
2291 If called without arguments, %edit opens up an empty editor with a
2275 temporary file and will execute the contents of this file when you
2292 temporary file and will execute the contents of this file when you
2276 close it (don't forget to save it!).
2293 close it (don't forget to save it!).
2277
2294
2278
2295
2279 Options:
2296 Options:
2280
2297
2281 -n <number>: open the editor at a specified line number. By default,
2298 -n <number>: open the editor at a specified line number. By default,
2282 the IPython editor hook uses the unix syntax 'editor +N filename', but
2299 the IPython editor hook uses the unix syntax 'editor +N filename', but
2283 you can configure this by providing your own modified hook if your
2300 you can configure this by providing your own modified hook if your
2284 favorite editor supports line-number specifications with a different
2301 favorite editor supports line-number specifications with a different
2285 syntax.
2302 syntax.
2286
2303
2287 -p: this will call the editor with the same data as the previous time
2304 -p: this will call the editor with the same data as the previous time
2288 it was used, regardless of how long ago (in your current session) it
2305 it was used, regardless of how long ago (in your current session) it
2289 was.
2306 was.
2290
2307
2291 -r: use 'raw' input. This option only applies to input taken from the
2308 -r: use 'raw' input. This option only applies to input taken from the
2292 user's history. By default, the 'processed' history is used, so that
2309 user's history. By default, the 'processed' history is used, so that
2293 magics are loaded in their transformed version to valid Python. If
2310 magics are loaded in their transformed version to valid Python. If
2294 this option is given, the raw input as typed as the command line is
2311 this option is given, the raw input as typed as the command line is
2295 used instead. When you exit the editor, it will be executed by
2312 used instead. When you exit the editor, it will be executed by
2296 IPython's own processor.
2313 IPython's own processor.
2297
2314
2298 -x: do not execute the edited code immediately upon exit. This is
2315 -x: do not execute the edited code immediately upon exit. This is
2299 mainly useful if you are editing programs which need to be called with
2316 mainly useful if you are editing programs which need to be called with
2300 command line arguments, which you can then do using %run.
2317 command line arguments, which you can then do using %run.
2301
2318
2302
2319
2303 Arguments:
2320 Arguments:
2304
2321
2305 If arguments are given, the following possibilites exist:
2322 If arguments are given, the following possibilites exist:
2306
2323
2307 - If the argument is a filename, IPython will load that into the
2324 - If the argument is a filename, IPython will load that into the
2308 editor. It will execute its contents with execfile() when you exit,
2325 editor. It will execute its contents with execfile() when you exit,
2309 loading any code in the file into your interactive namespace.
2326 loading any code in the file into your interactive namespace.
2310
2327
2311 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2328 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2312 The syntax is the same as in the %history magic.
2329 The syntax is the same as in the %history magic.
2313
2330
2314 - If the argument is a string variable, its contents are loaded
2331 - If the argument is a string variable, its contents are loaded
2315 into the editor. You can thus edit any string which contains
2332 into the editor. You can thus edit any string which contains
2316 python code (including the result of previous edits).
2333 python code (including the result of previous edits).
2317
2334
2318 - If the argument is the name of an object (other than a string),
2335 - If the argument is the name of an object (other than a string),
2319 IPython will try to locate the file where it was defined and open the
2336 IPython will try to locate the file where it was defined and open the
2320 editor at the point where it is defined. You can use `%edit function`
2337 editor at the point where it is defined. You can use `%edit function`
2321 to load an editor exactly at the point where 'function' is defined,
2338 to load an editor exactly at the point where 'function' is defined,
2322 edit it and have the file be executed automatically.
2339 edit it and have the file be executed automatically.
2323
2340
2324 If the object is a macro (see %macro for details), this opens up your
2341 If the object is a macro (see %macro for details), this opens up your
2325 specified editor with a temporary file containing the macro's data.
2342 specified editor with a temporary file containing the macro's data.
2326 Upon exit, the macro is reloaded with the contents of the file.
2343 Upon exit, the macro is reloaded with the contents of the file.
2327
2344
2328 Note: opening at an exact line is only supported under Unix, and some
2345 Note: opening at an exact line is only supported under Unix, and some
2329 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2346 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2330 '+NUMBER' parameter necessary for this feature. Good editors like
2347 '+NUMBER' parameter necessary for this feature. Good editors like
2331 (X)Emacs, vi, jed, pico and joe all do.
2348 (X)Emacs, vi, jed, pico and joe all do.
2332
2349
2333 After executing your code, %edit will return as output the code you
2350 After executing your code, %edit will return as output the code you
2334 typed in the editor (except when it was an existing file). This way
2351 typed in the editor (except when it was an existing file). This way
2335 you can reload the code in further invocations of %edit as a variable,
2352 you can reload the code in further invocations of %edit as a variable,
2336 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2353 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2337 the output.
2354 the output.
2338
2355
2339 Note that %edit is also available through the alias %ed.
2356 Note that %edit is also available through the alias %ed.
2340
2357
2341 This is an example of creating a simple function inside the editor and
2358 This is an example of creating a simple function inside the editor and
2342 then modifying it. First, start up the editor:
2359 then modifying it. First, start up the editor:
2343
2360
2344 In [1]: ed
2361 In [1]: ed
2345 Editing... done. Executing edited code...
2362 Editing... done. Executing edited code...
2346 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2363 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2347
2364
2348 We can then call the function foo():
2365 We can then call the function foo():
2349
2366
2350 In [2]: foo()
2367 In [2]: foo()
2351 foo() was defined in an editing session
2368 foo() was defined in an editing session
2352
2369
2353 Now we edit foo. IPython automatically loads the editor with the
2370 Now we edit foo. IPython automatically loads the editor with the
2354 (temporary) file where foo() was previously defined:
2371 (temporary) file where foo() was previously defined:
2355
2372
2356 In [3]: ed foo
2373 In [3]: ed foo
2357 Editing... done. Executing edited code...
2374 Editing... done. Executing edited code...
2358
2375
2359 And if we call foo() again we get the modified version:
2376 And if we call foo() again we get the modified version:
2360
2377
2361 In [4]: foo()
2378 In [4]: foo()
2362 foo() has now been changed!
2379 foo() has now been changed!
2363
2380
2364 Here is an example of how to edit a code snippet successive
2381 Here is an example of how to edit a code snippet successive
2365 times. First we call the editor:
2382 times. First we call the editor:
2366
2383
2367 In [5]: ed
2384 In [5]: ed
2368 Editing... done. Executing edited code...
2385 Editing... done. Executing edited code...
2369 hello
2386 hello
2370 Out[5]: "print 'hello'n"
2387 Out[5]: "print 'hello'n"
2371
2388
2372 Now we call it again with the previous output (stored in _):
2389 Now we call it again with the previous output (stored in _):
2373
2390
2374 In [6]: ed _
2391 In [6]: ed _
2375 Editing... done. Executing edited code...
2392 Editing... done. Executing edited code...
2376 hello world
2393 hello world
2377 Out[6]: "print 'hello world'n"
2394 Out[6]: "print 'hello world'n"
2378
2395
2379 Now we call it with the output #8 (stored in _8, also as Out[8]):
2396 Now we call it with the output #8 (stored in _8, also as Out[8]):
2380
2397
2381 In [7]: ed _8
2398 In [7]: ed _8
2382 Editing... done. Executing edited code...
2399 Editing... done. Executing edited code...
2383 hello again
2400 hello again
2384 Out[7]: "print 'hello again'n"
2401 Out[7]: "print 'hello again'n"
2385
2402
2386
2403
2387 Changing the default editor hook:
2404 Changing the default editor hook:
2388
2405
2389 If you wish to write your own editor hook, you can put it in a
2406 If you wish to write your own editor hook, you can put it in a
2390 configuration file which you load at startup time. The default hook
2407 configuration file which you load at startup time. The default hook
2391 is defined in the IPython.core.hooks module, and you can use that as a
2408 is defined in the IPython.core.hooks module, and you can use that as a
2392 starting example for further modifications. That file also has
2409 starting example for further modifications. That file also has
2393 general instructions on how to set a new hook for use once you've
2410 general instructions on how to set a new hook for use once you've
2394 defined it."""
2411 defined it."""
2395 opts,args = self.parse_options(parameter_s,'prxn:')
2412 opts,args = self.parse_options(parameter_s,'prxn:')
2396
2413
2397 try:
2414 try:
2398 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2415 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2399 except MacroToEdit as e:
2416 except MacroToEdit as e:
2400 self._edit_macro(args, e.args[0])
2417 self._edit_macro(args, e.args[0])
2401 return
2418 return
2402
2419
2403 # do actual editing here
2420 # do actual editing here
2404 print 'Editing...',
2421 print 'Editing...',
2405 sys.stdout.flush()
2422 sys.stdout.flush()
2406 try:
2423 try:
2407 # Quote filenames that may have spaces in them
2424 # Quote filenames that may have spaces in them
2408 if ' ' in filename:
2425 if ' ' in filename:
2409 filename = "'%s'" % filename
2426 filename = "'%s'" % filename
2410 self.shell.hooks.editor(filename,lineno)
2427 self.shell.hooks.editor(filename,lineno)
2411 except TryNext:
2428 except TryNext:
2412 warn('Could not open editor')
2429 warn('Could not open editor')
2413 return
2430 return
2414
2431
2415 # XXX TODO: should this be generalized for all string vars?
2432 # XXX TODO: should this be generalized for all string vars?
2416 # For now, this is special-cased to blocks created by cpaste
2433 # For now, this is special-cased to blocks created by cpaste
2417 if args.strip() == 'pasted_block':
2434 if args.strip() == 'pasted_block':
2418 self.shell.user_ns['pasted_block'] = file_read(filename)
2435 self.shell.user_ns['pasted_block'] = file_read(filename)
2419
2436
2420 if 'x' in opts: # -x prevents actual execution
2437 if 'x' in opts: # -x prevents actual execution
2421 print
2438 print
2422 else:
2439 else:
2423 print 'done. Executing edited code...'
2440 print 'done. Executing edited code...'
2424 if 'r' in opts: # Untranslated IPython code
2441 if 'r' in opts: # Untranslated IPython code
2425 self.shell.run_cell(file_read(filename),
2442 self.shell.run_cell(file_read(filename),
2426 store_history=False)
2443 store_history=False)
2427 else:
2444 else:
2428 self.shell.safe_execfile(filename,self.shell.user_ns,
2445 self.shell.safe_execfile(filename,self.shell.user_ns,
2429 self.shell.user_ns)
2446 self.shell.user_ns)
2430
2447
2431 if is_temp:
2448 if is_temp:
2432 try:
2449 try:
2433 return open(filename).read()
2450 return open(filename).read()
2434 except IOError,msg:
2451 except IOError,msg:
2435 if msg.filename == filename:
2452 if msg.filename == filename:
2436 warn('File not found. Did you forget to save?')
2453 warn('File not found. Did you forget to save?')
2437 return
2454 return
2438 else:
2455 else:
2439 self.shell.showtraceback()
2456 self.shell.showtraceback()
2440
2457
2441 def magic_xmode(self,parameter_s = ''):
2458 def magic_xmode(self,parameter_s = ''):
2442 """Switch modes for the exception handlers.
2459 """Switch modes for the exception handlers.
2443
2460
2444 Valid modes: Plain, Context and Verbose.
2461 Valid modes: Plain, Context and Verbose.
2445
2462
2446 If called without arguments, acts as a toggle."""
2463 If called without arguments, acts as a toggle."""
2447
2464
2448 def xmode_switch_err(name):
2465 def xmode_switch_err(name):
2449 warn('Error changing %s exception modes.\n%s' %
2466 warn('Error changing %s exception modes.\n%s' %
2450 (name,sys.exc_info()[1]))
2467 (name,sys.exc_info()[1]))
2451
2468
2452 shell = self.shell
2469 shell = self.shell
2453 new_mode = parameter_s.strip().capitalize()
2470 new_mode = parameter_s.strip().capitalize()
2454 try:
2471 try:
2455 shell.InteractiveTB.set_mode(mode=new_mode)
2472 shell.InteractiveTB.set_mode(mode=new_mode)
2456 print 'Exception reporting mode:',shell.InteractiveTB.mode
2473 print 'Exception reporting mode:',shell.InteractiveTB.mode
2457 except:
2474 except:
2458 xmode_switch_err('user')
2475 xmode_switch_err('user')
2459
2476
2460 def magic_colors(self,parameter_s = ''):
2477 def magic_colors(self,parameter_s = ''):
2461 """Switch color scheme for prompts, info system and exception handlers.
2478 """Switch color scheme for prompts, info system and exception handlers.
2462
2479
2463 Currently implemented schemes: NoColor, Linux, LightBG.
2480 Currently implemented schemes: NoColor, Linux, LightBG.
2464
2481
2465 Color scheme names are not case-sensitive.
2482 Color scheme names are not case-sensitive.
2466
2483
2467 Examples
2484 Examples
2468 --------
2485 --------
2469 To get a plain black and white terminal::
2486 To get a plain black and white terminal::
2470
2487
2471 %colors nocolor
2488 %colors nocolor
2472 """
2489 """
2473
2490
2474 def color_switch_err(name):
2491 def color_switch_err(name):
2475 warn('Error changing %s color schemes.\n%s' %
2492 warn('Error changing %s color schemes.\n%s' %
2476 (name,sys.exc_info()[1]))
2493 (name,sys.exc_info()[1]))
2477
2494
2478
2495
2479 new_scheme = parameter_s.strip()
2496 new_scheme = parameter_s.strip()
2480 if not new_scheme:
2497 if not new_scheme:
2481 raise UsageError(
2498 raise UsageError(
2482 "%colors: you must specify a color scheme. See '%colors?'")
2499 "%colors: you must specify a color scheme. See '%colors?'")
2483 return
2500 return
2484 # local shortcut
2501 # local shortcut
2485 shell = self.shell
2502 shell = self.shell
2486
2503
2487 import IPython.utils.rlineimpl as readline
2504 import IPython.utils.rlineimpl as readline
2488
2505
2489 if not readline.have_readline and sys.platform == "win32":
2506 if not readline.have_readline and sys.platform == "win32":
2490 msg = """\
2507 msg = """\
2491 Proper color support under MS Windows requires the pyreadline library.
2508 Proper color support under MS Windows requires the pyreadline library.
2492 You can find it at:
2509 You can find it at:
2493 http://ipython.scipy.org/moin/PyReadline/Intro
2510 http://ipython.scipy.org/moin/PyReadline/Intro
2494 Gary's readline needs the ctypes module, from:
2511 Gary's readline needs the ctypes module, from:
2495 http://starship.python.net/crew/theller/ctypes
2512 http://starship.python.net/crew/theller/ctypes
2496 (Note that ctypes is already part of Python versions 2.5 and newer).
2513 (Note that ctypes is already part of Python versions 2.5 and newer).
2497
2514
2498 Defaulting color scheme to 'NoColor'"""
2515 Defaulting color scheme to 'NoColor'"""
2499 new_scheme = 'NoColor'
2516 new_scheme = 'NoColor'
2500 warn(msg)
2517 warn(msg)
2501
2518
2502 # readline option is 0
2519 # readline option is 0
2503 if not shell.has_readline:
2520 if not shell.has_readline:
2504 new_scheme = 'NoColor'
2521 new_scheme = 'NoColor'
2505
2522
2506 # Set prompt colors
2523 # Set prompt colors
2507 try:
2524 try:
2508 shell.displayhook.set_colors(new_scheme)
2525 shell.displayhook.set_colors(new_scheme)
2509 except:
2526 except:
2510 color_switch_err('prompt')
2527 color_switch_err('prompt')
2511 else:
2528 else:
2512 shell.colors = \
2529 shell.colors = \
2513 shell.displayhook.color_table.active_scheme_name
2530 shell.displayhook.color_table.active_scheme_name
2514 # Set exception colors
2531 # Set exception colors
2515 try:
2532 try:
2516 shell.InteractiveTB.set_colors(scheme = new_scheme)
2533 shell.InteractiveTB.set_colors(scheme = new_scheme)
2517 shell.SyntaxTB.set_colors(scheme = new_scheme)
2534 shell.SyntaxTB.set_colors(scheme = new_scheme)
2518 except:
2535 except:
2519 color_switch_err('exception')
2536 color_switch_err('exception')
2520
2537
2521 # Set info (for 'object?') colors
2538 # Set info (for 'object?') colors
2522 if shell.color_info:
2539 if shell.color_info:
2523 try:
2540 try:
2524 shell.inspector.set_active_scheme(new_scheme)
2541 shell.inspector.set_active_scheme(new_scheme)
2525 except:
2542 except:
2526 color_switch_err('object inspector')
2543 color_switch_err('object inspector')
2527 else:
2544 else:
2528 shell.inspector.set_active_scheme('NoColor')
2545 shell.inspector.set_active_scheme('NoColor')
2529
2546
2530 def magic_pprint(self, parameter_s=''):
2547 def magic_pprint(self, parameter_s=''):
2531 """Toggle pretty printing on/off."""
2548 """Toggle pretty printing on/off."""
2532 ptformatter = self.shell.display_formatter.formatters['text/plain']
2549 ptformatter = self.shell.display_formatter.formatters['text/plain']
2533 ptformatter.pprint = bool(1 - ptformatter.pprint)
2550 ptformatter.pprint = bool(1 - ptformatter.pprint)
2534 print 'Pretty printing has been turned', \
2551 print 'Pretty printing has been turned', \
2535 ['OFF','ON'][ptformatter.pprint]
2552 ['OFF','ON'][ptformatter.pprint]
2536
2553
2537 #......................................................................
2554 #......................................................................
2538 # Functions to implement unix shell-type things
2555 # Functions to implement unix shell-type things
2539
2556
2540 @skip_doctest
2557 @skip_doctest
2541 def magic_alias(self, parameter_s = ''):
2558 def magic_alias(self, parameter_s = ''):
2542 """Define an alias for a system command.
2559 """Define an alias for a system command.
2543
2560
2544 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2561 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2545
2562
2546 Then, typing 'alias_name params' will execute the system command 'cmd
2563 Then, typing 'alias_name params' will execute the system command 'cmd
2547 params' (from your underlying operating system).
2564 params' (from your underlying operating system).
2548
2565
2549 Aliases have lower precedence than magic functions and Python normal
2566 Aliases have lower precedence than magic functions and Python normal
2550 variables, so if 'foo' is both a Python variable and an alias, the
2567 variables, so if 'foo' is both a Python variable and an alias, the
2551 alias can not be executed until 'del foo' removes the Python variable.
2568 alias can not be executed until 'del foo' removes the Python variable.
2552
2569
2553 You can use the %l specifier in an alias definition to represent the
2570 You can use the %l specifier in an alias definition to represent the
2554 whole line when the alias is called. For example:
2571 whole line when the alias is called. For example:
2555
2572
2556 In [2]: alias bracket echo "Input in brackets: <%l>"
2573 In [2]: alias bracket echo "Input in brackets: <%l>"
2557 In [3]: bracket hello world
2574 In [3]: bracket hello world
2558 Input in brackets: <hello world>
2575 Input in brackets: <hello world>
2559
2576
2560 You can also define aliases with parameters using %s specifiers (one
2577 You can also define aliases with parameters using %s specifiers (one
2561 per parameter):
2578 per parameter):
2562
2579
2563 In [1]: alias parts echo first %s second %s
2580 In [1]: alias parts echo first %s second %s
2564 In [2]: %parts A B
2581 In [2]: %parts A B
2565 first A second B
2582 first A second B
2566 In [3]: %parts A
2583 In [3]: %parts A
2567 Incorrect number of arguments: 2 expected.
2584 Incorrect number of arguments: 2 expected.
2568 parts is an alias to: 'echo first %s second %s'
2585 parts is an alias to: 'echo first %s second %s'
2569
2586
2570 Note that %l and %s are mutually exclusive. You can only use one or
2587 Note that %l and %s are mutually exclusive. You can only use one or
2571 the other in your aliases.
2588 the other in your aliases.
2572
2589
2573 Aliases expand Python variables just like system calls using ! or !!
2590 Aliases expand Python variables just like system calls using ! or !!
2574 do: all expressions prefixed with '$' get expanded. For details of
2591 do: all expressions prefixed with '$' get expanded. For details of
2575 the semantic rules, see PEP-215:
2592 the semantic rules, see PEP-215:
2576 http://www.python.org/peps/pep-0215.html. This is the library used by
2593 http://www.python.org/peps/pep-0215.html. This is the library used by
2577 IPython for variable expansion. If you want to access a true shell
2594 IPython for variable expansion. If you want to access a true shell
2578 variable, an extra $ is necessary to prevent its expansion by IPython:
2595 variable, an extra $ is necessary to prevent its expansion by IPython:
2579
2596
2580 In [6]: alias show echo
2597 In [6]: alias show echo
2581 In [7]: PATH='A Python string'
2598 In [7]: PATH='A Python string'
2582 In [8]: show $PATH
2599 In [8]: show $PATH
2583 A Python string
2600 A Python string
2584 In [9]: show $$PATH
2601 In [9]: show $$PATH
2585 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2602 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2586
2603
2587 You can use the alias facility to acess all of $PATH. See the %rehash
2604 You can use the alias facility to acess all of $PATH. See the %rehash
2588 and %rehashx functions, which automatically create aliases for the
2605 and %rehashx functions, which automatically create aliases for the
2589 contents of your $PATH.
2606 contents of your $PATH.
2590
2607
2591 If called with no parameters, %alias prints the current alias table."""
2608 If called with no parameters, %alias prints the current alias table."""
2592
2609
2593 par = parameter_s.strip()
2610 par = parameter_s.strip()
2594 if not par:
2611 if not par:
2595 stored = self.db.get('stored_aliases', {} )
2612 stored = self.db.get('stored_aliases', {} )
2596 aliases = sorted(self.shell.alias_manager.aliases)
2613 aliases = sorted(self.shell.alias_manager.aliases)
2597 # for k, v in stored:
2614 # for k, v in stored:
2598 # atab.append(k, v[0])
2615 # atab.append(k, v[0])
2599
2616
2600 print "Total number of aliases:", len(aliases)
2617 print "Total number of aliases:", len(aliases)
2601 sys.stdout.flush()
2618 sys.stdout.flush()
2602 return aliases
2619 return aliases
2603
2620
2604 # Now try to define a new one
2621 # Now try to define a new one
2605 try:
2622 try:
2606 alias,cmd = par.split(None, 1)
2623 alias,cmd = par.split(None, 1)
2607 except:
2624 except:
2608 print oinspect.getdoc(self.magic_alias)
2625 print oinspect.getdoc(self.magic_alias)
2609 else:
2626 else:
2610 self.shell.alias_manager.soft_define_alias(alias, cmd)
2627 self.shell.alias_manager.soft_define_alias(alias, cmd)
2611 # end magic_alias
2628 # end magic_alias
2612
2629
2613 def magic_unalias(self, parameter_s = ''):
2630 def magic_unalias(self, parameter_s = ''):
2614 """Remove an alias"""
2631 """Remove an alias"""
2615
2632
2616 aname = parameter_s.strip()
2633 aname = parameter_s.strip()
2617 self.shell.alias_manager.undefine_alias(aname)
2634 self.shell.alias_manager.undefine_alias(aname)
2618 stored = self.db.get('stored_aliases', {} )
2635 stored = self.db.get('stored_aliases', {} )
2619 if aname in stored:
2636 if aname in stored:
2620 print "Removing %stored alias",aname
2637 print "Removing %stored alias",aname
2621 del stored[aname]
2638 del stored[aname]
2622 self.db['stored_aliases'] = stored
2639 self.db['stored_aliases'] = stored
2623
2640
2624 def magic_rehashx(self, parameter_s = ''):
2641 def magic_rehashx(self, parameter_s = ''):
2625 """Update the alias table with all executable files in $PATH.
2642 """Update the alias table with all executable files in $PATH.
2626
2643
2627 This version explicitly checks that every entry in $PATH is a file
2644 This version explicitly checks that every entry in $PATH is a file
2628 with execute access (os.X_OK), so it is much slower than %rehash.
2645 with execute access (os.X_OK), so it is much slower than %rehash.
2629
2646
2630 Under Windows, it checks executability as a match agains a
2647 Under Windows, it checks executability as a match agains a
2631 '|'-separated string of extensions, stored in the IPython config
2648 '|'-separated string of extensions, stored in the IPython config
2632 variable win_exec_ext. This defaults to 'exe|com|bat'.
2649 variable win_exec_ext. This defaults to 'exe|com|bat'.
2633
2650
2634 This function also resets the root module cache of module completer,
2651 This function also resets the root module cache of module completer,
2635 used on slow filesystems.
2652 used on slow filesystems.
2636 """
2653 """
2637 from IPython.core.alias import InvalidAliasError
2654 from IPython.core.alias import InvalidAliasError
2638
2655
2639 # for the benefit of module completer in ipy_completers.py
2656 # for the benefit of module completer in ipy_completers.py
2640 del self.db['rootmodules']
2657 del self.db['rootmodules']
2641
2658
2642 path = [os.path.abspath(os.path.expanduser(p)) for p in
2659 path = [os.path.abspath(os.path.expanduser(p)) for p in
2643 os.environ.get('PATH','').split(os.pathsep)]
2660 os.environ.get('PATH','').split(os.pathsep)]
2644 path = filter(os.path.isdir,path)
2661 path = filter(os.path.isdir,path)
2645
2662
2646 syscmdlist = []
2663 syscmdlist = []
2647 # Now define isexec in a cross platform manner.
2664 # Now define isexec in a cross platform manner.
2648 if os.name == 'posix':
2665 if os.name == 'posix':
2649 isexec = lambda fname:os.path.isfile(fname) and \
2666 isexec = lambda fname:os.path.isfile(fname) and \
2650 os.access(fname,os.X_OK)
2667 os.access(fname,os.X_OK)
2651 else:
2668 else:
2652 try:
2669 try:
2653 winext = os.environ['pathext'].replace(';','|').replace('.','')
2670 winext = os.environ['pathext'].replace(';','|').replace('.','')
2654 except KeyError:
2671 except KeyError:
2655 winext = 'exe|com|bat|py'
2672 winext = 'exe|com|bat|py'
2656 if 'py' not in winext:
2673 if 'py' not in winext:
2657 winext += '|py'
2674 winext += '|py'
2658 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2675 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2659 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2676 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2660 savedir = os.getcwd()
2677 savedir = os.getcwd()
2661
2678
2662 # Now walk the paths looking for executables to alias.
2679 # Now walk the paths looking for executables to alias.
2663 try:
2680 try:
2664 # write the whole loop for posix/Windows so we don't have an if in
2681 # write the whole loop for posix/Windows so we don't have an if in
2665 # the innermost part
2682 # the innermost part
2666 if os.name == 'posix':
2683 if os.name == 'posix':
2667 for pdir in path:
2684 for pdir in path:
2668 os.chdir(pdir)
2685 os.chdir(pdir)
2669 for ff in os.listdir(pdir):
2686 for ff in os.listdir(pdir):
2670 if isexec(ff):
2687 if isexec(ff):
2671 try:
2688 try:
2672 # Removes dots from the name since ipython
2689 # Removes dots from the name since ipython
2673 # will assume names with dots to be python.
2690 # will assume names with dots to be python.
2674 self.shell.alias_manager.define_alias(
2691 self.shell.alias_manager.define_alias(
2675 ff.replace('.',''), ff)
2692 ff.replace('.',''), ff)
2676 except InvalidAliasError:
2693 except InvalidAliasError:
2677 pass
2694 pass
2678 else:
2695 else:
2679 syscmdlist.append(ff)
2696 syscmdlist.append(ff)
2680 else:
2697 else:
2681 no_alias = self.shell.alias_manager.no_alias
2698 no_alias = self.shell.alias_manager.no_alias
2682 for pdir in path:
2699 for pdir in path:
2683 os.chdir(pdir)
2700 os.chdir(pdir)
2684 for ff in os.listdir(pdir):
2701 for ff in os.listdir(pdir):
2685 base, ext = os.path.splitext(ff)
2702 base, ext = os.path.splitext(ff)
2686 if isexec(ff) and base.lower() not in no_alias:
2703 if isexec(ff) and base.lower() not in no_alias:
2687 if ext.lower() == '.exe':
2704 if ext.lower() == '.exe':
2688 ff = base
2705 ff = base
2689 try:
2706 try:
2690 # Removes dots from the name since ipython
2707 # Removes dots from the name since ipython
2691 # will assume names with dots to be python.
2708 # will assume names with dots to be python.
2692 self.shell.alias_manager.define_alias(
2709 self.shell.alias_manager.define_alias(
2693 base.lower().replace('.',''), ff)
2710 base.lower().replace('.',''), ff)
2694 except InvalidAliasError:
2711 except InvalidAliasError:
2695 pass
2712 pass
2696 syscmdlist.append(ff)
2713 syscmdlist.append(ff)
2697 db = self.db
2714 db = self.db
2698 db['syscmdlist'] = syscmdlist
2715 db['syscmdlist'] = syscmdlist
2699 finally:
2716 finally:
2700 os.chdir(savedir)
2717 os.chdir(savedir)
2701
2718
2702 @skip_doctest
2719 @skip_doctest
2703 def magic_pwd(self, parameter_s = ''):
2720 def magic_pwd(self, parameter_s = ''):
2704 """Return the current working directory path.
2721 """Return the current working directory path.
2705
2722
2706 Examples
2723 Examples
2707 --------
2724 --------
2708 ::
2725 ::
2709
2726
2710 In [9]: pwd
2727 In [9]: pwd
2711 Out[9]: '/home/tsuser/sprint/ipython'
2728 Out[9]: '/home/tsuser/sprint/ipython'
2712 """
2729 """
2713 return os.getcwd()
2730 return os.getcwd()
2714
2731
2715 @skip_doctest
2732 @skip_doctest
2716 def magic_cd(self, parameter_s=''):
2733 def magic_cd(self, parameter_s=''):
2717 """Change the current working directory.
2734 """Change the current working directory.
2718
2735
2719 This command automatically maintains an internal list of directories
2736 This command automatically maintains an internal list of directories
2720 you visit during your IPython session, in the variable _dh. The
2737 you visit during your IPython session, in the variable _dh. The
2721 command %dhist shows this history nicely formatted. You can also
2738 command %dhist shows this history nicely formatted. You can also
2722 do 'cd -<tab>' to see directory history conveniently.
2739 do 'cd -<tab>' to see directory history conveniently.
2723
2740
2724 Usage:
2741 Usage:
2725
2742
2726 cd 'dir': changes to directory 'dir'.
2743 cd 'dir': changes to directory 'dir'.
2727
2744
2728 cd -: changes to the last visited directory.
2745 cd -: changes to the last visited directory.
2729
2746
2730 cd -<n>: changes to the n-th directory in the directory history.
2747 cd -<n>: changes to the n-th directory in the directory history.
2731
2748
2732 cd --foo: change to directory that matches 'foo' in history
2749 cd --foo: change to directory that matches 'foo' in history
2733
2750
2734 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2751 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2735 (note: cd <bookmark_name> is enough if there is no
2752 (note: cd <bookmark_name> is enough if there is no
2736 directory <bookmark_name>, but a bookmark with the name exists.)
2753 directory <bookmark_name>, but a bookmark with the name exists.)
2737 'cd -b <tab>' allows you to tab-complete bookmark names.
2754 'cd -b <tab>' allows you to tab-complete bookmark names.
2738
2755
2739 Options:
2756 Options:
2740
2757
2741 -q: quiet. Do not print the working directory after the cd command is
2758 -q: quiet. Do not print the working directory after the cd command is
2742 executed. By default IPython's cd command does print this directory,
2759 executed. By default IPython's cd command does print this directory,
2743 since the default prompts do not display path information.
2760 since the default prompts do not display path information.
2744
2761
2745 Note that !cd doesn't work for this purpose because the shell where
2762 Note that !cd doesn't work for this purpose because the shell where
2746 !command runs is immediately discarded after executing 'command'.
2763 !command runs is immediately discarded after executing 'command'.
2747
2764
2748 Examples
2765 Examples
2749 --------
2766 --------
2750 ::
2767 ::
2751
2768
2752 In [10]: cd parent/child
2769 In [10]: cd parent/child
2753 /home/tsuser/parent/child
2770 /home/tsuser/parent/child
2754 """
2771 """
2755
2772
2756 parameter_s = parameter_s.strip()
2773 parameter_s = parameter_s.strip()
2757 #bkms = self.shell.persist.get("bookmarks",{})
2774 #bkms = self.shell.persist.get("bookmarks",{})
2758
2775
2759 oldcwd = os.getcwd()
2776 oldcwd = os.getcwd()
2760 numcd = re.match(r'(-)(\d+)$',parameter_s)
2777 numcd = re.match(r'(-)(\d+)$',parameter_s)
2761 # jump in directory history by number
2778 # jump in directory history by number
2762 if numcd:
2779 if numcd:
2763 nn = int(numcd.group(2))
2780 nn = int(numcd.group(2))
2764 try:
2781 try:
2765 ps = self.shell.user_ns['_dh'][nn]
2782 ps = self.shell.user_ns['_dh'][nn]
2766 except IndexError:
2783 except IndexError:
2767 print 'The requested directory does not exist in history.'
2784 print 'The requested directory does not exist in history.'
2768 return
2785 return
2769 else:
2786 else:
2770 opts = {}
2787 opts = {}
2771 elif parameter_s.startswith('--'):
2788 elif parameter_s.startswith('--'):
2772 ps = None
2789 ps = None
2773 fallback = None
2790 fallback = None
2774 pat = parameter_s[2:]
2791 pat = parameter_s[2:]
2775 dh = self.shell.user_ns['_dh']
2792 dh = self.shell.user_ns['_dh']
2776 # first search only by basename (last component)
2793 # first search only by basename (last component)
2777 for ent in reversed(dh):
2794 for ent in reversed(dh):
2778 if pat in os.path.basename(ent) and os.path.isdir(ent):
2795 if pat in os.path.basename(ent) and os.path.isdir(ent):
2779 ps = ent
2796 ps = ent
2780 break
2797 break
2781
2798
2782 if fallback is None and pat in ent and os.path.isdir(ent):
2799 if fallback is None and pat in ent and os.path.isdir(ent):
2783 fallback = ent
2800 fallback = ent
2784
2801
2785 # if we have no last part match, pick the first full path match
2802 # if we have no last part match, pick the first full path match
2786 if ps is None:
2803 if ps is None:
2787 ps = fallback
2804 ps = fallback
2788
2805
2789 if ps is None:
2806 if ps is None:
2790 print "No matching entry in directory history"
2807 print "No matching entry in directory history"
2791 return
2808 return
2792 else:
2809 else:
2793 opts = {}
2810 opts = {}
2794
2811
2795
2812
2796 else:
2813 else:
2797 #turn all non-space-escaping backslashes to slashes,
2814 #turn all non-space-escaping backslashes to slashes,
2798 # for c:\windows\directory\names\
2815 # for c:\windows\directory\names\
2799 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2816 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2800 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2817 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2801 # jump to previous
2818 # jump to previous
2802 if ps == '-':
2819 if ps == '-':
2803 try:
2820 try:
2804 ps = self.shell.user_ns['_dh'][-2]
2821 ps = self.shell.user_ns['_dh'][-2]
2805 except IndexError:
2822 except IndexError:
2806 raise UsageError('%cd -: No previous directory to change to.')
2823 raise UsageError('%cd -: No previous directory to change to.')
2807 # jump to bookmark if needed
2824 # jump to bookmark if needed
2808 else:
2825 else:
2809 if not os.path.isdir(ps) or opts.has_key('b'):
2826 if not os.path.isdir(ps) or opts.has_key('b'):
2810 bkms = self.db.get('bookmarks', {})
2827 bkms = self.db.get('bookmarks', {})
2811
2828
2812 if bkms.has_key(ps):
2829 if bkms.has_key(ps):
2813 target = bkms[ps]
2830 target = bkms[ps]
2814 print '(bookmark:%s) -> %s' % (ps,target)
2831 print '(bookmark:%s) -> %s' % (ps,target)
2815 ps = target
2832 ps = target
2816 else:
2833 else:
2817 if opts.has_key('b'):
2834 if opts.has_key('b'):
2818 raise UsageError("Bookmark '%s' not found. "
2835 raise UsageError("Bookmark '%s' not found. "
2819 "Use '%%bookmark -l' to see your bookmarks." % ps)
2836 "Use '%%bookmark -l' to see your bookmarks." % ps)
2820
2837
2821 # at this point ps should point to the target dir
2838 # at this point ps should point to the target dir
2822 if ps:
2839 if ps:
2823 try:
2840 try:
2824 os.chdir(os.path.expanduser(ps))
2841 os.chdir(os.path.expanduser(ps))
2825 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2842 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2826 set_term_title('IPython: ' + abbrev_cwd())
2843 set_term_title('IPython: ' + abbrev_cwd())
2827 except OSError:
2844 except OSError:
2828 print sys.exc_info()[1]
2845 print sys.exc_info()[1]
2829 else:
2846 else:
2830 cwd = os.getcwd()
2847 cwd = os.getcwd()
2831 dhist = self.shell.user_ns['_dh']
2848 dhist = self.shell.user_ns['_dh']
2832 if oldcwd != cwd:
2849 if oldcwd != cwd:
2833 dhist.append(cwd)
2850 dhist.append(cwd)
2834 self.db['dhist'] = compress_dhist(dhist)[-100:]
2851 self.db['dhist'] = compress_dhist(dhist)[-100:]
2835
2852
2836 else:
2853 else:
2837 os.chdir(self.shell.home_dir)
2854 os.chdir(self.shell.home_dir)
2838 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2855 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2839 set_term_title('IPython: ' + '~')
2856 set_term_title('IPython: ' + '~')
2840 cwd = os.getcwd()
2857 cwd = os.getcwd()
2841 dhist = self.shell.user_ns['_dh']
2858 dhist = self.shell.user_ns['_dh']
2842
2859
2843 if oldcwd != cwd:
2860 if oldcwd != cwd:
2844 dhist.append(cwd)
2861 dhist.append(cwd)
2845 self.db['dhist'] = compress_dhist(dhist)[-100:]
2862 self.db['dhist'] = compress_dhist(dhist)[-100:]
2846 if not 'q' in opts and self.shell.user_ns['_dh']:
2863 if not 'q' in opts and self.shell.user_ns['_dh']:
2847 print self.shell.user_ns['_dh'][-1]
2864 print self.shell.user_ns['_dh'][-1]
2848
2865
2849
2866
2850 def magic_env(self, parameter_s=''):
2867 def magic_env(self, parameter_s=''):
2851 """List environment variables."""
2868 """List environment variables."""
2852
2869
2853 return os.environ.data
2870 return os.environ.data
2854
2871
2855 def magic_pushd(self, parameter_s=''):
2872 def magic_pushd(self, parameter_s=''):
2856 """Place the current dir on stack and change directory.
2873 """Place the current dir on stack and change directory.
2857
2874
2858 Usage:\\
2875 Usage:\\
2859 %pushd ['dirname']
2876 %pushd ['dirname']
2860 """
2877 """
2861
2878
2862 dir_s = self.shell.dir_stack
2879 dir_s = self.shell.dir_stack
2863 tgt = os.path.expanduser(parameter_s)
2880 tgt = os.path.expanduser(parameter_s)
2864 cwd = os.getcwd().replace(self.home_dir,'~')
2881 cwd = os.getcwd().replace(self.home_dir,'~')
2865 if tgt:
2882 if tgt:
2866 self.magic_cd(parameter_s)
2883 self.magic_cd(parameter_s)
2867 dir_s.insert(0,cwd)
2884 dir_s.insert(0,cwd)
2868 return self.magic_dirs()
2885 return self.magic_dirs()
2869
2886
2870 def magic_popd(self, parameter_s=''):
2887 def magic_popd(self, parameter_s=''):
2871 """Change to directory popped off the top of the stack.
2888 """Change to directory popped off the top of the stack.
2872 """
2889 """
2873 if not self.shell.dir_stack:
2890 if not self.shell.dir_stack:
2874 raise UsageError("%popd on empty stack")
2891 raise UsageError("%popd on empty stack")
2875 top = self.shell.dir_stack.pop(0)
2892 top = self.shell.dir_stack.pop(0)
2876 self.magic_cd(top)
2893 self.magic_cd(top)
2877 print "popd ->",top
2894 print "popd ->",top
2878
2895
2879 def magic_dirs(self, parameter_s=''):
2896 def magic_dirs(self, parameter_s=''):
2880 """Return the current directory stack."""
2897 """Return the current directory stack."""
2881
2898
2882 return self.shell.dir_stack
2899 return self.shell.dir_stack
2883
2900
2884 def magic_dhist(self, parameter_s=''):
2901 def magic_dhist(self, parameter_s=''):
2885 """Print your history of visited directories.
2902 """Print your history of visited directories.
2886
2903
2887 %dhist -> print full history\\
2904 %dhist -> print full history\\
2888 %dhist n -> print last n entries only\\
2905 %dhist n -> print last n entries only\\
2889 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2906 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2890
2907
2891 This history is automatically maintained by the %cd command, and
2908 This history is automatically maintained by the %cd command, and
2892 always available as the global list variable _dh. You can use %cd -<n>
2909 always available as the global list variable _dh. You can use %cd -<n>
2893 to go to directory number <n>.
2910 to go to directory number <n>.
2894
2911
2895 Note that most of time, you should view directory history by entering
2912 Note that most of time, you should view directory history by entering
2896 cd -<TAB>.
2913 cd -<TAB>.
2897
2914
2898 """
2915 """
2899
2916
2900 dh = self.shell.user_ns['_dh']
2917 dh = self.shell.user_ns['_dh']
2901 if parameter_s:
2918 if parameter_s:
2902 try:
2919 try:
2903 args = map(int,parameter_s.split())
2920 args = map(int,parameter_s.split())
2904 except:
2921 except:
2905 self.arg_err(Magic.magic_dhist)
2922 self.arg_err(Magic.magic_dhist)
2906 return
2923 return
2907 if len(args) == 1:
2924 if len(args) == 1:
2908 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2925 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2909 elif len(args) == 2:
2926 elif len(args) == 2:
2910 ini,fin = args
2927 ini,fin = args
2911 else:
2928 else:
2912 self.arg_err(Magic.magic_dhist)
2929 self.arg_err(Magic.magic_dhist)
2913 return
2930 return
2914 else:
2931 else:
2915 ini,fin = 0,len(dh)
2932 ini,fin = 0,len(dh)
2916 nlprint(dh,
2933 nlprint(dh,
2917 header = 'Directory history (kept in _dh)',
2934 header = 'Directory history (kept in _dh)',
2918 start=ini,stop=fin)
2935 start=ini,stop=fin)
2919
2936
2920 @skip_doctest
2937 @skip_doctest
2921 def magic_sc(self, parameter_s=''):
2938 def magic_sc(self, parameter_s=''):
2922 """Shell capture - execute a shell command and capture its output.
2939 """Shell capture - execute a shell command and capture its output.
2923
2940
2924 DEPRECATED. Suboptimal, retained for backwards compatibility.
2941 DEPRECATED. Suboptimal, retained for backwards compatibility.
2925
2942
2926 You should use the form 'var = !command' instead. Example:
2943 You should use the form 'var = !command' instead. Example:
2927
2944
2928 "%sc -l myfiles = ls ~" should now be written as
2945 "%sc -l myfiles = ls ~" should now be written as
2929
2946
2930 "myfiles = !ls ~"
2947 "myfiles = !ls ~"
2931
2948
2932 myfiles.s, myfiles.l and myfiles.n still apply as documented
2949 myfiles.s, myfiles.l and myfiles.n still apply as documented
2933 below.
2950 below.
2934
2951
2935 --
2952 --
2936 %sc [options] varname=command
2953 %sc [options] varname=command
2937
2954
2938 IPython will run the given command using commands.getoutput(), and
2955 IPython will run the given command using commands.getoutput(), and
2939 will then update the user's interactive namespace with a variable
2956 will then update the user's interactive namespace with a variable
2940 called varname, containing the value of the call. Your command can
2957 called varname, containing the value of the call. Your command can
2941 contain shell wildcards, pipes, etc.
2958 contain shell wildcards, pipes, etc.
2942
2959
2943 The '=' sign in the syntax is mandatory, and the variable name you
2960 The '=' sign in the syntax is mandatory, and the variable name you
2944 supply must follow Python's standard conventions for valid names.
2961 supply must follow Python's standard conventions for valid names.
2945
2962
2946 (A special format without variable name exists for internal use)
2963 (A special format without variable name exists for internal use)
2947
2964
2948 Options:
2965 Options:
2949
2966
2950 -l: list output. Split the output on newlines into a list before
2967 -l: list output. Split the output on newlines into a list before
2951 assigning it to the given variable. By default the output is stored
2968 assigning it to the given variable. By default the output is stored
2952 as a single string.
2969 as a single string.
2953
2970
2954 -v: verbose. Print the contents of the variable.
2971 -v: verbose. Print the contents of the variable.
2955
2972
2956 In most cases you should not need to split as a list, because the
2973 In most cases you should not need to split as a list, because the
2957 returned value is a special type of string which can automatically
2974 returned value is a special type of string which can automatically
2958 provide its contents either as a list (split on newlines) or as a
2975 provide its contents either as a list (split on newlines) or as a
2959 space-separated string. These are convenient, respectively, either
2976 space-separated string. These are convenient, respectively, either
2960 for sequential processing or to be passed to a shell command.
2977 for sequential processing or to be passed to a shell command.
2961
2978
2962 For example:
2979 For example:
2963
2980
2964 # all-random
2981 # all-random
2965
2982
2966 # Capture into variable a
2983 # Capture into variable a
2967 In [1]: sc a=ls *py
2984 In [1]: sc a=ls *py
2968
2985
2969 # a is a string with embedded newlines
2986 # a is a string with embedded newlines
2970 In [2]: a
2987 In [2]: a
2971 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2988 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2972
2989
2973 # which can be seen as a list:
2990 # which can be seen as a list:
2974 In [3]: a.l
2991 In [3]: a.l
2975 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2992 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2976
2993
2977 # or as a whitespace-separated string:
2994 # or as a whitespace-separated string:
2978 In [4]: a.s
2995 In [4]: a.s
2979 Out[4]: 'setup.py win32_manual_post_install.py'
2996 Out[4]: 'setup.py win32_manual_post_install.py'
2980
2997
2981 # a.s is useful to pass as a single command line:
2998 # a.s is useful to pass as a single command line:
2982 In [5]: !wc -l $a.s
2999 In [5]: !wc -l $a.s
2983 146 setup.py
3000 146 setup.py
2984 130 win32_manual_post_install.py
3001 130 win32_manual_post_install.py
2985 276 total
3002 276 total
2986
3003
2987 # while the list form is useful to loop over:
3004 # while the list form is useful to loop over:
2988 In [6]: for f in a.l:
3005 In [6]: for f in a.l:
2989 ...: !wc -l $f
3006 ...: !wc -l $f
2990 ...:
3007 ...:
2991 146 setup.py
3008 146 setup.py
2992 130 win32_manual_post_install.py
3009 130 win32_manual_post_install.py
2993
3010
2994 Similiarly, the lists returned by the -l option are also special, in
3011 Similiarly, the lists returned by the -l option are also special, in
2995 the sense that you can equally invoke the .s attribute on them to
3012 the sense that you can equally invoke the .s attribute on them to
2996 automatically get a whitespace-separated string from their contents:
3013 automatically get a whitespace-separated string from their contents:
2997
3014
2998 In [7]: sc -l b=ls *py
3015 In [7]: sc -l b=ls *py
2999
3016
3000 In [8]: b
3017 In [8]: b
3001 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3018 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3002
3019
3003 In [9]: b.s
3020 In [9]: b.s
3004 Out[9]: 'setup.py win32_manual_post_install.py'
3021 Out[9]: 'setup.py win32_manual_post_install.py'
3005
3022
3006 In summary, both the lists and strings used for ouptut capture have
3023 In summary, both the lists and strings used for ouptut capture have
3007 the following special attributes:
3024 the following special attributes:
3008
3025
3009 .l (or .list) : value as list.
3026 .l (or .list) : value as list.
3010 .n (or .nlstr): value as newline-separated string.
3027 .n (or .nlstr): value as newline-separated string.
3011 .s (or .spstr): value as space-separated string.
3028 .s (or .spstr): value as space-separated string.
3012 """
3029 """
3013
3030
3014 opts,args = self.parse_options(parameter_s,'lv')
3031 opts,args = self.parse_options(parameter_s,'lv')
3015 # Try to get a variable name and command to run
3032 # Try to get a variable name and command to run
3016 try:
3033 try:
3017 # the variable name must be obtained from the parse_options
3034 # the variable name must be obtained from the parse_options
3018 # output, which uses shlex.split to strip options out.
3035 # output, which uses shlex.split to strip options out.
3019 var,_ = args.split('=',1)
3036 var,_ = args.split('=',1)
3020 var = var.strip()
3037 var = var.strip()
3021 # But the the command has to be extracted from the original input
3038 # But the the command has to be extracted from the original input
3022 # parameter_s, not on what parse_options returns, to avoid the
3039 # parameter_s, not on what parse_options returns, to avoid the
3023 # quote stripping which shlex.split performs on it.
3040 # quote stripping which shlex.split performs on it.
3024 _,cmd = parameter_s.split('=',1)
3041 _,cmd = parameter_s.split('=',1)
3025 except ValueError:
3042 except ValueError:
3026 var,cmd = '',''
3043 var,cmd = '',''
3027 # If all looks ok, proceed
3044 # If all looks ok, proceed
3028 split = 'l' in opts
3045 split = 'l' in opts
3029 out = self.shell.getoutput(cmd, split=split)
3046 out = self.shell.getoutput(cmd, split=split)
3030 if opts.has_key('v'):
3047 if opts.has_key('v'):
3031 print '%s ==\n%s' % (var,pformat(out))
3048 print '%s ==\n%s' % (var,pformat(out))
3032 if var:
3049 if var:
3033 self.shell.user_ns.update({var:out})
3050 self.shell.user_ns.update({var:out})
3034 else:
3051 else:
3035 return out
3052 return out
3036
3053
3037 def magic_sx(self, parameter_s=''):
3054 def magic_sx(self, parameter_s=''):
3038 """Shell execute - run a shell command and capture its output.
3055 """Shell execute - run a shell command and capture its output.
3039
3056
3040 %sx command
3057 %sx command
3041
3058
3042 IPython will run the given command using commands.getoutput(), and
3059 IPython will run the given command using commands.getoutput(), and
3043 return the result formatted as a list (split on '\\n'). Since the
3060 return the result formatted as a list (split on '\\n'). Since the
3044 output is _returned_, it will be stored in ipython's regular output
3061 output is _returned_, it will be stored in ipython's regular output
3045 cache Out[N] and in the '_N' automatic variables.
3062 cache Out[N] and in the '_N' automatic variables.
3046
3063
3047 Notes:
3064 Notes:
3048
3065
3049 1) If an input line begins with '!!', then %sx is automatically
3066 1) If an input line begins with '!!', then %sx is automatically
3050 invoked. That is, while:
3067 invoked. That is, while:
3051 !ls
3068 !ls
3052 causes ipython to simply issue system('ls'), typing
3069 causes ipython to simply issue system('ls'), typing
3053 !!ls
3070 !!ls
3054 is a shorthand equivalent to:
3071 is a shorthand equivalent to:
3055 %sx ls
3072 %sx ls
3056
3073
3057 2) %sx differs from %sc in that %sx automatically splits into a list,
3074 2) %sx differs from %sc in that %sx automatically splits into a list,
3058 like '%sc -l'. The reason for this is to make it as easy as possible
3075 like '%sc -l'. The reason for this is to make it as easy as possible
3059 to process line-oriented shell output via further python commands.
3076 to process line-oriented shell output via further python commands.
3060 %sc is meant to provide much finer control, but requires more
3077 %sc is meant to provide much finer control, but requires more
3061 typing.
3078 typing.
3062
3079
3063 3) Just like %sc -l, this is a list with special attributes:
3080 3) Just like %sc -l, this is a list with special attributes:
3064
3081
3065 .l (or .list) : value as list.
3082 .l (or .list) : value as list.
3066 .n (or .nlstr): value as newline-separated string.
3083 .n (or .nlstr): value as newline-separated string.
3067 .s (or .spstr): value as whitespace-separated string.
3084 .s (or .spstr): value as whitespace-separated string.
3068
3085
3069 This is very useful when trying to use such lists as arguments to
3086 This is very useful when trying to use such lists as arguments to
3070 system commands."""
3087 system commands."""
3071
3088
3072 if parameter_s:
3089 if parameter_s:
3073 return self.shell.getoutput(parameter_s)
3090 return self.shell.getoutput(parameter_s)
3074
3091
3075
3092
3076 def magic_bookmark(self, parameter_s=''):
3093 def magic_bookmark(self, parameter_s=''):
3077 """Manage IPython's bookmark system.
3094 """Manage IPython's bookmark system.
3078
3095
3079 %bookmark <name> - set bookmark to current dir
3096 %bookmark <name> - set bookmark to current dir
3080 %bookmark <name> <dir> - set bookmark to <dir>
3097 %bookmark <name> <dir> - set bookmark to <dir>
3081 %bookmark -l - list all bookmarks
3098 %bookmark -l - list all bookmarks
3082 %bookmark -d <name> - remove bookmark
3099 %bookmark -d <name> - remove bookmark
3083 %bookmark -r - remove all bookmarks
3100 %bookmark -r - remove all bookmarks
3084
3101
3085 You can later on access a bookmarked folder with:
3102 You can later on access a bookmarked folder with:
3086 %cd -b <name>
3103 %cd -b <name>
3087 or simply '%cd <name>' if there is no directory called <name> AND
3104 or simply '%cd <name>' if there is no directory called <name> AND
3088 there is such a bookmark defined.
3105 there is such a bookmark defined.
3089
3106
3090 Your bookmarks persist through IPython sessions, but they are
3107 Your bookmarks persist through IPython sessions, but they are
3091 associated with each profile."""
3108 associated with each profile."""
3092
3109
3093 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3110 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3094 if len(args) > 2:
3111 if len(args) > 2:
3095 raise UsageError("%bookmark: too many arguments")
3112 raise UsageError("%bookmark: too many arguments")
3096
3113
3097 bkms = self.db.get('bookmarks',{})
3114 bkms = self.db.get('bookmarks',{})
3098
3115
3099 if opts.has_key('d'):
3116 if opts.has_key('d'):
3100 try:
3117 try:
3101 todel = args[0]
3118 todel = args[0]
3102 except IndexError:
3119 except IndexError:
3103 raise UsageError(
3120 raise UsageError(
3104 "%bookmark -d: must provide a bookmark to delete")
3121 "%bookmark -d: must provide a bookmark to delete")
3105 else:
3122 else:
3106 try:
3123 try:
3107 del bkms[todel]
3124 del bkms[todel]
3108 except KeyError:
3125 except KeyError:
3109 raise UsageError(
3126 raise UsageError(
3110 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3127 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3111
3128
3112 elif opts.has_key('r'):
3129 elif opts.has_key('r'):
3113 bkms = {}
3130 bkms = {}
3114 elif opts.has_key('l'):
3131 elif opts.has_key('l'):
3115 bks = bkms.keys()
3132 bks = bkms.keys()
3116 bks.sort()
3133 bks.sort()
3117 if bks:
3134 if bks:
3118 size = max(map(len,bks))
3135 size = max(map(len,bks))
3119 else:
3136 else:
3120 size = 0
3137 size = 0
3121 fmt = '%-'+str(size)+'s -> %s'
3138 fmt = '%-'+str(size)+'s -> %s'
3122 print 'Current bookmarks:'
3139 print 'Current bookmarks:'
3123 for bk in bks:
3140 for bk in bks:
3124 print fmt % (bk,bkms[bk])
3141 print fmt % (bk,bkms[bk])
3125 else:
3142 else:
3126 if not args:
3143 if not args:
3127 raise UsageError("%bookmark: You must specify the bookmark name")
3144 raise UsageError("%bookmark: You must specify the bookmark name")
3128 elif len(args)==1:
3145 elif len(args)==1:
3129 bkms[args[0]] = os.getcwd()
3146 bkms[args[0]] = os.getcwd()
3130 elif len(args)==2:
3147 elif len(args)==2:
3131 bkms[args[0]] = args[1]
3148 bkms[args[0]] = args[1]
3132 self.db['bookmarks'] = bkms
3149 self.db['bookmarks'] = bkms
3133
3150
3134 def magic_pycat(self, parameter_s=''):
3151 def magic_pycat(self, parameter_s=''):
3135 """Show a syntax-highlighted file through a pager.
3152 """Show a syntax-highlighted file through a pager.
3136
3153
3137 This magic is similar to the cat utility, but it will assume the file
3154 This magic is similar to the cat utility, but it will assume the file
3138 to be Python source and will show it with syntax highlighting. """
3155 to be Python source and will show it with syntax highlighting. """
3139
3156
3140 try:
3157 try:
3141 filename = get_py_filename(parameter_s)
3158 filename = get_py_filename(parameter_s)
3142 cont = file_read(filename)
3159 cont = file_read(filename)
3143 except IOError:
3160 except IOError:
3144 try:
3161 try:
3145 cont = eval(parameter_s,self.user_ns)
3162 cont = eval(parameter_s,self.user_ns)
3146 except NameError:
3163 except NameError:
3147 cont = None
3164 cont = None
3148 if cont is None:
3165 if cont is None:
3149 print "Error: no such file or variable"
3166 print "Error: no such file or variable"
3150 return
3167 return
3151
3168
3152 page.page(self.shell.pycolorize(cont))
3169 page.page(self.shell.pycolorize(cont))
3153
3170
3154 def _rerun_pasted(self):
3171 def _rerun_pasted(self):
3155 """ Rerun a previously pasted command.
3172 """ Rerun a previously pasted command.
3156 """
3173 """
3157 b = self.user_ns.get('pasted_block', None)
3174 b = self.user_ns.get('pasted_block', None)
3158 if b is None:
3175 if b is None:
3159 raise UsageError('No previous pasted block available')
3176 raise UsageError('No previous pasted block available')
3160 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3177 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3161 exec b in self.user_ns
3178 exec b in self.user_ns
3162
3179
3163 def _get_pasted_lines(self, sentinel):
3180 def _get_pasted_lines(self, sentinel):
3164 """ Yield pasted lines until the user enters the given sentinel value.
3181 """ Yield pasted lines until the user enters the given sentinel value.
3165 """
3182 """
3166 from IPython.core import interactiveshell
3183 from IPython.core import interactiveshell
3167 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3184 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3168 while True:
3185 while True:
3169 l = interactiveshell.raw_input_original(':')
3186 l = interactiveshell.raw_input_original(':')
3170 if l == sentinel:
3187 if l == sentinel:
3171 return
3188 return
3172 else:
3189 else:
3173 yield l
3190 yield l
3174
3191
3175 def _strip_pasted_lines_for_code(self, raw_lines):
3192 def _strip_pasted_lines_for_code(self, raw_lines):
3176 """ Strip non-code parts of a sequence of lines to return a block of
3193 """ Strip non-code parts of a sequence of lines to return a block of
3177 code.
3194 code.
3178 """
3195 """
3179 # Regular expressions that declare text we strip from the input:
3196 # Regular expressions that declare text we strip from the input:
3180 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3197 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3181 r'^\s*(\s?>)+', # Python input prompt
3198 r'^\s*(\s?>)+', # Python input prompt
3182 r'^\s*\.{3,}', # Continuation prompts
3199 r'^\s*\.{3,}', # Continuation prompts
3183 r'^\++',
3200 r'^\++',
3184 ]
3201 ]
3185
3202
3186 strip_from_start = map(re.compile,strip_re)
3203 strip_from_start = map(re.compile,strip_re)
3187
3204
3188 lines = []
3205 lines = []
3189 for l in raw_lines:
3206 for l in raw_lines:
3190 for pat in strip_from_start:
3207 for pat in strip_from_start:
3191 l = pat.sub('',l)
3208 l = pat.sub('',l)
3192 lines.append(l)
3209 lines.append(l)
3193
3210
3194 block = "\n".join(lines) + '\n'
3211 block = "\n".join(lines) + '\n'
3195 #print "block:\n",block
3212 #print "block:\n",block
3196 return block
3213 return block
3197
3214
3198 def _execute_block(self, block, par):
3215 def _execute_block(self, block, par):
3199 """ Execute a block, or store it in a variable, per the user's request.
3216 """ Execute a block, or store it in a variable, per the user's request.
3200 """
3217 """
3201 if not par:
3218 if not par:
3202 b = textwrap.dedent(block)
3219 b = textwrap.dedent(block)
3203 self.user_ns['pasted_block'] = b
3220 self.user_ns['pasted_block'] = b
3204 exec b in self.user_ns
3221 exec b in self.user_ns
3205 else:
3222 else:
3206 self.user_ns[par] = SList(block.splitlines())
3223 self.user_ns[par] = SList(block.splitlines())
3207 print "Block assigned to '%s'" % par
3224 print "Block assigned to '%s'" % par
3208
3225
3209 def magic_quickref(self,arg):
3226 def magic_quickref(self,arg):
3210 """ Show a quick reference sheet """
3227 """ Show a quick reference sheet """
3211 import IPython.core.usage
3228 import IPython.core.usage
3212 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3229 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3213
3230
3214 page.page(qr)
3231 page.page(qr)
3215
3232
3216 def magic_doctest_mode(self,parameter_s=''):
3233 def magic_doctest_mode(self,parameter_s=''):
3217 """Toggle doctest mode on and off.
3234 """Toggle doctest mode on and off.
3218
3235
3219 This mode is intended to make IPython behave as much as possible like a
3236 This mode is intended to make IPython behave as much as possible like a
3220 plain Python shell, from the perspective of how its prompts, exceptions
3237 plain Python shell, from the perspective of how its prompts, exceptions
3221 and output look. This makes it easy to copy and paste parts of a
3238 and output look. This makes it easy to copy and paste parts of a
3222 session into doctests. It does so by:
3239 session into doctests. It does so by:
3223
3240
3224 - Changing the prompts to the classic ``>>>`` ones.
3241 - Changing the prompts to the classic ``>>>`` ones.
3225 - Changing the exception reporting mode to 'Plain'.
3242 - Changing the exception reporting mode to 'Plain'.
3226 - Disabling pretty-printing of output.
3243 - Disabling pretty-printing of output.
3227
3244
3228 Note that IPython also supports the pasting of code snippets that have
3245 Note that IPython also supports the pasting of code snippets that have
3229 leading '>>>' and '...' prompts in them. This means that you can paste
3246 leading '>>>' and '...' prompts in them. This means that you can paste
3230 doctests from files or docstrings (even if they have leading
3247 doctests from files or docstrings (even if they have leading
3231 whitespace), and the code will execute correctly. You can then use
3248 whitespace), and the code will execute correctly. You can then use
3232 '%history -t' to see the translated history; this will give you the
3249 '%history -t' to see the translated history; this will give you the
3233 input after removal of all the leading prompts and whitespace, which
3250 input after removal of all the leading prompts and whitespace, which
3234 can be pasted back into an editor.
3251 can be pasted back into an editor.
3235
3252
3236 With these features, you can switch into this mode easily whenever you
3253 With these features, you can switch into this mode easily whenever you
3237 need to do testing and changes to doctests, without having to leave
3254 need to do testing and changes to doctests, without having to leave
3238 your existing IPython session.
3255 your existing IPython session.
3239 """
3256 """
3240
3257
3241 from IPython.utils.ipstruct import Struct
3258 from IPython.utils.ipstruct import Struct
3242
3259
3243 # Shorthands
3260 # Shorthands
3244 shell = self.shell
3261 shell = self.shell
3245 oc = shell.displayhook
3262 oc = shell.displayhook
3246 meta = shell.meta
3263 meta = shell.meta
3247 disp_formatter = self.shell.display_formatter
3264 disp_formatter = self.shell.display_formatter
3248 ptformatter = disp_formatter.formatters['text/plain']
3265 ptformatter = disp_formatter.formatters['text/plain']
3249 # dstore is a data store kept in the instance metadata bag to track any
3266 # dstore is a data store kept in the instance metadata bag to track any
3250 # changes we make, so we can undo them later.
3267 # changes we make, so we can undo them later.
3251 dstore = meta.setdefault('doctest_mode',Struct())
3268 dstore = meta.setdefault('doctest_mode',Struct())
3252 save_dstore = dstore.setdefault
3269 save_dstore = dstore.setdefault
3253
3270
3254 # save a few values we'll need to recover later
3271 # save a few values we'll need to recover later
3255 mode = save_dstore('mode',False)
3272 mode = save_dstore('mode',False)
3256 save_dstore('rc_pprint',ptformatter.pprint)
3273 save_dstore('rc_pprint',ptformatter.pprint)
3257 save_dstore('xmode',shell.InteractiveTB.mode)
3274 save_dstore('xmode',shell.InteractiveTB.mode)
3258 save_dstore('rc_separate_out',shell.separate_out)
3275 save_dstore('rc_separate_out',shell.separate_out)
3259 save_dstore('rc_separate_out2',shell.separate_out2)
3276 save_dstore('rc_separate_out2',shell.separate_out2)
3260 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3277 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3261 save_dstore('rc_separate_in',shell.separate_in)
3278 save_dstore('rc_separate_in',shell.separate_in)
3262 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3279 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3263
3280
3264 if mode == False:
3281 if mode == False:
3265 # turn on
3282 # turn on
3266 oc.prompt1.p_template = '>>> '
3283 oc.prompt1.p_template = '>>> '
3267 oc.prompt2.p_template = '... '
3284 oc.prompt2.p_template = '... '
3268 oc.prompt_out.p_template = ''
3285 oc.prompt_out.p_template = ''
3269
3286
3270 # Prompt separators like plain python
3287 # Prompt separators like plain python
3271 oc.input_sep = oc.prompt1.sep = ''
3288 oc.input_sep = oc.prompt1.sep = ''
3272 oc.output_sep = ''
3289 oc.output_sep = ''
3273 oc.output_sep2 = ''
3290 oc.output_sep2 = ''
3274
3291
3275 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3292 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3276 oc.prompt_out.pad_left = False
3293 oc.prompt_out.pad_left = False
3277
3294
3278 ptformatter.pprint = False
3295 ptformatter.pprint = False
3279 disp_formatter.plain_text_only = True
3296 disp_formatter.plain_text_only = True
3280
3297
3281 shell.magic_xmode('Plain')
3298 shell.magic_xmode('Plain')
3282 else:
3299 else:
3283 # turn off
3300 # turn off
3284 oc.prompt1.p_template = shell.prompt_in1
3301 oc.prompt1.p_template = shell.prompt_in1
3285 oc.prompt2.p_template = shell.prompt_in2
3302 oc.prompt2.p_template = shell.prompt_in2
3286 oc.prompt_out.p_template = shell.prompt_out
3303 oc.prompt_out.p_template = shell.prompt_out
3287
3304
3288 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3305 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3289
3306
3290 oc.output_sep = dstore.rc_separate_out
3307 oc.output_sep = dstore.rc_separate_out
3291 oc.output_sep2 = dstore.rc_separate_out2
3308 oc.output_sep2 = dstore.rc_separate_out2
3292
3309
3293 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3310 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3294 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3311 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3295
3312
3296 ptformatter.pprint = dstore.rc_pprint
3313 ptformatter.pprint = dstore.rc_pprint
3297 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3314 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3298
3315
3299 shell.magic_xmode(dstore.xmode)
3316 shell.magic_xmode(dstore.xmode)
3300
3317
3301 # Store new mode and inform
3318 # Store new mode and inform
3302 dstore.mode = bool(1-int(mode))
3319 dstore.mode = bool(1-int(mode))
3303 mode_label = ['OFF','ON'][dstore.mode]
3320 mode_label = ['OFF','ON'][dstore.mode]
3304 print 'Doctest mode is:', mode_label
3321 print 'Doctest mode is:', mode_label
3305
3322
3306 def magic_gui(self, parameter_s=''):
3323 def magic_gui(self, parameter_s=''):
3307 """Enable or disable IPython GUI event loop integration.
3324 """Enable or disable IPython GUI event loop integration.
3308
3325
3309 %gui [GUINAME]
3326 %gui [GUINAME]
3310
3327
3311 This magic replaces IPython's threaded shells that were activated
3328 This magic replaces IPython's threaded shells that were activated
3312 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3329 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3313 can now be enabled, disabled and changed at runtime and keyboard
3330 can now be enabled, disabled and changed at runtime and keyboard
3314 interrupts should work without any problems. The following toolkits
3331 interrupts should work without any problems. The following toolkits
3315 are supported: wxPython, PyQt4, PyGTK, and Tk::
3332 are supported: wxPython, PyQt4, PyGTK, and Tk::
3316
3333
3317 %gui wx # enable wxPython event loop integration
3334 %gui wx # enable wxPython event loop integration
3318 %gui qt4|qt # enable PyQt4 event loop integration
3335 %gui qt4|qt # enable PyQt4 event loop integration
3319 %gui gtk # enable PyGTK event loop integration
3336 %gui gtk # enable PyGTK event loop integration
3320 %gui tk # enable Tk event loop integration
3337 %gui tk # enable Tk event loop integration
3321 %gui # disable all event loop integration
3338 %gui # disable all event loop integration
3322
3339
3323 WARNING: after any of these has been called you can simply create
3340 WARNING: after any of these has been called you can simply create
3324 an application object, but DO NOT start the event loop yourself, as
3341 an application object, but DO NOT start the event loop yourself, as
3325 we have already handled that.
3342 we have already handled that.
3326 """
3343 """
3327 from IPython.lib.inputhook import enable_gui
3344 from IPython.lib.inputhook import enable_gui
3328 opts, arg = self.parse_options(parameter_s, '')
3345 opts, arg = self.parse_options(parameter_s, '')
3329 if arg=='': arg = None
3346 if arg=='': arg = None
3330 return enable_gui(arg)
3347 return enable_gui(arg)
3331
3348
3332 def magic_load_ext(self, module_str):
3349 def magic_load_ext(self, module_str):
3333 """Load an IPython extension by its module name."""
3350 """Load an IPython extension by its module name."""
3334 return self.extension_manager.load_extension(module_str)
3351 return self.extension_manager.load_extension(module_str)
3335
3352
3336 def magic_unload_ext(self, module_str):
3353 def magic_unload_ext(self, module_str):
3337 """Unload an IPython extension by its module name."""
3354 """Unload an IPython extension by its module name."""
3338 self.extension_manager.unload_extension(module_str)
3355 self.extension_manager.unload_extension(module_str)
3339
3356
3340 def magic_reload_ext(self, module_str):
3357 def magic_reload_ext(self, module_str):
3341 """Reload an IPython extension by its module name."""
3358 """Reload an IPython extension by its module name."""
3342 self.extension_manager.reload_extension(module_str)
3359 self.extension_manager.reload_extension(module_str)
3343
3360
3344 @skip_doctest
3361 @skip_doctest
3345 def magic_install_profiles(self, s):
3362 def magic_install_profiles(self, s):
3346 """Install the default IPython profiles into the .ipython dir.
3363 """Install the default IPython profiles into the .ipython dir.
3347
3364
3348 If the default profiles have already been installed, they will not
3365 If the default profiles have already been installed, they will not
3349 be overwritten. You can force overwriting them by using the ``-o``
3366 be overwritten. You can force overwriting them by using the ``-o``
3350 option::
3367 option::
3351
3368
3352 In [1]: %install_profiles -o
3369 In [1]: %install_profiles -o
3353 """
3370 """
3354 if '-o' in s:
3371 if '-o' in s:
3355 overwrite = True
3372 overwrite = True
3356 else:
3373 else:
3357 overwrite = False
3374 overwrite = False
3358 from IPython.config import profile
3375 from IPython.config import profile
3359 profile_dir = os.path.split(profile.__file__)[0]
3376 profile_dir = os.path.split(profile.__file__)[0]
3360 ipython_dir = self.ipython_dir
3377 ipython_dir = self.ipython_dir
3361 files = os.listdir(profile_dir)
3378 files = os.listdir(profile_dir)
3362
3379
3363 to_install = []
3380 to_install = []
3364 for f in files:
3381 for f in files:
3365 if f.startswith('ipython_config'):
3382 if f.startswith('ipython_config'):
3366 src = os.path.join(profile_dir, f)
3383 src = os.path.join(profile_dir, f)
3367 dst = os.path.join(ipython_dir, f)
3384 dst = os.path.join(ipython_dir, f)
3368 if (not os.path.isfile(dst)) or overwrite:
3385 if (not os.path.isfile(dst)) or overwrite:
3369 to_install.append((f, src, dst))
3386 to_install.append((f, src, dst))
3370 if len(to_install)>0:
3387 if len(to_install)>0:
3371 print "Installing profiles to: ", ipython_dir
3388 print "Installing profiles to: ", ipython_dir
3372 for (f, src, dst) in to_install:
3389 for (f, src, dst) in to_install:
3373 shutil.copy(src, dst)
3390 shutil.copy(src, dst)
3374 print " %s" % f
3391 print " %s" % f
3375
3392
3376 @skip_doctest
3393 @skip_doctest
3377 def magic_install_default_config(self, s):
3394 def magic_install_default_config(self, s):
3378 """Install IPython's default config file into the .ipython dir.
3395 """Install IPython's default config file into the .ipython dir.
3379
3396
3380 If the default config file (:file:`ipython_config.py`) is already
3397 If the default config file (:file:`ipython_config.py`) is already
3381 installed, it will not be overwritten. You can force overwriting
3398 installed, it will not be overwritten. You can force overwriting
3382 by using the ``-o`` option::
3399 by using the ``-o`` option::
3383
3400
3384 In [1]: %install_default_config
3401 In [1]: %install_default_config
3385 """
3402 """
3386 if '-o' in s:
3403 if '-o' in s:
3387 overwrite = True
3404 overwrite = True
3388 else:
3405 else:
3389 overwrite = False
3406 overwrite = False
3390 from IPython.config import default
3407 from IPython.config import default
3391 config_dir = os.path.split(default.__file__)[0]
3408 config_dir = os.path.split(default.__file__)[0]
3392 ipython_dir = self.ipython_dir
3409 ipython_dir = self.ipython_dir
3393 default_config_file_name = 'ipython_config.py'
3410 default_config_file_name = 'ipython_config.py'
3394 src = os.path.join(config_dir, default_config_file_name)
3411 src = os.path.join(config_dir, default_config_file_name)
3395 dst = os.path.join(ipython_dir, default_config_file_name)
3412 dst = os.path.join(ipython_dir, default_config_file_name)
3396 if (not os.path.isfile(dst)) or overwrite:
3413 if (not os.path.isfile(dst)) or overwrite:
3397 shutil.copy(src, dst)
3414 shutil.copy(src, dst)
3398 print "Installing default config file: %s" % dst
3415 print "Installing default config file: %s" % dst
3399
3416
3400 # Pylab support: simple wrappers that activate pylab, load gui input
3417 # Pylab support: simple wrappers that activate pylab, load gui input
3401 # handling and modify slightly %run
3418 # handling and modify slightly %run
3402
3419
3403 @skip_doctest
3420 @skip_doctest
3404 def _pylab_magic_run(self, parameter_s=''):
3421 def _pylab_magic_run(self, parameter_s=''):
3405 Magic.magic_run(self, parameter_s,
3422 Magic.magic_run(self, parameter_s,
3406 runner=mpl_runner(self.shell.safe_execfile))
3423 runner=mpl_runner(self.shell.safe_execfile))
3407
3424
3408 _pylab_magic_run.__doc__ = magic_run.__doc__
3425 _pylab_magic_run.__doc__ = magic_run.__doc__
3409
3426
3410 @skip_doctest
3427 @skip_doctest
3411 def magic_pylab(self, s):
3428 def magic_pylab(self, s):
3412 """Load numpy and matplotlib to work interactively.
3429 """Load numpy and matplotlib to work interactively.
3413
3430
3414 %pylab [GUINAME]
3431 %pylab [GUINAME]
3415
3432
3416 This function lets you activate pylab (matplotlib, numpy and
3433 This function lets you activate pylab (matplotlib, numpy and
3417 interactive support) at any point during an IPython session.
3434 interactive support) at any point during an IPython session.
3418
3435
3419 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3436 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3420 pylab and mlab, as well as all names from numpy and pylab.
3437 pylab and mlab, as well as all names from numpy and pylab.
3421
3438
3422 Parameters
3439 Parameters
3423 ----------
3440 ----------
3424 guiname : optional
3441 guiname : optional
3425 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3442 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3426 'tk'). If given, the corresponding Matplotlib backend is used,
3443 'tk'). If given, the corresponding Matplotlib backend is used,
3427 otherwise matplotlib's default (which you can override in your
3444 otherwise matplotlib's default (which you can override in your
3428 matplotlib config file) is used.
3445 matplotlib config file) is used.
3429
3446
3430 Examples
3447 Examples
3431 --------
3448 --------
3432 In this case, where the MPL default is TkAgg:
3449 In this case, where the MPL default is TkAgg:
3433 In [2]: %pylab
3450 In [2]: %pylab
3434
3451
3435 Welcome to pylab, a matplotlib-based Python environment.
3452 Welcome to pylab, a matplotlib-based Python environment.
3436 Backend in use: TkAgg
3453 Backend in use: TkAgg
3437 For more information, type 'help(pylab)'.
3454 For more information, type 'help(pylab)'.
3438
3455
3439 But you can explicitly request a different backend:
3456 But you can explicitly request a different backend:
3440 In [3]: %pylab qt
3457 In [3]: %pylab qt
3441
3458
3442 Welcome to pylab, a matplotlib-based Python environment.
3459 Welcome to pylab, a matplotlib-based Python environment.
3443 Backend in use: Qt4Agg
3460 Backend in use: Qt4Agg
3444 For more information, type 'help(pylab)'.
3461 For more information, type 'help(pylab)'.
3445 """
3462 """
3446 self.shell.enable_pylab(s)
3463 self.shell.enable_pylab(s)
3447
3464
3448 def magic_tb(self, s):
3465 def magic_tb(self, s):
3449 """Print the last traceback with the currently active exception mode.
3466 """Print the last traceback with the currently active exception mode.
3450
3467
3451 See %xmode for changing exception reporting modes."""
3468 See %xmode for changing exception reporting modes."""
3452 self.shell.showtraceback()
3469 self.shell.showtraceback()
3453
3470
3454 @skip_doctest
3471 @skip_doctest
3455 def magic_precision(self, s=''):
3472 def magic_precision(self, s=''):
3456 """Set floating point precision for pretty printing.
3473 """Set floating point precision for pretty printing.
3457
3474
3458 Can set either integer precision or a format string.
3475 Can set either integer precision or a format string.
3459
3476
3460 If numpy has been imported and precision is an int,
3477 If numpy has been imported and precision is an int,
3461 numpy display precision will also be set, via ``numpy.set_printoptions``.
3478 numpy display precision will also be set, via ``numpy.set_printoptions``.
3462
3479
3463 If no argument is given, defaults will be restored.
3480 If no argument is given, defaults will be restored.
3464
3481
3465 Examples
3482 Examples
3466 --------
3483 --------
3467 ::
3484 ::
3468
3485
3469 In [1]: from math import pi
3486 In [1]: from math import pi
3470
3487
3471 In [2]: %precision 3
3488 In [2]: %precision 3
3472 Out[2]: '%.3f'
3489 Out[2]: '%.3f'
3473
3490
3474 In [3]: pi
3491 In [3]: pi
3475 Out[3]: 3.142
3492 Out[3]: 3.142
3476
3493
3477 In [4]: %precision %i
3494 In [4]: %precision %i
3478 Out[4]: '%i'
3495 Out[4]: '%i'
3479
3496
3480 In [5]: pi
3497 In [5]: pi
3481 Out[5]: 3
3498 Out[5]: 3
3482
3499
3483 In [6]: %precision %e
3500 In [6]: %precision %e
3484 Out[6]: '%e'
3501 Out[6]: '%e'
3485
3502
3486 In [7]: pi**10
3503 In [7]: pi**10
3487 Out[7]: 9.364805e+04
3504 Out[7]: 9.364805e+04
3488
3505
3489 In [8]: %precision
3506 In [8]: %precision
3490 Out[8]: '%r'
3507 Out[8]: '%r'
3491
3508
3492 In [9]: pi**10
3509 In [9]: pi**10
3493 Out[9]: 93648.047476082982
3510 Out[9]: 93648.047476082982
3494
3511
3495 """
3512 """
3496
3513
3497 ptformatter = self.shell.display_formatter.formatters['text/plain']
3514 ptformatter = self.shell.display_formatter.formatters['text/plain']
3498 ptformatter.float_precision = s
3515 ptformatter.float_precision = s
3499 return ptformatter.float_format
3516 return ptformatter.float_format
3500
3517
3501 # end Magic
3518 # end Magic
@@ -1,440 +1,462 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions begin
24 # Test functions begin
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_rehashx():
26 def test_rehashx():
27 # clear up everything
27 # clear up everything
28 _ip = get_ipython()
28 _ip = get_ipython()
29 _ip.alias_manager.alias_table.clear()
29 _ip.alias_manager.alias_table.clear()
30 del _ip.db['syscmdlist']
30 del _ip.db['syscmdlist']
31
31
32 _ip.magic('rehashx')
32 _ip.magic('rehashx')
33 # Practically ALL ipython development systems will have more than 10 aliases
33 # Practically ALL ipython development systems will have more than 10 aliases
34
34
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 for key, val in _ip.alias_manager.alias_table.iteritems():
36 for key, val in _ip.alias_manager.alias_table.iteritems():
37 # we must strip dots from alias names
37 # we must strip dots from alias names
38 nt.assert_true('.' not in key)
38 nt.assert_true('.' not in key)
39
39
40 # rehashx must fill up syscmdlist
40 # rehashx must fill up syscmdlist
41 scoms = _ip.db['syscmdlist']
41 scoms = _ip.db['syscmdlist']
42 yield (nt.assert_true, len(scoms) > 10)
42 yield (nt.assert_true, len(scoms) > 10)
43
43
44
44
45 def test_magic_parse_options():
45 def test_magic_parse_options():
46 """Test that we don't mangle paths when parsing magic options."""
46 """Test that we don't mangle paths when parsing magic options."""
47 ip = get_ipython()
47 ip = get_ipython()
48 path = 'c:\\x'
48 path = 'c:\\x'
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 # argv splitting is os-dependent
50 # argv splitting is os-dependent
51 if os.name == 'posix':
51 if os.name == 'posix':
52 expected = 'c:x'
52 expected = 'c:x'
53 else:
53 else:
54 expected = path
54 expected = path
55 nt.assert_equals(opts['f'], expected)
55 nt.assert_equals(opts['f'], expected)
56
56
57
57
58 def doctest_hist_f():
58 def doctest_hist_f():
59 """Test %hist -f with temporary filename.
59 """Test %hist -f with temporary filename.
60
60
61 In [9]: import tempfile
61 In [9]: import tempfile
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -nl -f $tfile 3
65 In [11]: %hist -nl -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
69
69
70
70
71 def doctest_hist_r():
71 def doctest_hist_r():
72 """Test %hist -r
72 """Test %hist -r
73
73
74 XXX - This test is not recording the output correctly. For some reason, in
74 XXX - This test is not recording the output correctly. For some reason, in
75 testing mode the raw history isn't getting populated. No idea why.
75 testing mode the raw history isn't getting populated. No idea why.
76 Disabling the output checking for now, though at least we do run it.
76 Disabling the output checking for now, though at least we do run it.
77
77
78 In [1]: 'hist' in _ip.lsmagic()
78 In [1]: 'hist' in _ip.lsmagic()
79 Out[1]: True
79 Out[1]: True
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -rl 2
83 In [3]: %hist -rl 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
87
87
88 def doctest_hist_op():
88 def doctest_hist_op():
89 """Test %hist -op
89 """Test %hist -op
90
90
91 In [1]: class b:
91 In [1]: class b:
92 ...: pass
92 ...: pass
93 ...:
93 ...:
94
94
95 In [2]: class s(b):
95 In [2]: class s(b):
96 ...: def __str__(self):
96 ...: def __str__(self):
97 ...: return 's'
97 ...: return 's'
98 ...:
98 ...:
99
99
100 In [3]:
100 In [3]:
101
101
102 In [4]: class r(b):
102 In [4]: class r(b):
103 ...: def __repr__(self):
103 ...: def __repr__(self):
104 ...: return 'r'
104 ...: return 'r'
105 ...:
105 ...:
106
106
107 In [5]: class sr(s,r): pass
107 In [5]: class sr(s,r): pass
108 ...:
108 ...:
109
109
110 In [6]:
110 In [6]:
111
111
112 In [7]: bb=b()
112 In [7]: bb=b()
113
113
114 In [8]: ss=s()
114 In [8]: ss=s()
115
115
116 In [9]: rr=r()
116 In [9]: rr=r()
117
117
118 In [10]: ssrr=sr()
118 In [10]: ssrr=sr()
119
119
120 In [11]: bb
120 In [11]: bb
121 Out[11]: <...b instance at ...>
121 Out[11]: <...b instance at ...>
122
122
123 In [12]: ss
123 In [12]: ss
124 Out[12]: <...s instance at ...>
124 Out[12]: <...s instance at ...>
125
125
126 In [13]:
126 In [13]:
127
127
128 In [14]: %hist -op
128 In [14]: %hist -op
129 >>> class b:
129 >>> class b:
130 ... pass
130 ... pass
131 ...
131 ...
132 >>> class s(b):
132 >>> class s(b):
133 ... def __str__(self):
133 ... def __str__(self):
134 ... return 's'
134 ... return 's'
135 ...
135 ...
136 >>>
136 >>>
137 >>> class r(b):
137 >>> class r(b):
138 ... def __repr__(self):
138 ... def __repr__(self):
139 ... return 'r'
139 ... return 'r'
140 ...
140 ...
141 >>> class sr(s,r): pass
141 >>> class sr(s,r): pass
142 >>>
142 >>>
143 >>> bb=b()
143 >>> bb=b()
144 >>> ss=s()
144 >>> ss=s()
145 >>> rr=r()
145 >>> rr=r()
146 >>> ssrr=sr()
146 >>> ssrr=sr()
147 >>> bb
147 >>> bb
148 <...b instance at ...>
148 <...b instance at ...>
149 >>> ss
149 >>> ss
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_macro():
154 def test_macro():
155 ip = get_ipython()
155 ip = get_ipython()
156 ip.history_manager.reset() # Clear any existing history.
156 ip.history_manager.reset() # Clear any existing history.
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
158 for i, cmd in enumerate(cmds, start=1):
158 for i, cmd in enumerate(cmds, start=1):
159 ip.history_manager.store_inputs(i, cmd)
159 ip.history_manager.store_inputs(i, cmd)
160 ip.magic("macro test 1-3")
160 ip.magic("macro test 1-3")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162
162
163 # List macros.
163 # List macros.
164 assert "test" in ip.magic("macro")
164 assert "test" in ip.magic("macro")
165
165
166 def test_macro_run():
166 def test_macro_run():
167 """Test that we can run a multi-line macro successfully."""
167 """Test that we can run a multi-line macro successfully."""
168 ip = get_ipython()
168 ip = get_ipython()
169 ip.history_manager.reset()
169 ip.history_manager.reset()
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
171 for cmd in cmds:
171 for cmd in cmds:
172 ip.run_cell(cmd)
172 ip.run_cell(cmd)
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
174 original_stdout = sys.stdout
174 original_stdout = sys.stdout
175 new_stdout = StringIO()
175 new_stdout = StringIO()
176 sys.stdout = new_stdout
176 sys.stdout = new_stdout
177 try:
177 try:
178 ip.run_cell("test")
178 ip.run_cell("test")
179 nt.assert_true("12" in new_stdout.getvalue())
179 nt.assert_true("12" in new_stdout.getvalue())
180 ip.run_cell("test")
180 ip.run_cell("test")
181 nt.assert_true("13" in new_stdout.getvalue())
181 nt.assert_true("13" in new_stdout.getvalue())
182 finally:
182 finally:
183 sys.stdout = original_stdout
183 sys.stdout = original_stdout
184 new_stdout.close()
184 new_stdout.close()
185
185
186
186
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
188 # fix this and revert the skip to happen only if numpy is not around.
188 # fix this and revert the skip to happen only if numpy is not around.
189 #@dec.skipif_not_numpy
189 #@dec.skipif_not_numpy
190 @dec.skip_known_failure
190 @dec.skip_known_failure
191 def test_numpy_clear_array_undec():
191 def test_numpy_clear_array_undec():
192 from IPython.extensions import clearcmd
192 from IPython.extensions import clearcmd
193
193
194 _ip.ex('import numpy as np')
194 _ip.ex('import numpy as np')
195 _ip.ex('a = np.empty(2)')
195 _ip.ex('a = np.empty(2)')
196 yield (nt.assert_true, 'a' in _ip.user_ns)
196 yield (nt.assert_true, 'a' in _ip.user_ns)
197 _ip.magic('clear array')
197 _ip.magic('clear array')
198 yield (nt.assert_false, 'a' in _ip.user_ns)
198 yield (nt.assert_false, 'a' in _ip.user_ns)
199
199
200
200
201 # Multiple tests for clipboard pasting
201 # Multiple tests for clipboard pasting
202 @dec.parametric
202 @dec.parametric
203 def test_paste():
203 def test_paste():
204 _ip = get_ipython()
204 _ip = get_ipython()
205 def paste(txt, flags='-q'):
205 def paste(txt, flags='-q'):
206 """Paste input text, by default in quiet mode"""
206 """Paste input text, by default in quiet mode"""
207 hooks.clipboard_get = lambda : txt
207 hooks.clipboard_get = lambda : txt
208 _ip.magic('paste '+flags)
208 _ip.magic('paste '+flags)
209
209
210 # Inject fake clipboard hook but save original so we can restore it later
210 # Inject fake clipboard hook but save original so we can restore it later
211 hooks = _ip.hooks
211 hooks = _ip.hooks
212 user_ns = _ip.user_ns
212 user_ns = _ip.user_ns
213 original_clip = hooks.clipboard_get
213 original_clip = hooks.clipboard_get
214
214
215 try:
215 try:
216 # This try/except with an emtpy except clause is here only because
216 # This try/except with an emtpy except clause is here only because
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
218 # removed when we drop 2.4-compatibility, and the emtpy except below
218 # removed when we drop 2.4-compatibility, and the emtpy except below
219 # will be changed to a finally.
219 # will be changed to a finally.
220
220
221 # Run tests with fake clipboard function
221 # Run tests with fake clipboard function
222 user_ns.pop('x', None)
222 user_ns.pop('x', None)
223 paste('x=1')
223 paste('x=1')
224 yield nt.assert_equal(user_ns['x'], 1)
224 yield nt.assert_equal(user_ns['x'], 1)
225
225
226 user_ns.pop('x', None)
226 user_ns.pop('x', None)
227 paste('>>> x=2')
227 paste('>>> x=2')
228 yield nt.assert_equal(user_ns['x'], 2)
228 yield nt.assert_equal(user_ns['x'], 2)
229
229
230 paste("""
230 paste("""
231 >>> x = [1,2,3]
231 >>> x = [1,2,3]
232 >>> y = []
232 >>> y = []
233 >>> for i in x:
233 >>> for i in x:
234 ... y.append(i**2)
234 ... y.append(i**2)
235 ...
235 ...
236 """)
236 """)
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
239
239
240 # Now, test that paste -r works
240 # Now, test that paste -r works
241 user_ns.pop('x', None)
241 user_ns.pop('x', None)
242 yield nt.assert_false('x' in user_ns)
242 yield nt.assert_false('x' in user_ns)
243 _ip.magic('paste -r')
243 _ip.magic('paste -r')
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
245
245
246 # Also test paste echoing, by temporarily faking the writer
246 # Also test paste echoing, by temporarily faking the writer
247 w = StringIO()
247 w = StringIO()
248 writer = _ip.write
248 writer = _ip.write
249 _ip.write = w.write
249 _ip.write = w.write
250 code = """
250 code = """
251 a = 100
251 a = 100
252 b = 200"""
252 b = 200"""
253 try:
253 try:
254 paste(code,'')
254 paste(code,'')
255 out = w.getvalue()
255 out = w.getvalue()
256 finally:
256 finally:
257 _ip.write = writer
257 _ip.write = writer
258 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['a'], 100)
259 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(user_ns['b'], 200)
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
261
261
262 finally:
262 finally:
263 # This should be in a finally clause, instead of the bare except above.
263 # This should be in a finally clause, instead of the bare except above.
264 # Restore original hook
264 # Restore original hook
265 hooks.clipboard_get = original_clip
265 hooks.clipboard_get = original_clip
266
266
267
267
268 def test_time():
268 def test_time():
269 _ip.magic('time None')
269 _ip.magic('time None')
270
270
271
271
272 def doctest_time():
272 def doctest_time():
273 """
273 """
274 In [10]: %time None
274 In [10]: %time None
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
276 Wall time: 0.00 s
276 Wall time: 0.00 s
277
277
278 In [11]: def f(kmjy):
278 In [11]: def f(kmjy):
279 ....: %time print 2*kmjy
279 ....: %time print 2*kmjy
280
280
281 In [12]: f(3)
281 In [12]: f(3)
282 6
282 6
283 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
284 Wall time: 0.00 s
284 Wall time: 0.00 s
285 """
285 """
286
286
287
287
288 def test_doctest_mode():
288 def test_doctest_mode():
289 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 "Toggle doctest_mode twice, it should be a no-op and run without error"
290 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
291 _ip.magic('doctest_mode')
291 _ip.magic('doctest_mode')
292
292
293
293
294 def test_parse_options():
294 def test_parse_options():
295 """Tests for basic options parsing in magics."""
295 """Tests for basic options parsing in magics."""
296 # These are only the most minimal of tests, more should be added later. At
296 # These are only the most minimal of tests, more should be added later. At
297 # the very least we check that basic text/unicode calls work OK.
297 # the very least we check that basic text/unicode calls work OK.
298 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
298 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
299 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
299 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
300
300
301
301
302 def test_dirops():
302 def test_dirops():
303 """Test various directory handling operations."""
303 """Test various directory handling operations."""
304 curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
305
305
306 startdir = os.getcwdu()
306 startdir = os.getcwdu()
307 ipdir = _ip.ipython_dir
307 ipdir = _ip.ipython_dir
308 try:
308 try:
309 _ip.magic('cd "%s"' % ipdir)
309 _ip.magic('cd "%s"' % ipdir)
310 nt.assert_equal(curpath(), ipdir)
310 nt.assert_equal(curpath(), ipdir)
311 _ip.magic('cd -')
311 _ip.magic('cd -')
312 nt.assert_equal(curpath(), startdir)
312 nt.assert_equal(curpath(), startdir)
313 _ip.magic('pushd "%s"' % ipdir)
313 _ip.magic('pushd "%s"' % ipdir)
314 nt.assert_equal(curpath(), ipdir)
314 nt.assert_equal(curpath(), ipdir)
315 _ip.magic('popd')
315 _ip.magic('popd')
316 nt.assert_equal(curpath(), startdir)
316 nt.assert_equal(curpath(), startdir)
317 finally:
317 finally:
318 os.chdir(startdir)
318 os.chdir(startdir)
319
319
320
320
321 def check_cpaste(code, should_fail=False):
321 def check_cpaste(code, should_fail=False):
322 """Execute code via 'cpaste' and ensure it was executed, unless
322 """Execute code via 'cpaste' and ensure it was executed, unless
323 should_fail is set.
323 should_fail is set.
324 """
324 """
325 _ip.user_ns['code_ran'] = False
325 _ip.user_ns['code_ran'] = False
326
326
327 src = StringIO()
327 src = StringIO()
328 src.write('\n')
328 src.write('\n')
329 src.write(code)
329 src.write(code)
330 src.write('\n--\n')
330 src.write('\n--\n')
331 src.seek(0)
331 src.seek(0)
332
332
333 stdin_save = sys.stdin
333 stdin_save = sys.stdin
334 sys.stdin = src
334 sys.stdin = src
335
335
336 try:
336 try:
337 _ip.magic('cpaste')
337 _ip.magic('cpaste')
338 except:
338 except:
339 if not should_fail:
339 if not should_fail:
340 raise AssertionError("Failure not expected : '%s'" %
340 raise AssertionError("Failure not expected : '%s'" %
341 code)
341 code)
342 else:
342 else:
343 assert _ip.user_ns['code_ran']
343 assert _ip.user_ns['code_ran']
344 if should_fail:
344 if should_fail:
345 raise AssertionError("Failure expected : '%s'" % code)
345 raise AssertionError("Failure expected : '%s'" % code)
346 finally:
346 finally:
347 sys.stdin = stdin_save
347 sys.stdin = stdin_save
348
348
349
349
350 def test_cpaste():
350 def test_cpaste():
351 """Test cpaste magic"""
351 """Test cpaste magic"""
352
352
353 def run():
353 def run():
354 """Marker function: sets a flag when executed.
354 """Marker function: sets a flag when executed.
355 """
355 """
356 _ip.user_ns['code_ran'] = True
356 _ip.user_ns['code_ran'] = True
357 return 'run' # return string so '+ run()' doesn't result in success
357 return 'run' # return string so '+ run()' doesn't result in success
358
358
359 tests = {'pass': ["> > > run()",
359 tests = {'pass': ["> > > run()",
360 ">>> > run()",
360 ">>> > run()",
361 "+++ run()",
361 "+++ run()",
362 "++ run()",
362 "++ run()",
363 " >>> run()"],
363 " >>> run()"],
364
364
365 'fail': ["+ + run()",
365 'fail': ["+ + run()",
366 " ++ run()"]}
366 " ++ run()"]}
367
367
368 _ip.user_ns['run'] = run
368 _ip.user_ns['run'] = run
369
369
370 for code in tests['pass']:
370 for code in tests['pass']:
371 check_cpaste(code)
371 check_cpaste(code)
372
372
373 for code in tests['fail']:
373 for code in tests['fail']:
374 check_cpaste(code, should_fail=True)
374 check_cpaste(code, should_fail=True)
375
375
376 def test_xmode():
376 def test_xmode():
377 # Calling xmode three times should be a no-op
377 # Calling xmode three times should be a no-op
378 xmode = _ip.InteractiveTB.mode
378 xmode = _ip.InteractiveTB.mode
379 for i in range(3):
379 for i in range(3):
380 _ip.magic("xmode")
380 _ip.magic("xmode")
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
382
382
383 def test_reset_hard():
383 def test_reset_hard():
384 monitor = []
384 monitor = []
385 class A(object):
385 class A(object):
386 def __del__(self):
386 def __del__(self):
387 monitor.append(1)
387 monitor.append(1)
388 def __repr__(self):
388 def __repr__(self):
389 return "<A instance>"
389 return "<A instance>"
390
390
391 _ip.user_ns["a"] = A()
391 _ip.user_ns["a"] = A()
392 _ip.run_cell("a")
392 _ip.run_cell("a")
393
393
394 nt.assert_equal(monitor, [])
394 nt.assert_equal(monitor, [])
395 _ip.magic_reset("-f")
395 _ip.magic_reset("-f")
396 nt.assert_equal(monitor, [1])
396 nt.assert_equal(monitor, [1])
397
398 class TestXdel(tt.TempFileMixin):
399 def test_xdel(self):
400 """Test that references from %run are cleared by xdel."""
401 src = ("class A(object):\n"
402 " monitor = []\n"
403 " def __del__(self):\n"
404 " self.monitor.append(1)\n"
405 "a = A()\n")
406 self.mktmp(src)
407 # %run creates some hidden references...
408 _ip.magic("run %s" % self.fname)
409 # ... as does the displayhook.
410 _ip.run_cell("a")
411
412 monitor = _ip.user_ns["A"].monitor
413 nt.assert_equal(monitor, [])
414
415 _ip.magic("xdel a")
416
417 # Check that a's __del__ method has been called.
418 nt.assert_equal(monitor, [1])
397
419
398 def doctest_who():
420 def doctest_who():
399 """doctest for %who
421 """doctest for %who
400
422
401 In [1]: %reset -f
423 In [1]: %reset -f
402
424
403 In [2]: alpha = 123
425 In [2]: alpha = 123
404
426
405 In [3]: beta = 'beta'
427 In [3]: beta = 'beta'
406
428
407 In [4]: %who int
429 In [4]: %who int
408 alpha
430 alpha
409
431
410 In [5]: %who str
432 In [5]: %who str
411 beta
433 beta
412
434
413 In [6]: %whos
435 In [6]: %whos
414 Variable Type Data/Info
436 Variable Type Data/Info
415 ----------------------------
437 ----------------------------
416 alpha int 123
438 alpha int 123
417 beta str beta
439 beta str beta
418
440
419 In [7]: %who_ls
441 In [7]: %who_ls
420 Out[7]: ['alpha', 'beta']
442 Out[7]: ['alpha', 'beta']
421 """
443 """
422
444
423 def doctest_precision():
445 def doctest_precision():
424 """doctest for %precision
446 """doctest for %precision
425
447
426 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
448 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
427
449
428 In [2]: %precision 5
450 In [2]: %precision 5
429 Out[2]: '%.5f'
451 Out[2]: '%.5f'
430
452
431 In [3]: f.float_format
453 In [3]: f.float_format
432 Out[3]: '%.5f'
454 Out[3]: '%.5f'
433
455
434 In [4]: %precision %e
456 In [4]: %precision %e
435 Out[4]: '%e'
457 Out[4]: '%e'
436
458
437 In [5]: f(3.1415927)
459 In [5]: f(3.1415927)
438 Out[5]: '3.141593e+00'
460 Out[5]: '3.141593e+00'
439 """
461 """
440
462
@@ -1,220 +1,230 b''
1 """Global IPython app to support test running.
1 """Global IPython app to support test running.
2
2
3 We must start our own ipython object and heavily muck with it so that all the
3 We must start our own ipython object and heavily muck with it so that all the
4 modifications IPython makes to system behavior don't send the doctest machinery
4 modifications IPython makes to system behavior don't send the doctest machinery
5 into a fit. This code should be considered a gross hack, but it gets the job
5 into a fit. This code should be considered a gross hack, but it gets the job
6 done.
6 done.
7 """
7 """
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9 from __future__ import print_function
9 from __future__ import print_function
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009-2010 The IPython Development Team
12 # Copyright (C) 2009-2010 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # stdlib
22 # stdlib
23 import __builtin__
23 import __builtin__
24 import os
24 import os
25 import sys
25 import sys
26 from types import MethodType
26 from types import MethodType
27
27
28 # our own
28 # our own
29 from . import tools
29 from . import tools
30
30
31 from IPython.utils import io
31 from IPython.utils import io
32 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
32 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Functions
35 # Functions
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 class StreamProxy(io.IOStream):
38 class StreamProxy(io.IOStream):
39 """Proxy for sys.stdout/err. This will request the stream *at call time*
39 """Proxy for sys.stdout/err. This will request the stream *at call time*
40 allowing for nose's Capture plugin's redirection of sys.stdout/err.
40 allowing for nose's Capture plugin's redirection of sys.stdout/err.
41
41
42 Parameters
42 Parameters
43 ----------
43 ----------
44 name : str
44 name : str
45 The name of the stream. This will be requested anew at every call
45 The name of the stream. This will be requested anew at every call
46 """
46 """
47
47
48 def __init__(self, name):
48 def __init__(self, name):
49 self.name=name
49 self.name=name
50
50
51 @property
51 @property
52 def stream(self):
52 def stream(self):
53 return getattr(sys, self.name)
53 return getattr(sys, self.name)
54
54
55 def flush(self):
55 def flush(self):
56 self.stream.flush()
56 self.stream.flush()
57
57
58 # Hack to modify the %run command so we can sync the user's namespace with the
58 # Hack to modify the %run command so we can sync the user's namespace with the
59 # test globals. Once we move over to a clean magic system, this will be done
59 # test globals. Once we move over to a clean magic system, this will be done
60 # with much less ugliness.
60 # with much less ugliness.
61
61
62 class py_file_finder(object):
62 class py_file_finder(object):
63 def __init__(self,test_filename):
63 def __init__(self,test_filename):
64 self.test_filename = test_filename
64 self.test_filename = test_filename
65
65
66 def __call__(self,name):
66 def __call__(self,name):
67 from IPython.utils.path import get_py_filename
67 from IPython.utils.path import get_py_filename
68 try:
68 try:
69 return get_py_filename(name)
69 return get_py_filename(name)
70 except IOError:
70 except IOError:
71 test_dir = os.path.dirname(self.test_filename)
71 test_dir = os.path.dirname(self.test_filename)
72 new_path = os.path.join(test_dir,name)
72 new_path = os.path.join(test_dir,name)
73 return get_py_filename(new_path)
73 return get_py_filename(new_path)
74
74
75
75
76 def _run_ns_sync(self,arg_s,runner=None):
76 def _run_ns_sync(self,arg_s,runner=None):
77 """Modified version of %run that syncs testing namespaces.
77 """Modified version of %run that syncs testing namespaces.
78
78
79 This is strictly needed for running doctests that call %run.
79 This is strictly needed for running doctests that call %run.
80 """
80 """
81 #print('in run_ns_sync', arg_s, file=sys.stderr) # dbg
81 #print('in run_ns_sync', arg_s, file=sys.stderr) # dbg
82 finder = py_file_finder(arg_s)
82 finder = py_file_finder(arg_s)
83 return get_ipython().magic_run_ori(arg_s, runner, finder)
83 return get_ipython().magic_run_ori(arg_s, runner, finder)
84
84
85
85
86 class ipnsdict(dict):
86 class ipnsdict(dict):
87 """A special subclass of dict for use as an IPython namespace in doctests.
87 """A special subclass of dict for use as an IPython namespace in doctests.
88
88
89 This subclass adds a simple checkpointing capability so that when testing
89 This subclass adds a simple checkpointing capability so that when testing
90 machinery clears it (we use it as the test execution context), it doesn't
90 machinery clears it (we use it as the test execution context), it doesn't
91 get completely destroyed.
91 get completely destroyed.
92
92
93 In addition, it can handle the presence of the '_' key in a special manner,
93 In addition, it can handle the presence of the '_' key in a special manner,
94 which is needed because of how Python's doctest machinery operates with
94 which is needed because of how Python's doctest machinery operates with
95 '_'. See constructor and :meth:`update` for details.
95 '_'. See constructor and :meth:`update` for details.
96 """
96 """
97
97
98 def __init__(self,*a):
98 def __init__(self,*a):
99 dict.__init__(self,*a)
99 dict.__init__(self,*a)
100 self._savedict = {}
100 self._savedict = {}
101 # If this flag is True, the .update() method will unconditionally
101 # If this flag is True, the .update() method will unconditionally
102 # remove a key named '_'. This is so that such a dict can be used as a
102 # remove a key named '_'. This is so that such a dict can be used as a
103 # namespace in doctests that call '_'.
103 # namespace in doctests that call '_'.
104 self.protect_underscore = False
104 self.protect_underscore = False
105
105
106 def clear(self):
106 def clear(self):
107 dict.clear(self)
107 dict.clear(self)
108 self.update(self._savedict)
108 self.update(self._savedict)
109
109
110 def _checkpoint(self):
110 def _checkpoint(self):
111 self._savedict.clear()
111 self._savedict.clear()
112 self._savedict.update(self)
112 self._savedict.update(self)
113
113
114 def update(self,other):
114 def update(self,other):
115 self._checkpoint()
115 self._checkpoint()
116 dict.update(self,other)
116 dict.update(self,other)
117
117
118 if self.protect_underscore:
118 if self.protect_underscore:
119 # If '_' is in the namespace, python won't set it when executing
119 # If '_' is in the namespace, python won't set it when executing
120 # code *in doctests*, and we have multiple doctests that use '_'.
120 # code *in doctests*, and we have multiple doctests that use '_'.
121 # So we ensure that the namespace is always 'clean' of it before
121 # So we ensure that the namespace is always 'clean' of it before
122 # it's used for test code execution.
122 # it's used for test code execution.
123 # This flag is only turned on by the doctest machinery, so that
123 # This flag is only turned on by the doctest machinery, so that
124 # normal test code can assume the _ key is updated like any other
124 # normal test code can assume the _ key is updated like any other
125 # key and can test for its presence after cell executions.
125 # key and can test for its presence after cell executions.
126 self.pop('_', None)
126 self.pop('_', None)
127
127
128 # The builtins namespace must *always* be the real __builtin__ module,
128 # The builtins namespace must *always* be the real __builtin__ module,
129 # else weird stuff happens. The main ipython code does have provisions
129 # else weird stuff happens. The main ipython code does have provisions
130 # to ensure this after %run, but since in this class we do some
130 # to ensure this after %run, but since in this class we do some
131 # aggressive low-level cleaning of the execution namespace, we need to
131 # aggressive low-level cleaning of the execution namespace, we need to
132 # correct for that ourselves, to ensure consitency with the 'real'
132 # correct for that ourselves, to ensure consitency with the 'real'
133 # ipython.
133 # ipython.
134 self['__builtins__'] = __builtin__
134 self['__builtins__'] = __builtin__
135
136 def __delitem__(self, key):
137 """Part of the test suite checks that we can release all
138 references to an object. So we need to make sure that we're not
139 keeping a reference in _savedict."""
140 dict.__delitem__(self, key)
141 try:
142 del self._savedict[key]
143 except KeyError:
144 pass
135
145
136
146
137 def get_ipython():
147 def get_ipython():
138 # This will get replaced by the real thing once we start IPython below
148 # This will get replaced by the real thing once we start IPython below
139 return start_ipython()
149 return start_ipython()
140
150
141
151
142 # A couple of methods to override those in the running IPython to interact
152 # A couple of methods to override those in the running IPython to interact
143 # better with doctest (doctest captures on raw stdout, so we need to direct
153 # better with doctest (doctest captures on raw stdout, so we need to direct
144 # various types of output there otherwise it will miss them).
154 # various types of output there otherwise it will miss them).
145
155
146 def xsys(self, cmd):
156 def xsys(self, cmd):
147 """Replace the default system call with a capturing one for doctest.
157 """Replace the default system call with a capturing one for doctest.
148 """
158 """
149 # We use getoutput, but we need to strip it because pexpect captures
159 # We use getoutput, but we need to strip it because pexpect captures
150 # the trailing newline differently from commands.getoutput
160 # the trailing newline differently from commands.getoutput
151 print(self.getoutput(cmd, split=False).rstrip(), end='', file=sys.stdout)
161 print(self.getoutput(cmd, split=False).rstrip(), end='', file=sys.stdout)
152 sys.stdout.flush()
162 sys.stdout.flush()
153
163
154
164
155 def _showtraceback(self, etype, evalue, stb):
165 def _showtraceback(self, etype, evalue, stb):
156 """Print the traceback purely on stdout for doctest to capture it.
166 """Print the traceback purely on stdout for doctest to capture it.
157 """
167 """
158 print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
168 print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
159
169
160
170
161 def start_ipython():
171 def start_ipython():
162 """Start a global IPython shell, which we need for IPython-specific syntax.
172 """Start a global IPython shell, which we need for IPython-specific syntax.
163 """
173 """
164 global get_ipython
174 global get_ipython
165
175
166 # This function should only ever run once!
176 # This function should only ever run once!
167 if hasattr(start_ipython, 'already_called'):
177 if hasattr(start_ipython, 'already_called'):
168 return
178 return
169 start_ipython.already_called = True
179 start_ipython.already_called = True
170
180
171 # Store certain global objects that IPython modifies
181 # Store certain global objects that IPython modifies
172 _displayhook = sys.displayhook
182 _displayhook = sys.displayhook
173 _excepthook = sys.excepthook
183 _excepthook = sys.excepthook
174 _main = sys.modules.get('__main__')
184 _main = sys.modules.get('__main__')
175
185
176 # Create custom argv and namespaces for our IPython to be test-friendly
186 # Create custom argv and namespaces for our IPython to be test-friendly
177 config = tools.default_config()
187 config = tools.default_config()
178
188
179 # Create and initialize our test-friendly IPython instance.
189 # Create and initialize our test-friendly IPython instance.
180 shell = TerminalInteractiveShell.instance(config=config,
190 shell = TerminalInteractiveShell.instance(config=config,
181 user_ns=ipnsdict(),
191 user_ns=ipnsdict(),
182 user_global_ns={}
192 user_global_ns={}
183 )
193 )
184
194
185 # A few more tweaks needed for playing nicely with doctests...
195 # A few more tweaks needed for playing nicely with doctests...
186
196
187 # These traps are normally only active for interactive use, set them
197 # These traps are normally only active for interactive use, set them
188 # permanently since we'll be mocking interactive sessions.
198 # permanently since we'll be mocking interactive sessions.
189 shell.builtin_trap.activate()
199 shell.builtin_trap.activate()
190
200
191 # Modify the IPython system call with one that uses getoutput, so that we
201 # Modify the IPython system call with one that uses getoutput, so that we
192 # can capture subcommands and print them to Python's stdout, otherwise the
202 # can capture subcommands and print them to Python's stdout, otherwise the
193 # doctest machinery would miss them.
203 # doctest machinery would miss them.
194 shell.system = MethodType(xsys, shell, TerminalInteractiveShell)
204 shell.system = MethodType(xsys, shell, TerminalInteractiveShell)
195
205
196
206
197 shell._showtraceback = MethodType(_showtraceback, shell,
207 shell._showtraceback = MethodType(_showtraceback, shell,
198 TerminalInteractiveShell)
208 TerminalInteractiveShell)
199
209
200 # IPython is ready, now clean up some global state...
210 # IPython is ready, now clean up some global state...
201
211
202 # Deactivate the various python system hooks added by ipython for
212 # Deactivate the various python system hooks added by ipython for
203 # interactive convenience so we don't confuse the doctest system
213 # interactive convenience so we don't confuse the doctest system
204 sys.modules['__main__'] = _main
214 sys.modules['__main__'] = _main
205 sys.displayhook = _displayhook
215 sys.displayhook = _displayhook
206 sys.excepthook = _excepthook
216 sys.excepthook = _excepthook
207
217
208 # So that ipython magics and aliases can be doctested (they work by making
218 # So that ipython magics and aliases can be doctested (they work by making
209 # a call into a global _ip object). Also make the top-level get_ipython
219 # a call into a global _ip object). Also make the top-level get_ipython
210 # now return this without recursively calling here again.
220 # now return this without recursively calling here again.
211 _ip = shell
221 _ip = shell
212 get_ipython = _ip.get_ipython
222 get_ipython = _ip.get_ipython
213 __builtin__._ip = _ip
223 __builtin__._ip = _ip
214 __builtin__.get_ipython = get_ipython
224 __builtin__.get_ipython = get_ipython
215
225
216 # To avoid extra IPython messages during testing, suppress io.stdout/stderr
226 # To avoid extra IPython messages during testing, suppress io.stdout/stderr
217 io.stdout = StreamProxy('stdout')
227 io.stdout = StreamProxy('stdout')
218 io.stderr = StreamProxy('stderr')
228 io.stderr = StreamProxy('stderr')
219
229
220 return _ip
230 return _ip
General Comments 0
You need to be logged in to leave comments. Login now