Show More
@@ -0,0 +1,32 b'' | |||||
|
1 | """Error script. DO NOT EDIT FURTHER! It will break exception doctests!!!""" | |||
|
2 | import sys | |||
|
3 | ||||
|
4 | def div0(): | |||
|
5 | "foo" | |||
|
6 | x = 1 | |||
|
7 | y = 0 | |||
|
8 | x/y | |||
|
9 | ||||
|
10 | def sysexit(stat, mode): | |||
|
11 | raise SystemExit(stat, 'Mode = %s' % mode) | |||
|
12 | ||||
|
13 | def bar(mode): | |||
|
14 | "bar" | |||
|
15 | if mode=='div': | |||
|
16 | div0() | |||
|
17 | elif mode=='exit': | |||
|
18 | try: | |||
|
19 | stat = int(sys.argv[2]) | |||
|
20 | except: | |||
|
21 | stat = 1 | |||
|
22 | sysexit(stat, mode) | |||
|
23 | else: | |||
|
24 | raise ValueError('Unknown mode') | |||
|
25 | ||||
|
26 | if __name__ == '__main__': | |||
|
27 | try: | |||
|
28 | mode = sys.argv[1] | |||
|
29 | except IndexError: | |||
|
30 | mode = 'div' | |||
|
31 | ||||
|
32 | bar(mode) |
@@ -1,2529 +1,2528 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Main IPython Component |
|
3 | Main IPython Component | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from __future__ import with_statement |
|
19 | from __future__ import with_statement | |
20 | from __future__ import absolute_import |
|
20 | from __future__ import absolute_import | |
21 |
|
21 | |||
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | import StringIO |
|
23 | import StringIO | |
24 | import bdb |
|
24 | import bdb | |
25 | import codeop |
|
25 | import codeop | |
26 | import exceptions |
|
26 | import exceptions | |
27 | import new |
|
27 | import new | |
28 | import os |
|
28 | import os | |
29 | import re |
|
29 | import re | |
30 | import string |
|
30 | import string | |
31 | import sys |
|
31 | import sys | |
32 | import tempfile |
|
32 | import tempfile | |
33 | from contextlib import nested |
|
33 | from contextlib import nested | |
34 |
|
34 | |||
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 prefilter |
|
37 | from IPython.core import prefilter | |
38 | from IPython.core import shadowns |
|
38 | from IPython.core import shadowns | |
39 | from IPython.core import ultratb |
|
39 | from IPython.core import ultratb | |
40 | from IPython.core.alias import AliasManager |
|
40 | from IPython.core.alias import AliasManager | |
41 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | from IPython.core.builtin_trap import BuiltinTrap | |
42 | from IPython.core.component import Component |
|
42 | from IPython.core.component import Component | |
43 | from IPython.core.display_trap import DisplayTrap |
|
43 | from IPython.core.display_trap import DisplayTrap | |
44 | from IPython.core.error import TryNext, UsageError |
|
44 | from IPython.core.error import TryNext, UsageError | |
45 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
45 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
46 | from IPython.core.logger import Logger |
|
46 | from IPython.core.logger import Logger | |
47 | from IPython.core.magic import Magic |
|
47 | from IPython.core.magic import Magic | |
48 | from IPython.core.prefilter import PrefilterManager |
|
48 | from IPython.core.prefilter import PrefilterManager | |
49 | from IPython.core.prompts import CachedOutput |
|
49 | from IPython.core.prompts import CachedOutput | |
50 | from IPython.core.pylabtools import pylab_activate |
|
50 | from IPython.core.pylabtools import pylab_activate | |
51 | from IPython.core.usage import interactive_usage, default_banner |
|
51 | from IPython.core.usage import interactive_usage, default_banner | |
52 | from IPython.external.Itpl import ItplNS |
|
52 | from IPython.external.Itpl import ItplNS | |
53 | from IPython.lib.inputhook import enable_gui |
|
53 | from IPython.lib.inputhook import enable_gui | |
54 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
54 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
55 | from IPython.utils import PyColorize |
|
55 | from IPython.utils import PyColorize | |
56 | from IPython.utils import pickleshare |
|
56 | from IPython.utils import pickleshare | |
57 | from IPython.utils.genutils import get_ipython_dir |
|
57 | from IPython.utils.genutils import get_ipython_dir | |
58 | from IPython.utils.ipstruct import Struct |
|
58 | from IPython.utils.ipstruct import Struct | |
59 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
59 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
60 | from IPython.utils.strdispatch import StrDispatch |
|
60 | from IPython.utils.strdispatch import StrDispatch | |
61 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
61 | from IPython.utils.syspathcontext import prepended_to_syspath | |
62 |
|
62 | |||
63 | # XXX - need to clean up this import * line |
|
63 | # XXX - need to clean up this import * line | |
64 | from IPython.utils.genutils import * |
|
64 | from IPython.utils.genutils import * | |
65 |
|
65 | |||
66 | # from IPython.utils import growl |
|
66 | # from IPython.utils import growl | |
67 | # growl.start("IPython") |
|
67 | # growl.start("IPython") | |
68 |
|
68 | |||
69 | from IPython.utils.traitlets import ( |
|
69 | from IPython.utils.traitlets import ( | |
70 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
70 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
71 | ) |
|
71 | ) | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # store the builtin raw_input globally, and use this always, in case user code |
|
77 | # store the builtin raw_input globally, and use this always, in case user code | |
78 | # overwrites it (like wx.py.PyShell does) |
|
78 | # overwrites it (like wx.py.PyShell does) | |
79 | raw_input_original = raw_input |
|
79 | raw_input_original = raw_input | |
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 | ini_spaces_re = re.compile(r'^(\s+)') |
|
88 | ini_spaces_re = re.compile(r'^(\s+)') | |
89 |
|
89 | |||
90 |
|
90 | |||
91 | def num_ini_spaces(strng): |
|
91 | def num_ini_spaces(strng): | |
92 | """Return the number of initial spaces in a string""" |
|
92 | """Return the number of initial spaces in a string""" | |
93 |
|
93 | |||
94 | ini_spaces = ini_spaces_re.match(strng) |
|
94 | ini_spaces = ini_spaces_re.match(strng) | |
95 | if ini_spaces: |
|
95 | if ini_spaces: | |
96 | return ini_spaces.end() |
|
96 | return ini_spaces.end() | |
97 | else: |
|
97 | else: | |
98 | return 0 |
|
98 | return 0 | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | def softspace(file, newvalue): |
|
101 | def softspace(file, newvalue): | |
102 | """Copied from code.py, to remove the dependency""" |
|
102 | """Copied from code.py, to remove the dependency""" | |
103 |
|
103 | |||
104 | oldvalue = 0 |
|
104 | oldvalue = 0 | |
105 | try: |
|
105 | try: | |
106 | oldvalue = file.softspace |
|
106 | oldvalue = file.softspace | |
107 | except AttributeError: |
|
107 | except AttributeError: | |
108 | pass |
|
108 | pass | |
109 | try: |
|
109 | try: | |
110 | file.softspace = newvalue |
|
110 | file.softspace = newvalue | |
111 | except (AttributeError, TypeError): |
|
111 | except (AttributeError, TypeError): | |
112 | # "attribute-less object" or "read-only attributes" |
|
112 | # "attribute-less object" or "read-only attributes" | |
113 | pass |
|
113 | pass | |
114 | return oldvalue |
|
114 | return oldvalue | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | def no_op(*a, **kw): pass |
|
117 | def no_op(*a, **kw): pass | |
118 |
|
118 | |||
119 | class SpaceInInput(exceptions.Exception): pass |
|
119 | class SpaceInInput(exceptions.Exception): pass | |
120 |
|
120 | |||
121 | class Bunch: pass |
|
121 | class Bunch: pass | |
122 |
|
122 | |||
123 | class InputList(list): |
|
123 | class InputList(list): | |
124 | """Class to store user input. |
|
124 | """Class to store user input. | |
125 |
|
125 | |||
126 | It's basically a list, but slices return a string instead of a list, thus |
|
126 | It's basically a list, but slices return a string instead of a list, thus | |
127 | allowing things like (assuming 'In' is an instance): |
|
127 | allowing things like (assuming 'In' is an instance): | |
128 |
|
128 | |||
129 | exec In[4:7] |
|
129 | exec In[4:7] | |
130 |
|
130 | |||
131 | or |
|
131 | or | |
132 |
|
132 | |||
133 | exec In[5:9] + In[14] + In[21:25]""" |
|
133 | exec In[5:9] + In[14] + In[21:25]""" | |
134 |
|
134 | |||
135 | def __getslice__(self,i,j): |
|
135 | def __getslice__(self,i,j): | |
136 | return ''.join(list.__getslice__(self,i,j)) |
|
136 | return ''.join(list.__getslice__(self,i,j)) | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | class SyntaxTB(ultratb.ListTB): |
|
139 | class SyntaxTB(ultratb.ListTB): | |
140 | """Extension which holds some state: the last exception value""" |
|
140 | """Extension which holds some state: the last exception value""" | |
141 |
|
141 | |||
142 | def __init__(self,color_scheme = 'NoColor'): |
|
142 | def __init__(self,color_scheme = 'NoColor'): | |
143 | ultratb.ListTB.__init__(self,color_scheme) |
|
143 | ultratb.ListTB.__init__(self,color_scheme) | |
144 | self.last_syntax_error = None |
|
144 | self.last_syntax_error = None | |
145 |
|
145 | |||
146 | def __call__(self, etype, value, elist): |
|
146 | def __call__(self, etype, value, elist): | |
147 | self.last_syntax_error = value |
|
147 | self.last_syntax_error = value | |
148 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
148 | ultratb.ListTB.__call__(self,etype,value,elist) | |
149 |
|
149 | |||
150 | def clear_err_state(self): |
|
150 | def clear_err_state(self): | |
151 | """Return the current error state and clear it""" |
|
151 | """Return the current error state and clear it""" | |
152 | e = self.last_syntax_error |
|
152 | e = self.last_syntax_error | |
153 | self.last_syntax_error = None |
|
153 | self.last_syntax_error = None | |
154 | return e |
|
154 | return e | |
155 |
|
155 | |||
156 |
|
156 | |||
157 | def get_default_editor(): |
|
157 | def get_default_editor(): | |
158 | try: |
|
158 | try: | |
159 | ed = os.environ['EDITOR'] |
|
159 | ed = os.environ['EDITOR'] | |
160 | except KeyError: |
|
160 | except KeyError: | |
161 | if os.name == 'posix': |
|
161 | if os.name == 'posix': | |
162 | ed = 'vi' # the only one guaranteed to be there! |
|
162 | ed = 'vi' # the only one guaranteed to be there! | |
163 | else: |
|
163 | else: | |
164 | ed = 'notepad' # same in Windows! |
|
164 | ed = 'notepad' # same in Windows! | |
165 | return ed |
|
165 | return ed | |
166 |
|
166 | |||
167 |
|
167 | |||
168 | def get_default_colors(): |
|
168 | def get_default_colors(): | |
169 | if sys.platform=='darwin': |
|
169 | if sys.platform=='darwin': | |
170 | return "LightBG" |
|
170 | return "LightBG" | |
171 | elif os.name=='nt': |
|
171 | elif os.name=='nt': | |
172 | return 'Linux' |
|
172 | return 'Linux' | |
173 | else: |
|
173 | else: | |
174 | return 'Linux' |
|
174 | return 'Linux' | |
175 |
|
175 | |||
176 |
|
176 | |||
177 | class SeparateStr(Str): |
|
177 | class SeparateStr(Str): | |
178 | """A Str subclass to validate separate_in, separate_out, etc. |
|
178 | """A Str subclass to validate separate_in, separate_out, etc. | |
179 |
|
179 | |||
180 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
180 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. | |
181 | """ |
|
181 | """ | |
182 |
|
182 | |||
183 | def validate(self, obj, value): |
|
183 | def validate(self, obj, value): | |
184 | if value == '0': value = '' |
|
184 | if value == '0': value = '' | |
185 | value = value.replace('\\n','\n') |
|
185 | value = value.replace('\\n','\n') | |
186 | return super(SeparateStr, self).validate(obj, value) |
|
186 | return super(SeparateStr, self).validate(obj, value) | |
187 |
|
187 | |||
188 |
|
188 | |||
189 | def make_user_namespaces(user_ns=None, user_global_ns=None): |
|
189 | def make_user_namespaces(user_ns=None, user_global_ns=None): | |
190 | """Return a valid local and global user interactive namespaces. |
|
190 | """Return a valid local and global user interactive namespaces. | |
191 |
|
191 | |||
192 | This builds a dict with the minimal information needed to operate as a |
|
192 | This builds a dict with the minimal information needed to operate as a | |
193 | valid IPython user namespace, which you can pass to the various |
|
193 | valid IPython user namespace, which you can pass to the various | |
194 | embedding classes in ipython. The default implementation returns the |
|
194 | embedding classes in ipython. The default implementation returns the | |
195 | same dict for both the locals and the globals to allow functions to |
|
195 | same dict for both the locals and the globals to allow functions to | |
196 | refer to variables in the namespace. Customized implementations can |
|
196 | refer to variables in the namespace. Customized implementations can | |
197 | return different dicts. The locals dictionary can actually be anything |
|
197 | return different dicts. The locals dictionary can actually be anything | |
198 | following the basic mapping protocol of a dict, but the globals dict |
|
198 | following the basic mapping protocol of a dict, but the globals dict | |
199 | must be a true dict, not even a subclass. It is recommended that any |
|
199 | must be a true dict, not even a subclass. It is recommended that any | |
200 | custom object for the locals namespace synchronize with the globals |
|
200 | custom object for the locals namespace synchronize with the globals | |
201 | dict somehow. |
|
201 | dict somehow. | |
202 |
|
202 | |||
203 | Raises TypeError if the provided globals namespace is not a true dict. |
|
203 | Raises TypeError if the provided globals namespace is not a true dict. | |
204 |
|
204 | |||
205 | Parameters |
|
205 | Parameters | |
206 | ---------- |
|
206 | ---------- | |
207 | user_ns : dict-like, optional |
|
207 | user_ns : dict-like, optional | |
208 | The current user namespace. The items in this namespace should |
|
208 | The current user namespace. The items in this namespace should | |
209 | be included in the output. If None, an appropriate blank |
|
209 | be included in the output. If None, an appropriate blank | |
210 | namespace should be created. |
|
210 | namespace should be created. | |
211 | user_global_ns : dict, optional |
|
211 | user_global_ns : dict, optional | |
212 | The current user global namespace. The items in this namespace |
|
212 | The current user global namespace. The items in this namespace | |
213 | should be included in the output. If None, an appropriate |
|
213 | should be included in the output. If None, an appropriate | |
214 | blank namespace should be created. |
|
214 | blank namespace should be created. | |
215 |
|
215 | |||
216 | Returns |
|
216 | Returns | |
217 | ------- |
|
217 | ------- | |
218 | A pair of dictionary-like object to be used as the local namespace |
|
218 | A pair of dictionary-like object to be used as the local namespace | |
219 | of the interpreter and a dict to be used as the global namespace. |
|
219 | of the interpreter and a dict to be used as the global namespace. | |
220 | """ |
|
220 | """ | |
221 |
|
221 | |||
222 | if user_ns is None: |
|
222 | if user_ns is None: | |
223 | # Set __name__ to __main__ to better match the behavior of the |
|
223 | # Set __name__ to __main__ to better match the behavior of the | |
224 | # normal interpreter. |
|
224 | # normal interpreter. | |
225 | user_ns = {'__name__' :'__main__', |
|
225 | user_ns = {'__name__' :'__main__', | |
226 | '__builtins__' : __builtin__, |
|
226 | '__builtins__' : __builtin__, | |
227 | } |
|
227 | } | |
228 | else: |
|
228 | else: | |
229 | user_ns.setdefault('__name__','__main__') |
|
229 | user_ns.setdefault('__name__','__main__') | |
230 | user_ns.setdefault('__builtins__',__builtin__) |
|
230 | user_ns.setdefault('__builtins__',__builtin__) | |
231 |
|
231 | |||
232 | if user_global_ns is None: |
|
232 | if user_global_ns is None: | |
233 | user_global_ns = user_ns |
|
233 | user_global_ns = user_ns | |
234 | if type(user_global_ns) is not dict: |
|
234 | if type(user_global_ns) is not dict: | |
235 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
235 | raise TypeError("user_global_ns must be a true dict; got %r" | |
236 | % type(user_global_ns)) |
|
236 | % type(user_global_ns)) | |
237 |
|
237 | |||
238 | return user_ns, user_global_ns |
|
238 | return user_ns, user_global_ns | |
239 |
|
239 | |||
240 | #----------------------------------------------------------------------------- |
|
240 | #----------------------------------------------------------------------------- | |
241 | # Main IPython class |
|
241 | # Main IPython class | |
242 | #----------------------------------------------------------------------------- |
|
242 | #----------------------------------------------------------------------------- | |
243 |
|
243 | |||
244 |
|
244 | |||
245 | class InteractiveShell(Component, Magic): |
|
245 | class InteractiveShell(Component, Magic): | |
246 | """An enhanced, interactive shell for Python.""" |
|
246 | """An enhanced, interactive shell for Python.""" | |
247 |
|
247 | |||
248 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
248 | autocall = Enum((0,1,2), default_value=1, config=True) | |
249 | autoedit_syntax = CBool(False, config=True) |
|
249 | autoedit_syntax = CBool(False, config=True) | |
250 | autoindent = CBool(True, config=True) |
|
250 | autoindent = CBool(True, config=True) | |
251 | automagic = CBool(True, config=True) |
|
251 | automagic = CBool(True, config=True) | |
252 | banner = Str('') |
|
252 | banner = Str('') | |
253 | banner1 = Str(default_banner, config=True) |
|
253 | banner1 = Str(default_banner, config=True) | |
254 | banner2 = Str('', config=True) |
|
254 | banner2 = Str('', config=True) | |
255 | cache_size = Int(1000, config=True) |
|
255 | cache_size = Int(1000, config=True) | |
256 | color_info = CBool(True, config=True) |
|
256 | color_info = CBool(True, config=True) | |
257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
258 | default_value=get_default_colors(), config=True) |
|
258 | default_value=get_default_colors(), config=True) | |
259 | confirm_exit = CBool(True, config=True) |
|
259 | confirm_exit = CBool(True, config=True) | |
260 | debug = CBool(False, config=True) |
|
260 | debug = CBool(False, config=True) | |
261 | deep_reload = CBool(False, config=True) |
|
261 | deep_reload = CBool(False, config=True) | |
262 | # This display_banner only controls whether or not self.show_banner() |
|
262 | # This display_banner only controls whether or not self.show_banner() | |
263 | # is called when mainloop/interact are called. The default is False |
|
263 | # is called when mainloop/interact are called. The default is False | |
264 | # because for the terminal based application, the banner behavior |
|
264 | # because for the terminal based application, the banner behavior | |
265 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
265 | # is controlled by Global.display_banner, which IPythonApp looks at | |
266 | # to determine if *it* should call show_banner() by hand or not. |
|
266 | # to determine if *it* should call show_banner() by hand or not. | |
267 | display_banner = CBool(False) # This isn't configurable! |
|
267 | display_banner = CBool(False) # This isn't configurable! | |
268 | embedded = CBool(False) |
|
268 | embedded = CBool(False) | |
269 | embedded_active = CBool(False) |
|
269 | embedded_active = CBool(False) | |
270 | editor = Str(get_default_editor(), config=True) |
|
270 | editor = Str(get_default_editor(), config=True) | |
271 | filename = Str("<ipython console>") |
|
271 | filename = Str("<ipython console>") | |
272 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
272 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
273 | logstart = CBool(False, config=True) |
|
273 | logstart = CBool(False, config=True) | |
274 | logfile = Str('', config=True) |
|
274 | logfile = Str('', config=True) | |
275 | logappend = Str('', config=True) |
|
275 | logappend = Str('', config=True) | |
276 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
276 | object_info_string_level = Enum((0,1,2), default_value=0, | |
277 | config=True) |
|
277 | config=True) | |
278 | pager = Str('less', config=True) |
|
278 | pager = Str('less', config=True) | |
279 | pdb = CBool(False, config=True) |
|
279 | pdb = CBool(False, config=True) | |
280 | pprint = CBool(True, config=True) |
|
280 | pprint = CBool(True, config=True) | |
281 | profile = Str('', config=True) |
|
281 | profile = Str('', config=True) | |
282 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
282 | prompt_in1 = Str('In [\\#]: ', config=True) | |
283 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
283 | prompt_in2 = Str(' .\\D.: ', config=True) | |
284 | prompt_out = Str('Out[\\#]: ', config=True) |
|
284 | prompt_out = Str('Out[\\#]: ', config=True) | |
285 | prompts_pad_left = CBool(True, config=True) |
|
285 | prompts_pad_left = CBool(True, config=True) | |
286 | quiet = CBool(False, config=True) |
|
286 | quiet = CBool(False, config=True) | |
287 |
|
287 | |||
288 | readline_use = CBool(True, config=True) |
|
288 | readline_use = CBool(True, config=True) | |
289 | readline_merge_completions = CBool(True, config=True) |
|
289 | readline_merge_completions = CBool(True, config=True) | |
290 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
290 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
291 | readline_remove_delims = Str('-/~', config=True) |
|
291 | readline_remove_delims = Str('-/~', config=True) | |
292 | readline_parse_and_bind = List([ |
|
292 | readline_parse_and_bind = List([ | |
293 | 'tab: complete', |
|
293 | 'tab: complete', | |
294 | '"\C-l": possible-completions', |
|
294 | '"\C-l": possible-completions', | |
295 | 'set show-all-if-ambiguous on', |
|
295 | 'set show-all-if-ambiguous on', | |
296 | '"\C-o": tab-insert', |
|
296 | '"\C-o": tab-insert', | |
297 | '"\M-i": " "', |
|
297 | '"\M-i": " "', | |
298 | '"\M-o": "\d\d\d\d"', |
|
298 | '"\M-o": "\d\d\d\d"', | |
299 | '"\M-I": "\d\d\d\d"', |
|
299 | '"\M-I": "\d\d\d\d"', | |
300 | '"\C-r": reverse-search-history', |
|
300 | '"\C-r": reverse-search-history', | |
301 | '"\C-s": forward-search-history', |
|
301 | '"\C-s": forward-search-history', | |
302 | '"\C-p": history-search-backward', |
|
302 | '"\C-p": history-search-backward', | |
303 | '"\C-n": history-search-forward', |
|
303 | '"\C-n": history-search-forward', | |
304 | '"\e[A": history-search-backward', |
|
304 | '"\e[A": history-search-backward', | |
305 | '"\e[B": history-search-forward', |
|
305 | '"\e[B": history-search-forward', | |
306 | '"\C-k": kill-line', |
|
306 | '"\C-k": kill-line', | |
307 | '"\C-u": unix-line-discard', |
|
307 | '"\C-u": unix-line-discard', | |
308 | ], allow_none=False, config=True) |
|
308 | ], allow_none=False, config=True) | |
309 |
|
309 | |||
310 | screen_length = Int(0, config=True) |
|
310 | screen_length = Int(0, config=True) | |
311 |
|
311 | |||
312 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
312 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' | |
313 | separate_in = SeparateStr('\n', config=True) |
|
313 | separate_in = SeparateStr('\n', config=True) | |
314 | separate_out = SeparateStr('', config=True) |
|
314 | separate_out = SeparateStr('', config=True) | |
315 | separate_out2 = SeparateStr('', config=True) |
|
315 | separate_out2 = SeparateStr('', config=True) | |
316 |
|
316 | |||
317 | system_header = Str('IPython system call: ', config=True) |
|
317 | system_header = Str('IPython system call: ', config=True) | |
318 | system_verbose = CBool(False, config=True) |
|
318 | system_verbose = CBool(False, config=True) | |
319 | term_title = CBool(False, config=True) |
|
319 | term_title = CBool(False, config=True) | |
320 | wildcards_case_sensitive = CBool(True, config=True) |
|
320 | wildcards_case_sensitive = CBool(True, config=True) | |
321 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
321 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
322 | default_value='Context', config=True) |
|
322 | default_value='Context', config=True) | |
323 |
|
323 | |||
324 | autoexec = List(allow_none=False) |
|
324 | autoexec = List(allow_none=False) | |
325 |
|
325 | |||
326 | # class attribute to indicate whether the class supports threads or not. |
|
326 | # class attribute to indicate whether the class supports threads or not. | |
327 | # Subclasses with thread support should override this as needed. |
|
327 | # Subclasses with thread support should override this as needed. | |
328 | isthreaded = False |
|
328 | isthreaded = False | |
329 |
|
329 | |||
330 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, |
|
330 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, | |
331 | user_ns=None, user_global_ns=None, |
|
331 | user_ns=None, user_global_ns=None, | |
332 | banner1=None, banner2=None, display_banner=None, |
|
332 | banner1=None, banner2=None, display_banner=None, | |
333 | custom_exceptions=((),None)): |
|
333 | custom_exceptions=((),None)): | |
334 |
|
334 | |||
335 | # This is where traitlets with a config_key argument are updated |
|
335 | # This is where traitlets with a config_key argument are updated | |
336 | # from the values on config. |
|
336 | # from the values on config. | |
337 | super(InteractiveShell, self).__init__(parent, config=config) |
|
337 | super(InteractiveShell, self).__init__(parent, config=config) | |
338 |
|
338 | |||
339 | # These are relatively independent and stateless |
|
339 | # These are relatively independent and stateless | |
340 | self.init_ipython_dir(ipython_dir) |
|
340 | self.init_ipython_dir(ipython_dir) | |
341 | self.init_instance_attrs() |
|
341 | self.init_instance_attrs() | |
342 | self.init_term_title() |
|
342 | self.init_term_title() | |
343 | self.init_usage(usage) |
|
343 | self.init_usage(usage) | |
344 | self.init_banner(banner1, banner2, display_banner) |
|
344 | self.init_banner(banner1, banner2, display_banner) | |
345 |
|
345 | |||
346 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
346 | # Create namespaces (user_ns, user_global_ns, etc.) | |
347 | self.init_create_namespaces(user_ns, user_global_ns) |
|
347 | self.init_create_namespaces(user_ns, user_global_ns) | |
348 | # This has to be done after init_create_namespaces because it uses |
|
348 | # This has to be done after init_create_namespaces because it uses | |
349 | # something in self.user_ns, but before init_sys_modules, which |
|
349 | # something in self.user_ns, but before init_sys_modules, which | |
350 | # is the first thing to modify sys. |
|
350 | # is the first thing to modify sys. | |
351 | self.save_sys_module_state() |
|
351 | self.save_sys_module_state() | |
352 | self.init_sys_modules() |
|
352 | self.init_sys_modules() | |
353 |
|
353 | |||
354 | self.init_history() |
|
354 | self.init_history() | |
355 | self.init_encoding() |
|
355 | self.init_encoding() | |
356 | self.init_prefilter() |
|
356 | self.init_prefilter() | |
357 |
|
357 | |||
358 | Magic.__init__(self, self) |
|
358 | Magic.__init__(self, self) | |
359 |
|
359 | |||
360 | self.init_syntax_highlighting() |
|
360 | self.init_syntax_highlighting() | |
361 | self.init_hooks() |
|
361 | self.init_hooks() | |
362 | self.init_pushd_popd_magic() |
|
362 | self.init_pushd_popd_magic() | |
363 | self.init_traceback_handlers(custom_exceptions) |
|
363 | self.init_traceback_handlers(custom_exceptions) | |
364 | self.init_user_ns() |
|
364 | self.init_user_ns() | |
365 | self.init_logger() |
|
365 | self.init_logger() | |
366 | self.init_alias() |
|
366 | self.init_alias() | |
367 | self.init_builtins() |
|
367 | self.init_builtins() | |
368 |
|
368 | |||
369 | # pre_config_initialization |
|
369 | # pre_config_initialization | |
370 | self.init_shadow_hist() |
|
370 | self.init_shadow_hist() | |
371 |
|
371 | |||
372 | # The next section should contain averything that was in ipmaker. |
|
372 | # The next section should contain averything that was in ipmaker. | |
373 | self.init_logstart() |
|
373 | self.init_logstart() | |
374 |
|
374 | |||
375 | # The following was in post_config_initialization |
|
375 | # The following was in post_config_initialization | |
376 | self.init_inspector() |
|
376 | self.init_inspector() | |
377 | self.init_readline() |
|
377 | self.init_readline() | |
378 | self.init_prompts() |
|
378 | self.init_prompts() | |
379 | self.init_displayhook() |
|
379 | self.init_displayhook() | |
380 | self.init_reload_doctest() |
|
380 | self.init_reload_doctest() | |
381 | self.init_magics() |
|
381 | self.init_magics() | |
382 | self.init_pdb() |
|
382 | self.init_pdb() | |
383 | self.hooks.late_startup_hook() |
|
383 | self.hooks.late_startup_hook() | |
384 |
|
384 | |||
385 | def get_ipython(self): |
|
385 | def get_ipython(self): | |
386 | """Return the currently running IPython instance.""" |
|
386 | """Return the currently running IPython instance.""" | |
387 | return self |
|
387 | return self | |
388 |
|
388 | |||
389 | #------------------------------------------------------------------------- |
|
389 | #------------------------------------------------------------------------- | |
390 | # Traitlet changed handlers |
|
390 | # Traitlet changed handlers | |
391 | #------------------------------------------------------------------------- |
|
391 | #------------------------------------------------------------------------- | |
392 |
|
392 | |||
393 | def _banner1_changed(self): |
|
393 | def _banner1_changed(self): | |
394 | self.compute_banner() |
|
394 | self.compute_banner() | |
395 |
|
395 | |||
396 | def _banner2_changed(self): |
|
396 | def _banner2_changed(self): | |
397 | self.compute_banner() |
|
397 | self.compute_banner() | |
398 |
|
398 | |||
399 | def _ipython_dir_changed(self, name, new): |
|
399 | def _ipython_dir_changed(self, name, new): | |
400 | if not os.path.isdir(new): |
|
400 | if not os.path.isdir(new): | |
401 | os.makedirs(new, mode = 0777) |
|
401 | os.makedirs(new, mode = 0777) | |
402 | if not os.path.isdir(self.ipython_extension_dir): |
|
402 | if not os.path.isdir(self.ipython_extension_dir): | |
403 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
403 | os.makedirs(self.ipython_extension_dir, mode = 0777) | |
404 |
|
404 | |||
405 | @property |
|
405 | @property | |
406 | def ipython_extension_dir(self): |
|
406 | def ipython_extension_dir(self): | |
407 | return os.path.join(self.ipython_dir, 'extensions') |
|
407 | return os.path.join(self.ipython_dir, 'extensions') | |
408 |
|
408 | |||
409 | @property |
|
409 | @property | |
410 | def usable_screen_length(self): |
|
410 | def usable_screen_length(self): | |
411 | if self.screen_length == 0: |
|
411 | if self.screen_length == 0: | |
412 | return 0 |
|
412 | return 0 | |
413 | else: |
|
413 | else: | |
414 | num_lines_bot = self.separate_in.count('\n')+1 |
|
414 | num_lines_bot = self.separate_in.count('\n')+1 | |
415 | return self.screen_length - num_lines_bot |
|
415 | return self.screen_length - num_lines_bot | |
416 |
|
416 | |||
417 | def _term_title_changed(self, name, new_value): |
|
417 | def _term_title_changed(self, name, new_value): | |
418 | self.init_term_title() |
|
418 | self.init_term_title() | |
419 |
|
419 | |||
420 | def set_autoindent(self,value=None): |
|
420 | def set_autoindent(self,value=None): | |
421 | """Set the autoindent flag, checking for readline support. |
|
421 | """Set the autoindent flag, checking for readline support. | |
422 |
|
422 | |||
423 | If called with no arguments, it acts as a toggle.""" |
|
423 | If called with no arguments, it acts as a toggle.""" | |
424 |
|
424 | |||
425 | if not self.has_readline: |
|
425 | if not self.has_readline: | |
426 | if os.name == 'posix': |
|
426 | if os.name == 'posix': | |
427 | warn("The auto-indent feature requires the readline library") |
|
427 | warn("The auto-indent feature requires the readline library") | |
428 | self.autoindent = 0 |
|
428 | self.autoindent = 0 | |
429 | return |
|
429 | return | |
430 | if value is None: |
|
430 | if value is None: | |
431 | self.autoindent = not self.autoindent |
|
431 | self.autoindent = not self.autoindent | |
432 | else: |
|
432 | else: | |
433 | self.autoindent = value |
|
433 | self.autoindent = value | |
434 |
|
434 | |||
435 | #------------------------------------------------------------------------- |
|
435 | #------------------------------------------------------------------------- | |
436 | # init_* methods called by __init__ |
|
436 | # init_* methods called by __init__ | |
437 | #------------------------------------------------------------------------- |
|
437 | #------------------------------------------------------------------------- | |
438 |
|
438 | |||
439 | def init_ipython_dir(self, ipython_dir): |
|
439 | def init_ipython_dir(self, ipython_dir): | |
440 | if ipython_dir is not None: |
|
440 | if ipython_dir is not None: | |
441 | self.ipython_dir = ipython_dir |
|
441 | self.ipython_dir = ipython_dir | |
442 | self.config.Global.ipython_dir = self.ipython_dir |
|
442 | self.config.Global.ipython_dir = self.ipython_dir | |
443 | return |
|
443 | return | |
444 |
|
444 | |||
445 | if hasattr(self.config.Global, 'ipython_dir'): |
|
445 | if hasattr(self.config.Global, 'ipython_dir'): | |
446 | self.ipython_dir = self.config.Global.ipython_dir |
|
446 | self.ipython_dir = self.config.Global.ipython_dir | |
447 | else: |
|
447 | else: | |
448 | self.ipython_dir = get_ipython_dir() |
|
448 | self.ipython_dir = get_ipython_dir() | |
449 |
|
449 | |||
450 | # All children can just read this |
|
450 | # All children can just read this | |
451 | self.config.Global.ipython_dir = self.ipython_dir |
|
451 | self.config.Global.ipython_dir = self.ipython_dir | |
452 |
|
452 | |||
453 | def init_instance_attrs(self): |
|
453 | def init_instance_attrs(self): | |
454 | self.jobs = BackgroundJobManager() |
|
454 | self.jobs = BackgroundJobManager() | |
455 | self.more = False |
|
455 | self.more = False | |
456 |
|
456 | |||
457 | # command compiler |
|
457 | # command compiler | |
458 | self.compile = codeop.CommandCompiler() |
|
458 | self.compile = codeop.CommandCompiler() | |
459 |
|
459 | |||
460 | # User input buffer |
|
460 | # User input buffer | |
461 | self.buffer = [] |
|
461 | self.buffer = [] | |
462 |
|
462 | |||
463 | # Make an empty namespace, which extension writers can rely on both |
|
463 | # Make an empty namespace, which extension writers can rely on both | |
464 | # existing and NEVER being used by ipython itself. This gives them a |
|
464 | # existing and NEVER being used by ipython itself. This gives them a | |
465 | # convenient location for storing additional information and state |
|
465 | # convenient location for storing additional information and state | |
466 | # their extensions may require, without fear of collisions with other |
|
466 | # their extensions may require, without fear of collisions with other | |
467 | # ipython names that may develop later. |
|
467 | # ipython names that may develop later. | |
468 | self.meta = Struct() |
|
468 | self.meta = Struct() | |
469 |
|
469 | |||
470 | # Object variable to store code object waiting execution. This is |
|
470 | # Object variable to store code object waiting execution. This is | |
471 | # used mainly by the multithreaded shells, but it can come in handy in |
|
471 | # used mainly by the multithreaded shells, but it can come in handy in | |
472 | # other situations. No need to use a Queue here, since it's a single |
|
472 | # other situations. No need to use a Queue here, since it's a single | |
473 | # item which gets cleared once run. |
|
473 | # item which gets cleared once run. | |
474 | self.code_to_run = None |
|
474 | self.code_to_run = None | |
475 |
|
475 | |||
476 | # Flag to mark unconditional exit |
|
476 | # Flag to mark unconditional exit | |
477 | self.exit_now = False |
|
477 | self.exit_now = False | |
478 |
|
478 | |||
479 | # Temporary files used for various purposes. Deleted at exit. |
|
479 | # Temporary files used for various purposes. Deleted at exit. | |
480 | self.tempfiles = [] |
|
480 | self.tempfiles = [] | |
481 |
|
481 | |||
482 | # Keep track of readline usage (later set by init_readline) |
|
482 | # Keep track of readline usage (later set by init_readline) | |
483 | self.has_readline = False |
|
483 | self.has_readline = False | |
484 |
|
484 | |||
485 | # keep track of where we started running (mainly for crash post-mortem) |
|
485 | # keep track of where we started running (mainly for crash post-mortem) | |
486 | # This is not being used anywhere currently. |
|
486 | # This is not being used anywhere currently. | |
487 | self.starting_dir = os.getcwd() |
|
487 | self.starting_dir = os.getcwd() | |
488 |
|
488 | |||
489 | # Indentation management |
|
489 | # Indentation management | |
490 | self.indent_current_nsp = 0 |
|
490 | self.indent_current_nsp = 0 | |
491 |
|
491 | |||
492 | def init_term_title(self): |
|
492 | def init_term_title(self): | |
493 | # Enable or disable the terminal title. |
|
493 | # Enable or disable the terminal title. | |
494 | if self.term_title: |
|
494 | if self.term_title: | |
495 | toggle_set_term_title(True) |
|
495 | toggle_set_term_title(True) | |
496 | set_term_title('IPython: ' + abbrev_cwd()) |
|
496 | set_term_title('IPython: ' + abbrev_cwd()) | |
497 | else: |
|
497 | else: | |
498 | toggle_set_term_title(False) |
|
498 | toggle_set_term_title(False) | |
499 |
|
499 | |||
500 | def init_usage(self, usage=None): |
|
500 | def init_usage(self, usage=None): | |
501 | if usage is None: |
|
501 | if usage is None: | |
502 | self.usage = interactive_usage |
|
502 | self.usage = interactive_usage | |
503 | else: |
|
503 | else: | |
504 | self.usage = usage |
|
504 | self.usage = usage | |
505 |
|
505 | |||
506 | def init_encoding(self): |
|
506 | def init_encoding(self): | |
507 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
507 | # Get system encoding at startup time. Certain terminals (like Emacs | |
508 | # under Win32 have it set to None, and we need to have a known valid |
|
508 | # under Win32 have it set to None, and we need to have a known valid | |
509 | # encoding to use in the raw_input() method |
|
509 | # encoding to use in the raw_input() method | |
510 | try: |
|
510 | try: | |
511 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
511 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
512 | except AttributeError: |
|
512 | except AttributeError: | |
513 | self.stdin_encoding = 'ascii' |
|
513 | self.stdin_encoding = 'ascii' | |
514 |
|
514 | |||
515 | def init_syntax_highlighting(self): |
|
515 | def init_syntax_highlighting(self): | |
516 | # Python source parser/formatter for syntax highlighting |
|
516 | # Python source parser/formatter for syntax highlighting | |
517 | pyformat = PyColorize.Parser().format |
|
517 | pyformat = PyColorize.Parser().format | |
518 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
518 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
519 |
|
519 | |||
520 | def init_pushd_popd_magic(self): |
|
520 | def init_pushd_popd_magic(self): | |
521 | # for pushd/popd management |
|
521 | # for pushd/popd management | |
522 | try: |
|
522 | try: | |
523 | self.home_dir = get_home_dir() |
|
523 | self.home_dir = get_home_dir() | |
524 | except HomeDirError, msg: |
|
524 | except HomeDirError, msg: | |
525 | fatal(msg) |
|
525 | fatal(msg) | |
526 |
|
526 | |||
527 | self.dir_stack = [] |
|
527 | self.dir_stack = [] | |
528 |
|
528 | |||
529 | def init_logger(self): |
|
529 | def init_logger(self): | |
530 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
530 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
531 | # local shortcut, this is used a LOT |
|
531 | # local shortcut, this is used a LOT | |
532 | self.log = self.logger.log |
|
532 | self.log = self.logger.log | |
533 |
|
533 | |||
534 | def init_logstart(self): |
|
534 | def init_logstart(self): | |
535 | if self.logappend: |
|
535 | if self.logappend: | |
536 | self.magic_logstart(self.logappend + ' append') |
|
536 | self.magic_logstart(self.logappend + ' append') | |
537 | elif self.logfile: |
|
537 | elif self.logfile: | |
538 | self.magic_logstart(self.logfile) |
|
538 | self.magic_logstart(self.logfile) | |
539 | elif self.logstart: |
|
539 | elif self.logstart: | |
540 | self.magic_logstart() |
|
540 | self.magic_logstart() | |
541 |
|
541 | |||
542 | def init_builtins(self): |
|
542 | def init_builtins(self): | |
543 | self.builtin_trap = BuiltinTrap(self) |
|
543 | self.builtin_trap = BuiltinTrap(self) | |
544 |
|
544 | |||
545 | def init_inspector(self): |
|
545 | def init_inspector(self): | |
546 | # Object inspector |
|
546 | # Object inspector | |
547 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
547 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
548 | PyColorize.ANSICodeColors, |
|
548 | PyColorize.ANSICodeColors, | |
549 | 'NoColor', |
|
549 | 'NoColor', | |
550 | self.object_info_string_level) |
|
550 | self.object_info_string_level) | |
551 |
|
551 | |||
552 | def init_prompts(self): |
|
552 | def init_prompts(self): | |
553 | # Initialize cache, set in/out prompts and printing system |
|
553 | # Initialize cache, set in/out prompts and printing system | |
554 | self.outputcache = CachedOutput(self, |
|
554 | self.outputcache = CachedOutput(self, | |
555 | self.cache_size, |
|
555 | self.cache_size, | |
556 | self.pprint, |
|
556 | self.pprint, | |
557 | input_sep = self.separate_in, |
|
557 | input_sep = self.separate_in, | |
558 | output_sep = self.separate_out, |
|
558 | output_sep = self.separate_out, | |
559 | output_sep2 = self.separate_out2, |
|
559 | output_sep2 = self.separate_out2, | |
560 | ps1 = self.prompt_in1, |
|
560 | ps1 = self.prompt_in1, | |
561 | ps2 = self.prompt_in2, |
|
561 | ps2 = self.prompt_in2, | |
562 | ps_out = self.prompt_out, |
|
562 | ps_out = self.prompt_out, | |
563 | pad_left = self.prompts_pad_left) |
|
563 | pad_left = self.prompts_pad_left) | |
564 |
|
564 | |||
565 | # user may have over-ridden the default print hook: |
|
565 | # user may have over-ridden the default print hook: | |
566 | try: |
|
566 | try: | |
567 | self.outputcache.__class__.display = self.hooks.display |
|
567 | self.outputcache.__class__.display = self.hooks.display | |
568 | except AttributeError: |
|
568 | except AttributeError: | |
569 | pass |
|
569 | pass | |
570 |
|
570 | |||
571 | def init_displayhook(self): |
|
571 | def init_displayhook(self): | |
572 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
572 | self.display_trap = DisplayTrap(self, self.outputcache) | |
573 |
|
573 | |||
574 | def init_reload_doctest(self): |
|
574 | def init_reload_doctest(self): | |
575 | # Do a proper resetting of doctest, including the necessary displayhook |
|
575 | # Do a proper resetting of doctest, including the necessary displayhook | |
576 | # monkeypatching |
|
576 | # monkeypatching | |
577 | try: |
|
577 | try: | |
578 | doctest_reload() |
|
578 | doctest_reload() | |
579 | except ImportError: |
|
579 | except ImportError: | |
580 | warn("doctest module does not exist.") |
|
580 | warn("doctest module does not exist.") | |
581 |
|
581 | |||
582 | #------------------------------------------------------------------------- |
|
582 | #------------------------------------------------------------------------- | |
583 | # Things related to the banner |
|
583 | # Things related to the banner | |
584 | #------------------------------------------------------------------------- |
|
584 | #------------------------------------------------------------------------- | |
585 |
|
585 | |||
586 | def init_banner(self, banner1, banner2, display_banner): |
|
586 | def init_banner(self, banner1, banner2, display_banner): | |
587 | if banner1 is not None: |
|
587 | if banner1 is not None: | |
588 | self.banner1 = banner1 |
|
588 | self.banner1 = banner1 | |
589 | if banner2 is not None: |
|
589 | if banner2 is not None: | |
590 | self.banner2 = banner2 |
|
590 | self.banner2 = banner2 | |
591 | if display_banner is not None: |
|
591 | if display_banner is not None: | |
592 | self.display_banner = display_banner |
|
592 | self.display_banner = display_banner | |
593 | self.compute_banner() |
|
593 | self.compute_banner() | |
594 |
|
594 | |||
595 | def show_banner(self, banner=None): |
|
595 | def show_banner(self, banner=None): | |
596 | if banner is None: |
|
596 | if banner is None: | |
597 | banner = self.banner |
|
597 | banner = self.banner | |
598 | self.write(banner) |
|
598 | self.write(banner) | |
599 |
|
599 | |||
600 | def compute_banner(self): |
|
600 | def compute_banner(self): | |
601 | self.banner = self.banner1 + '\n' |
|
601 | self.banner = self.banner1 + '\n' | |
602 | if self.profile: |
|
602 | if self.profile: | |
603 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
603 | self.banner += '\nIPython profile: %s\n' % self.profile | |
604 | if self.banner2: |
|
604 | if self.banner2: | |
605 | self.banner += '\n' + self.banner2 + '\n' |
|
605 | self.banner += '\n' + self.banner2 + '\n' | |
606 |
|
606 | |||
607 | #------------------------------------------------------------------------- |
|
607 | #------------------------------------------------------------------------- | |
608 | # Things related to injections into the sys module |
|
608 | # Things related to injections into the sys module | |
609 | #------------------------------------------------------------------------- |
|
609 | #------------------------------------------------------------------------- | |
610 |
|
610 | |||
611 | def save_sys_module_state(self): |
|
611 | def save_sys_module_state(self): | |
612 | """Save the state of hooks in the sys module. |
|
612 | """Save the state of hooks in the sys module. | |
613 |
|
613 | |||
614 | This has to be called after self.user_ns is created. |
|
614 | This has to be called after self.user_ns is created. | |
615 | """ |
|
615 | """ | |
616 | self._orig_sys_module_state = {} |
|
616 | self._orig_sys_module_state = {} | |
617 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
617 | self._orig_sys_module_state['stdin'] = sys.stdin | |
618 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
618 | self._orig_sys_module_state['stdout'] = sys.stdout | |
619 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
619 | self._orig_sys_module_state['stderr'] = sys.stderr | |
620 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
620 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
621 | try: |
|
621 | try: | |
622 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
622 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
623 | except KeyError: |
|
623 | except KeyError: | |
624 | pass |
|
624 | pass | |
625 |
|
625 | |||
626 | def restore_sys_module_state(self): |
|
626 | def restore_sys_module_state(self): | |
627 | """Restore the state of the sys module.""" |
|
627 | """Restore the state of the sys module.""" | |
628 | try: |
|
628 | try: | |
629 | for k, v in self._orig_sys_module_state.items(): |
|
629 | for k, v in self._orig_sys_module_state.items(): | |
630 | setattr(sys, k, v) |
|
630 | setattr(sys, k, v) | |
631 | except AttributeError: |
|
631 | except AttributeError: | |
632 | pass |
|
632 | pass | |
633 | try: |
|
633 | try: | |
634 | delattr(sys, 'ipcompleter') |
|
634 | delattr(sys, 'ipcompleter') | |
635 | except AttributeError: |
|
635 | except AttributeError: | |
636 | pass |
|
636 | pass | |
637 | # Reset what what done in self.init_sys_modules |
|
637 | # Reset what what done in self.init_sys_modules | |
638 | try: |
|
638 | try: | |
639 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
639 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
640 | except (AttributeError, KeyError): |
|
640 | except (AttributeError, KeyError): | |
641 | pass |
|
641 | pass | |
642 |
|
642 | |||
643 | #------------------------------------------------------------------------- |
|
643 | #------------------------------------------------------------------------- | |
644 | # Things related to hooks |
|
644 | # Things related to hooks | |
645 | #------------------------------------------------------------------------- |
|
645 | #------------------------------------------------------------------------- | |
646 |
|
646 | |||
647 | def init_hooks(self): |
|
647 | def init_hooks(self): | |
648 | # hooks holds pointers used for user-side customizations |
|
648 | # hooks holds pointers used for user-side customizations | |
649 | self.hooks = Struct() |
|
649 | self.hooks = Struct() | |
650 |
|
650 | |||
651 | self.strdispatchers = {} |
|
651 | self.strdispatchers = {} | |
652 |
|
652 | |||
653 | # Set all default hooks, defined in the IPython.hooks module. |
|
653 | # Set all default hooks, defined in the IPython.hooks module. | |
654 | import IPython.core.hooks |
|
654 | import IPython.core.hooks | |
655 | hooks = IPython.core.hooks |
|
655 | hooks = IPython.core.hooks | |
656 | for hook_name in hooks.__all__: |
|
656 | for hook_name in hooks.__all__: | |
657 | # default hooks have priority 100, i.e. low; user hooks should have |
|
657 | # default hooks have priority 100, i.e. low; user hooks should have | |
658 | # 0-100 priority |
|
658 | # 0-100 priority | |
659 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
659 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
660 |
|
660 | |||
661 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
661 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
662 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
662 | """set_hook(name,hook) -> sets an internal IPython hook. | |
663 |
|
663 | |||
664 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
664 | IPython exposes some of its internal API as user-modifiable hooks. By | |
665 | adding your function to one of these hooks, you can modify IPython's |
|
665 | adding your function to one of these hooks, you can modify IPython's | |
666 | behavior to call at runtime your own routines.""" |
|
666 | behavior to call at runtime your own routines.""" | |
667 |
|
667 | |||
668 | # At some point in the future, this should validate the hook before it |
|
668 | # At some point in the future, this should validate the hook before it | |
669 | # accepts it. Probably at least check that the hook takes the number |
|
669 | # accepts it. Probably at least check that the hook takes the number | |
670 | # of args it's supposed to. |
|
670 | # of args it's supposed to. | |
671 |
|
671 | |||
672 | f = new.instancemethod(hook,self,self.__class__) |
|
672 | f = new.instancemethod(hook,self,self.__class__) | |
673 |
|
673 | |||
674 | # check if the hook is for strdispatcher first |
|
674 | # check if the hook is for strdispatcher first | |
675 | if str_key is not None: |
|
675 | if str_key is not None: | |
676 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
676 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
677 | sdp.add_s(str_key, f, priority ) |
|
677 | sdp.add_s(str_key, f, priority ) | |
678 | self.strdispatchers[name] = sdp |
|
678 | self.strdispatchers[name] = sdp | |
679 | return |
|
679 | return | |
680 | if re_key is not None: |
|
680 | if re_key is not None: | |
681 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
681 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
682 | sdp.add_re(re.compile(re_key), f, priority ) |
|
682 | sdp.add_re(re.compile(re_key), f, priority ) | |
683 | self.strdispatchers[name] = sdp |
|
683 | self.strdispatchers[name] = sdp | |
684 | return |
|
684 | return | |
685 |
|
685 | |||
686 | dp = getattr(self.hooks, name, None) |
|
686 | dp = getattr(self.hooks, name, None) | |
687 | if name not in IPython.core.hooks.__all__: |
|
687 | if name not in IPython.core.hooks.__all__: | |
688 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
688 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
689 | if not dp: |
|
689 | if not dp: | |
690 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
690 | dp = IPython.core.hooks.CommandChainDispatcher() | |
691 |
|
691 | |||
692 | try: |
|
692 | try: | |
693 | dp.add(f,priority) |
|
693 | dp.add(f,priority) | |
694 | except AttributeError: |
|
694 | except AttributeError: | |
695 | # it was not commandchain, plain old func - replace |
|
695 | # it was not commandchain, plain old func - replace | |
696 | dp = f |
|
696 | dp = f | |
697 |
|
697 | |||
698 | setattr(self.hooks,name, dp) |
|
698 | setattr(self.hooks,name, dp) | |
699 |
|
699 | |||
700 | #------------------------------------------------------------------------- |
|
700 | #------------------------------------------------------------------------- | |
701 | # Things related to the "main" module |
|
701 | # Things related to the "main" module | |
702 | #------------------------------------------------------------------------- |
|
702 | #------------------------------------------------------------------------- | |
703 |
|
703 | |||
704 | def new_main_mod(self,ns=None): |
|
704 | def new_main_mod(self,ns=None): | |
705 | """Return a new 'main' module object for user code execution. |
|
705 | """Return a new 'main' module object for user code execution. | |
706 | """ |
|
706 | """ | |
707 | main_mod = self._user_main_module |
|
707 | main_mod = self._user_main_module | |
708 | init_fakemod_dict(main_mod,ns) |
|
708 | init_fakemod_dict(main_mod,ns) | |
709 | return main_mod |
|
709 | return main_mod | |
710 |
|
710 | |||
711 | def cache_main_mod(self,ns,fname): |
|
711 | def cache_main_mod(self,ns,fname): | |
712 | """Cache a main module's namespace. |
|
712 | """Cache a main module's namespace. | |
713 |
|
713 | |||
714 | When scripts are executed via %run, we must keep a reference to the |
|
714 | When scripts are executed via %run, we must keep a reference to the | |
715 | namespace of their __main__ module (a FakeModule instance) around so |
|
715 | namespace of their __main__ module (a FakeModule instance) around so | |
716 | that Python doesn't clear it, rendering objects defined therein |
|
716 | that Python doesn't clear it, rendering objects defined therein | |
717 | useless. |
|
717 | useless. | |
718 |
|
718 | |||
719 | This method keeps said reference in a private dict, keyed by the |
|
719 | This method keeps said reference in a private dict, keyed by the | |
720 | absolute path of the module object (which corresponds to the script |
|
720 | absolute path of the module object (which corresponds to the script | |
721 | path). This way, for multiple executions of the same script we only |
|
721 | path). This way, for multiple executions of the same script we only | |
722 | keep one copy of the namespace (the last one), thus preventing memory |
|
722 | keep one copy of the namespace (the last one), thus preventing memory | |
723 | leaks from old references while allowing the objects from the last |
|
723 | leaks from old references while allowing the objects from the last | |
724 | execution to be accessible. |
|
724 | execution to be accessible. | |
725 |
|
725 | |||
726 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
726 | Note: we can not allow the actual FakeModule instances to be deleted, | |
727 | because of how Python tears down modules (it hard-sets all their |
|
727 | because of how Python tears down modules (it hard-sets all their | |
728 | references to None without regard for reference counts). This method |
|
728 | references to None without regard for reference counts). This method | |
729 | must therefore make a *copy* of the given namespace, to allow the |
|
729 | must therefore make a *copy* of the given namespace, to allow the | |
730 | original module's __dict__ to be cleared and reused. |
|
730 | original module's __dict__ to be cleared and reused. | |
731 |
|
731 | |||
732 |
|
732 | |||
733 | Parameters |
|
733 | Parameters | |
734 | ---------- |
|
734 | ---------- | |
735 | ns : a namespace (a dict, typically) |
|
735 | ns : a namespace (a dict, typically) | |
736 |
|
736 | |||
737 | fname : str |
|
737 | fname : str | |
738 | Filename associated with the namespace. |
|
738 | Filename associated with the namespace. | |
739 |
|
739 | |||
740 | Examples |
|
740 | Examples | |
741 | -------- |
|
741 | -------- | |
742 |
|
742 | |||
743 | In [10]: import IPython |
|
743 | In [10]: import IPython | |
744 |
|
744 | |||
745 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
745 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
746 |
|
746 | |||
747 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
747 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
748 | Out[12]: True |
|
748 | Out[12]: True | |
749 | """ |
|
749 | """ | |
750 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
750 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
751 |
|
751 | |||
752 | def clear_main_mod_cache(self): |
|
752 | def clear_main_mod_cache(self): | |
753 | """Clear the cache of main modules. |
|
753 | """Clear the cache of main modules. | |
754 |
|
754 | |||
755 | Mainly for use by utilities like %reset. |
|
755 | Mainly for use by utilities like %reset. | |
756 |
|
756 | |||
757 | Examples |
|
757 | Examples | |
758 | -------- |
|
758 | -------- | |
759 |
|
759 | |||
760 | In [15]: import IPython |
|
760 | In [15]: import IPython | |
761 |
|
761 | |||
762 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
762 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
763 |
|
763 | |||
764 | In [17]: len(_ip._main_ns_cache) > 0 |
|
764 | In [17]: len(_ip._main_ns_cache) > 0 | |
765 | Out[17]: True |
|
765 | Out[17]: True | |
766 |
|
766 | |||
767 | In [18]: _ip.clear_main_mod_cache() |
|
767 | In [18]: _ip.clear_main_mod_cache() | |
768 |
|
768 | |||
769 | In [19]: len(_ip._main_ns_cache) == 0 |
|
769 | In [19]: len(_ip._main_ns_cache) == 0 | |
770 | Out[19]: True |
|
770 | Out[19]: True | |
771 | """ |
|
771 | """ | |
772 | self._main_ns_cache.clear() |
|
772 | self._main_ns_cache.clear() | |
773 |
|
773 | |||
774 | #------------------------------------------------------------------------- |
|
774 | #------------------------------------------------------------------------- | |
775 | # Things related to debugging |
|
775 | # Things related to debugging | |
776 | #------------------------------------------------------------------------- |
|
776 | #------------------------------------------------------------------------- | |
777 |
|
777 | |||
778 | def init_pdb(self): |
|
778 | def init_pdb(self): | |
779 | # Set calling of pdb on exceptions |
|
779 | # Set calling of pdb on exceptions | |
780 | # self.call_pdb is a property |
|
780 | # self.call_pdb is a property | |
781 | self.call_pdb = self.pdb |
|
781 | self.call_pdb = self.pdb | |
782 |
|
782 | |||
783 | def _get_call_pdb(self): |
|
783 | def _get_call_pdb(self): | |
784 | return self._call_pdb |
|
784 | return self._call_pdb | |
785 |
|
785 | |||
786 | def _set_call_pdb(self,val): |
|
786 | def _set_call_pdb(self,val): | |
787 |
|
787 | |||
788 | if val not in (0,1,False,True): |
|
788 | if val not in (0,1,False,True): | |
789 | raise ValueError,'new call_pdb value must be boolean' |
|
789 | raise ValueError,'new call_pdb value must be boolean' | |
790 |
|
790 | |||
791 | # store value in instance |
|
791 | # store value in instance | |
792 | self._call_pdb = val |
|
792 | self._call_pdb = val | |
793 |
|
793 | |||
794 | # notify the actual exception handlers |
|
794 | # notify the actual exception handlers | |
795 | self.InteractiveTB.call_pdb = val |
|
795 | self.InteractiveTB.call_pdb = val | |
796 | if self.isthreaded: |
|
796 | if self.isthreaded: | |
797 | try: |
|
797 | try: | |
798 | self.sys_excepthook.call_pdb = val |
|
798 | self.sys_excepthook.call_pdb = val | |
799 | except: |
|
799 | except: | |
800 | warn('Failed to activate pdb for threaded exception handler') |
|
800 | warn('Failed to activate pdb for threaded exception handler') | |
801 |
|
801 | |||
802 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
802 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
803 | 'Control auto-activation of pdb at exceptions') |
|
803 | 'Control auto-activation of pdb at exceptions') | |
804 |
|
804 | |||
805 | def debugger(self,force=False): |
|
805 | def debugger(self,force=False): | |
806 | """Call the pydb/pdb debugger. |
|
806 | """Call the pydb/pdb debugger. | |
807 |
|
807 | |||
808 | Keywords: |
|
808 | Keywords: | |
809 |
|
809 | |||
810 | - force(False): by default, this routine checks the instance call_pdb |
|
810 | - force(False): by default, this routine checks the instance call_pdb | |
811 | flag and does not actually invoke the debugger if the flag is false. |
|
811 | flag and does not actually invoke the debugger if the flag is false. | |
812 | The 'force' option forces the debugger to activate even if the flag |
|
812 | The 'force' option forces the debugger to activate even if the flag | |
813 | is false. |
|
813 | is false. | |
814 | """ |
|
814 | """ | |
815 |
|
815 | |||
816 | if not (force or self.call_pdb): |
|
816 | if not (force or self.call_pdb): | |
817 | return |
|
817 | return | |
818 |
|
818 | |||
819 | if not hasattr(sys,'last_traceback'): |
|
819 | if not hasattr(sys,'last_traceback'): | |
820 | error('No traceback has been produced, nothing to debug.') |
|
820 | error('No traceback has been produced, nothing to debug.') | |
821 | return |
|
821 | return | |
822 |
|
822 | |||
823 | # use pydb if available |
|
823 | # use pydb if available | |
824 | if debugger.has_pydb: |
|
824 | if debugger.has_pydb: | |
825 | from pydb import pm |
|
825 | from pydb import pm | |
826 | else: |
|
826 | else: | |
827 | # fallback to our internal debugger |
|
827 | # fallback to our internal debugger | |
828 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
828 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
829 | self.history_saving_wrapper(pm)() |
|
829 | self.history_saving_wrapper(pm)() | |
830 |
|
830 | |||
831 | #------------------------------------------------------------------------- |
|
831 | #------------------------------------------------------------------------- | |
832 | # Things related to IPython's various namespaces |
|
832 | # Things related to IPython's various namespaces | |
833 | #------------------------------------------------------------------------- |
|
833 | #------------------------------------------------------------------------- | |
834 |
|
834 | |||
835 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
835 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
836 | # Create the namespace where the user will operate. user_ns is |
|
836 | # Create the namespace where the user will operate. user_ns is | |
837 | # normally the only one used, and it is passed to the exec calls as |
|
837 | # normally the only one used, and it is passed to the exec calls as | |
838 | # the locals argument. But we do carry a user_global_ns namespace |
|
838 | # the locals argument. But we do carry a user_global_ns namespace | |
839 | # given as the exec 'globals' argument, This is useful in embedding |
|
839 | # given as the exec 'globals' argument, This is useful in embedding | |
840 | # situations where the ipython shell opens in a context where the |
|
840 | # situations where the ipython shell opens in a context where the | |
841 | # distinction between locals and globals is meaningful. For |
|
841 | # distinction between locals and globals is meaningful. For | |
842 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
842 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
843 |
|
843 | |||
844 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
844 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
845 | # level as a dict instead of a module. This is a manual fix, but I |
|
845 | # level as a dict instead of a module. This is a manual fix, but I | |
846 | # should really track down where the problem is coming from. Alex |
|
846 | # should really track down where the problem is coming from. Alex | |
847 | # Schmolck reported this problem first. |
|
847 | # Schmolck reported this problem first. | |
848 |
|
848 | |||
849 | # A useful post by Alex Martelli on this topic: |
|
849 | # A useful post by Alex Martelli on this topic: | |
850 | # Re: inconsistent value from __builtins__ |
|
850 | # Re: inconsistent value from __builtins__ | |
851 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
851 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
852 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
852 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
853 | # Gruppen: comp.lang.python |
|
853 | # Gruppen: comp.lang.python | |
854 |
|
854 | |||
855 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
855 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
856 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
856 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
857 | # > <type 'dict'> |
|
857 | # > <type 'dict'> | |
858 | # > >>> print type(__builtins__) |
|
858 | # > >>> print type(__builtins__) | |
859 | # > <type 'module'> |
|
859 | # > <type 'module'> | |
860 | # > Is this difference in return value intentional? |
|
860 | # > Is this difference in return value intentional? | |
861 |
|
861 | |||
862 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
862 | # Well, it's documented that '__builtins__' can be either a dictionary | |
863 | # or a module, and it's been that way for a long time. Whether it's |
|
863 | # or a module, and it's been that way for a long time. Whether it's | |
864 | # intentional (or sensible), I don't know. In any case, the idea is |
|
864 | # intentional (or sensible), I don't know. In any case, the idea is | |
865 | # that if you need to access the built-in namespace directly, you |
|
865 | # that if you need to access the built-in namespace directly, you | |
866 | # should start with "import __builtin__" (note, no 's') which will |
|
866 | # should start with "import __builtin__" (note, no 's') which will | |
867 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
867 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
868 |
|
868 | |||
869 | # These routines return properly built dicts as needed by the rest of |
|
869 | # These routines return properly built dicts as needed by the rest of | |
870 | # the code, and can also be used by extension writers to generate |
|
870 | # the code, and can also be used by extension writers to generate | |
871 | # properly initialized namespaces. |
|
871 | # properly initialized namespaces. | |
872 | user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns) |
|
872 | user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns) | |
873 |
|
873 | |||
874 | # Assign namespaces |
|
874 | # Assign namespaces | |
875 | # This is the namespace where all normal user variables live |
|
875 | # This is the namespace where all normal user variables live | |
876 | self.user_ns = user_ns |
|
876 | self.user_ns = user_ns | |
877 | self.user_global_ns = user_global_ns |
|
877 | self.user_global_ns = user_global_ns | |
878 |
|
878 | |||
879 | # An auxiliary namespace that checks what parts of the user_ns were |
|
879 | # An auxiliary namespace that checks what parts of the user_ns were | |
880 | # loaded at startup, so we can list later only variables defined in |
|
880 | # loaded at startup, so we can list later only variables defined in | |
881 | # actual interactive use. Since it is always a subset of user_ns, it |
|
881 | # actual interactive use. Since it is always a subset of user_ns, it | |
882 | # doesn't need to be separately tracked in the ns_table. |
|
882 | # doesn't need to be separately tracked in the ns_table. | |
883 | self.user_config_ns = {} |
|
883 | self.user_config_ns = {} | |
884 |
|
884 | |||
885 | # A namespace to keep track of internal data structures to prevent |
|
885 | # A namespace to keep track of internal data structures to prevent | |
886 | # them from cluttering user-visible stuff. Will be updated later |
|
886 | # them from cluttering user-visible stuff. Will be updated later | |
887 | self.internal_ns = {} |
|
887 | self.internal_ns = {} | |
888 |
|
888 | |||
889 | # Now that FakeModule produces a real module, we've run into a nasty |
|
889 | # Now that FakeModule produces a real module, we've run into a nasty | |
890 | # problem: after script execution (via %run), the module where the user |
|
890 | # problem: after script execution (via %run), the module where the user | |
891 | # code ran is deleted. Now that this object is a true module (needed |
|
891 | # code ran is deleted. Now that this object is a true module (needed | |
892 | # so docetst and other tools work correctly), the Python module |
|
892 | # so docetst and other tools work correctly), the Python module | |
893 | # teardown mechanism runs over it, and sets to None every variable |
|
893 | # teardown mechanism runs over it, and sets to None every variable | |
894 | # present in that module. Top-level references to objects from the |
|
894 | # present in that module. Top-level references to objects from the | |
895 | # script survive, because the user_ns is updated with them. However, |
|
895 | # script survive, because the user_ns is updated with them. However, | |
896 | # calling functions defined in the script that use other things from |
|
896 | # calling functions defined in the script that use other things from | |
897 | # the script will fail, because the function's closure had references |
|
897 | # the script will fail, because the function's closure had references | |
898 | # to the original objects, which are now all None. So we must protect |
|
898 | # to the original objects, which are now all None. So we must protect | |
899 | # these modules from deletion by keeping a cache. |
|
899 | # these modules from deletion by keeping a cache. | |
900 | # |
|
900 | # | |
901 | # To avoid keeping stale modules around (we only need the one from the |
|
901 | # To avoid keeping stale modules around (we only need the one from the | |
902 | # last run), we use a dict keyed with the full path to the script, so |
|
902 | # last run), we use a dict keyed with the full path to the script, so | |
903 | # only the last version of the module is held in the cache. Note, |
|
903 | # only the last version of the module is held in the cache. Note, | |
904 | # however, that we must cache the module *namespace contents* (their |
|
904 | # however, that we must cache the module *namespace contents* (their | |
905 | # __dict__). Because if we try to cache the actual modules, old ones |
|
905 | # __dict__). Because if we try to cache the actual modules, old ones | |
906 | # (uncached) could be destroyed while still holding references (such as |
|
906 | # (uncached) could be destroyed while still holding references (such as | |
907 | # those held by GUI objects that tend to be long-lived)> |
|
907 | # those held by GUI objects that tend to be long-lived)> | |
908 | # |
|
908 | # | |
909 | # The %reset command will flush this cache. See the cache_main_mod() |
|
909 | # The %reset command will flush this cache. See the cache_main_mod() | |
910 | # and clear_main_mod_cache() methods for details on use. |
|
910 | # and clear_main_mod_cache() methods for details on use. | |
911 |
|
911 | |||
912 | # This is the cache used for 'main' namespaces |
|
912 | # This is the cache used for 'main' namespaces | |
913 | self._main_ns_cache = {} |
|
913 | self._main_ns_cache = {} | |
914 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
914 | # And this is the single instance of FakeModule whose __dict__ we keep | |
915 | # copying and clearing for reuse on each %run |
|
915 | # copying and clearing for reuse on each %run | |
916 | self._user_main_module = FakeModule() |
|
916 | self._user_main_module = FakeModule() | |
917 |
|
917 | |||
918 | # A table holding all the namespaces IPython deals with, so that |
|
918 | # A table holding all the namespaces IPython deals with, so that | |
919 | # introspection facilities can search easily. |
|
919 | # introspection facilities can search easily. | |
920 | self.ns_table = {'user':user_ns, |
|
920 | self.ns_table = {'user':user_ns, | |
921 | 'user_global':user_global_ns, |
|
921 | 'user_global':user_global_ns, | |
922 | 'internal':self.internal_ns, |
|
922 | 'internal':self.internal_ns, | |
923 | 'builtin':__builtin__.__dict__ |
|
923 | 'builtin':__builtin__.__dict__ | |
924 | } |
|
924 | } | |
925 |
|
925 | |||
926 | # Similarly, track all namespaces where references can be held and that |
|
926 | # Similarly, track all namespaces where references can be held and that | |
927 | # we can safely clear (so it can NOT include builtin). This one can be |
|
927 | # we can safely clear (so it can NOT include builtin). This one can be | |
928 | # a simple list. |
|
928 | # a simple list. | |
929 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
929 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
930 | self.internal_ns, self._main_ns_cache ] |
|
930 | self.internal_ns, self._main_ns_cache ] | |
931 |
|
931 | |||
932 | def init_sys_modules(self): |
|
932 | def init_sys_modules(self): | |
933 | # We need to insert into sys.modules something that looks like a |
|
933 | # We need to insert into sys.modules something that looks like a | |
934 | # module but which accesses the IPython namespace, for shelve and |
|
934 | # module but which accesses the IPython namespace, for shelve and | |
935 | # pickle to work interactively. Normally they rely on getting |
|
935 | # pickle to work interactively. Normally they rely on getting | |
936 | # everything out of __main__, but for embedding purposes each IPython |
|
936 | # everything out of __main__, but for embedding purposes each IPython | |
937 | # instance has its own private namespace, so we can't go shoving |
|
937 | # instance has its own private namespace, so we can't go shoving | |
938 | # everything into __main__. |
|
938 | # everything into __main__. | |
939 |
|
939 | |||
940 | # note, however, that we should only do this for non-embedded |
|
940 | # note, however, that we should only do this for non-embedded | |
941 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
941 | # ipythons, which really mimic the __main__.__dict__ with their own | |
942 | # namespace. Embedded instances, on the other hand, should not do |
|
942 | # namespace. Embedded instances, on the other hand, should not do | |
943 | # this because they need to manage the user local/global namespaces |
|
943 | # this because they need to manage the user local/global namespaces | |
944 | # only, but they live within a 'normal' __main__ (meaning, they |
|
944 | # only, but they live within a 'normal' __main__ (meaning, they | |
945 | # shouldn't overtake the execution environment of the script they're |
|
945 | # shouldn't overtake the execution environment of the script they're | |
946 | # embedded in). |
|
946 | # embedded in). | |
947 |
|
947 | |||
948 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
948 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
949 |
|
949 | |||
950 | try: |
|
950 | try: | |
951 | main_name = self.user_ns['__name__'] |
|
951 | main_name = self.user_ns['__name__'] | |
952 | except KeyError: |
|
952 | except KeyError: | |
953 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
953 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
954 | else: |
|
954 | else: | |
955 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
955 | sys.modules[main_name] = FakeModule(self.user_ns) | |
956 |
|
956 | |||
957 | def init_user_ns(self): |
|
957 | def init_user_ns(self): | |
958 | """Initialize all user-visible namespaces to their minimum defaults. |
|
958 | """Initialize all user-visible namespaces to their minimum defaults. | |
959 |
|
959 | |||
960 | Certain history lists are also initialized here, as they effectively |
|
960 | Certain history lists are also initialized here, as they effectively | |
961 | act as user namespaces. |
|
961 | act as user namespaces. | |
962 |
|
962 | |||
963 | Notes |
|
963 | Notes | |
964 | ----- |
|
964 | ----- | |
965 | All data structures here are only filled in, they are NOT reset by this |
|
965 | All data structures here are only filled in, they are NOT reset by this | |
966 | method. If they were not empty before, data will simply be added to |
|
966 | method. If they were not empty before, data will simply be added to | |
967 | therm. |
|
967 | therm. | |
968 | """ |
|
968 | """ | |
969 | # This function works in two parts: first we put a few things in |
|
969 | # This function works in two parts: first we put a few things in | |
970 | # user_ns, and we sync that contents into user_config_ns so that these |
|
970 | # user_ns, and we sync that contents into user_config_ns so that these | |
971 | # initial variables aren't shown by %who. After the sync, we add the |
|
971 | # initial variables aren't shown by %who. After the sync, we add the | |
972 | # rest of what we *do* want the user to see with %who even on a new |
|
972 | # rest of what we *do* want the user to see with %who even on a new | |
973 | # session. |
|
973 | # session. | |
974 | ns = {} |
|
974 | ns = {} | |
975 |
|
975 | |||
976 | # Put 'help' in the user namespace |
|
976 | # Put 'help' in the user namespace | |
977 | try: |
|
977 | try: | |
978 | from site import _Helper |
|
978 | from site import _Helper | |
979 | ns['help'] = _Helper() |
|
979 | ns['help'] = _Helper() | |
980 | except ImportError: |
|
980 | except ImportError: | |
981 | warn('help() not available - check site.py') |
|
981 | warn('help() not available - check site.py') | |
982 |
|
982 | |||
983 | # make global variables for user access to the histories |
|
983 | # make global variables for user access to the histories | |
984 | ns['_ih'] = self.input_hist |
|
984 | ns['_ih'] = self.input_hist | |
985 | ns['_oh'] = self.output_hist |
|
985 | ns['_oh'] = self.output_hist | |
986 | ns['_dh'] = self.dir_hist |
|
986 | ns['_dh'] = self.dir_hist | |
987 |
|
987 | |||
988 | ns['_sh'] = shadowns |
|
988 | ns['_sh'] = shadowns | |
989 |
|
989 | |||
990 | # Sync what we've added so far to user_config_ns so these aren't seen |
|
990 | # Sync what we've added so far to user_config_ns so these aren't seen | |
991 | # by %who |
|
991 | # by %who | |
992 | self.user_config_ns.update(ns) |
|
992 | self.user_config_ns.update(ns) | |
993 |
|
993 | |||
994 | # Now, continue adding more contents |
|
994 | # Now, continue adding more contents | |
995 |
|
995 | |||
996 | # user aliases to input and output histories |
|
996 | # user aliases to input and output histories | |
997 | ns['In'] = self.input_hist |
|
997 | ns['In'] = self.input_hist | |
998 | ns['Out'] = self.output_hist |
|
998 | ns['Out'] = self.output_hist | |
999 |
|
999 | |||
1000 | # Store myself as the public api!!! |
|
1000 | # Store myself as the public api!!! | |
1001 | ns['get_ipython'] = self.get_ipython |
|
1001 | ns['get_ipython'] = self.get_ipython | |
1002 |
|
1002 | |||
1003 | # And update the real user's namespace |
|
1003 | # And update the real user's namespace | |
1004 | self.user_ns.update(ns) |
|
1004 | self.user_ns.update(ns) | |
1005 |
|
1005 | |||
1006 |
|
1006 | |||
1007 | def reset(self): |
|
1007 | def reset(self): | |
1008 | """Clear all internal namespaces. |
|
1008 | """Clear all internal namespaces. | |
1009 |
|
1009 | |||
1010 | Note that this is much more aggressive than %reset, since it clears |
|
1010 | Note that this is much more aggressive than %reset, since it clears | |
1011 | fully all namespaces, as well as all input/output lists. |
|
1011 | fully all namespaces, as well as all input/output lists. | |
1012 | """ |
|
1012 | """ | |
1013 | for ns in self.ns_refs_table: |
|
1013 | for ns in self.ns_refs_table: | |
1014 | ns.clear() |
|
1014 | ns.clear() | |
1015 |
|
1015 | |||
1016 | self.alias_manager.clear_aliases() |
|
1016 | self.alias_manager.clear_aliases() | |
1017 |
|
1017 | |||
1018 | # Clear input and output histories |
|
1018 | # Clear input and output histories | |
1019 | self.input_hist[:] = [] |
|
1019 | self.input_hist[:] = [] | |
1020 | self.input_hist_raw[:] = [] |
|
1020 | self.input_hist_raw[:] = [] | |
1021 | self.output_hist.clear() |
|
1021 | self.output_hist.clear() | |
1022 |
|
1022 | |||
1023 | # Restore the user namespaces to minimal usability |
|
1023 | # Restore the user namespaces to minimal usability | |
1024 | self.init_user_ns() |
|
1024 | self.init_user_ns() | |
1025 |
|
1025 | |||
1026 | # Restore the default and user aliases |
|
1026 | # Restore the default and user aliases | |
1027 | self.alias_manager.init_aliases() |
|
1027 | self.alias_manager.init_aliases() | |
1028 |
|
1028 | |||
1029 | def push(self, variables, interactive=True): |
|
1029 | def push(self, variables, interactive=True): | |
1030 | """Inject a group of variables into the IPython user namespace. |
|
1030 | """Inject a group of variables into the IPython user namespace. | |
1031 |
|
1031 | |||
1032 | Parameters |
|
1032 | Parameters | |
1033 | ---------- |
|
1033 | ---------- | |
1034 | variables : dict, str or list/tuple of str |
|
1034 | variables : dict, str or list/tuple of str | |
1035 | The variables to inject into the user's namespace. If a dict, |
|
1035 | The variables to inject into the user's namespace. If a dict, | |
1036 | a simple update is done. If a str, the string is assumed to |
|
1036 | a simple update is done. If a str, the string is assumed to | |
1037 | have variable names separated by spaces. A list/tuple of str |
|
1037 | have variable names separated by spaces. A list/tuple of str | |
1038 | can also be used to give the variable names. If just the variable |
|
1038 | can also be used to give the variable names. If just the variable | |
1039 | names are give (list/tuple/str) then the variable values looked |
|
1039 | names are give (list/tuple/str) then the variable values looked | |
1040 | up in the callers frame. |
|
1040 | up in the callers frame. | |
1041 | interactive : bool |
|
1041 | interactive : bool | |
1042 | If True (default), the variables will be listed with the ``who`` |
|
1042 | If True (default), the variables will be listed with the ``who`` | |
1043 | magic. |
|
1043 | magic. | |
1044 | """ |
|
1044 | """ | |
1045 | vdict = None |
|
1045 | vdict = None | |
1046 |
|
1046 | |||
1047 | # We need a dict of name/value pairs to do namespace updates. |
|
1047 | # We need a dict of name/value pairs to do namespace updates. | |
1048 | if isinstance(variables, dict): |
|
1048 | if isinstance(variables, dict): | |
1049 | vdict = variables |
|
1049 | vdict = variables | |
1050 | elif isinstance(variables, (basestring, list, tuple)): |
|
1050 | elif isinstance(variables, (basestring, list, tuple)): | |
1051 | if isinstance(variables, basestring): |
|
1051 | if isinstance(variables, basestring): | |
1052 | vlist = variables.split() |
|
1052 | vlist = variables.split() | |
1053 | else: |
|
1053 | else: | |
1054 | vlist = variables |
|
1054 | vlist = variables | |
1055 | vdict = {} |
|
1055 | vdict = {} | |
1056 | cf = sys._getframe(1) |
|
1056 | cf = sys._getframe(1) | |
1057 | for name in vlist: |
|
1057 | for name in vlist: | |
1058 | try: |
|
1058 | try: | |
1059 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1059 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1060 | except: |
|
1060 | except: | |
1061 | print ('Could not get variable %s from %s' % |
|
1061 | print ('Could not get variable %s from %s' % | |
1062 | (name,cf.f_code.co_name)) |
|
1062 | (name,cf.f_code.co_name)) | |
1063 | else: |
|
1063 | else: | |
1064 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1064 | raise ValueError('variables must be a dict/str/list/tuple') | |
1065 |
|
1065 | |||
1066 | # Propagate variables to user namespace |
|
1066 | # Propagate variables to user namespace | |
1067 | self.user_ns.update(vdict) |
|
1067 | self.user_ns.update(vdict) | |
1068 |
|
1068 | |||
1069 | # And configure interactive visibility |
|
1069 | # And configure interactive visibility | |
1070 | config_ns = self.user_config_ns |
|
1070 | config_ns = self.user_config_ns | |
1071 | if interactive: |
|
1071 | if interactive: | |
1072 | for name, val in vdict.iteritems(): |
|
1072 | for name, val in vdict.iteritems(): | |
1073 | config_ns.pop(name, None) |
|
1073 | config_ns.pop(name, None) | |
1074 | else: |
|
1074 | else: | |
1075 | for name,val in vdict.iteritems(): |
|
1075 | for name,val in vdict.iteritems(): | |
1076 | config_ns[name] = val |
|
1076 | config_ns[name] = val | |
1077 |
|
1077 | |||
1078 | #------------------------------------------------------------------------- |
|
1078 | #------------------------------------------------------------------------- | |
1079 | # Things related to history management |
|
1079 | # Things related to history management | |
1080 | #------------------------------------------------------------------------- |
|
1080 | #------------------------------------------------------------------------- | |
1081 |
|
1081 | |||
1082 | def init_history(self): |
|
1082 | def init_history(self): | |
1083 | # List of input with multi-line handling. |
|
1083 | # List of input with multi-line handling. | |
1084 | self.input_hist = InputList() |
|
1084 | self.input_hist = InputList() | |
1085 | # This one will hold the 'raw' input history, without any |
|
1085 | # This one will hold the 'raw' input history, without any | |
1086 | # pre-processing. This will allow users to retrieve the input just as |
|
1086 | # pre-processing. This will allow users to retrieve the input just as | |
1087 | # it was exactly typed in by the user, with %hist -r. |
|
1087 | # it was exactly typed in by the user, with %hist -r. | |
1088 | self.input_hist_raw = InputList() |
|
1088 | self.input_hist_raw = InputList() | |
1089 |
|
1089 | |||
1090 | # list of visited directories |
|
1090 | # list of visited directories | |
1091 | try: |
|
1091 | try: | |
1092 | self.dir_hist = [os.getcwd()] |
|
1092 | self.dir_hist = [os.getcwd()] | |
1093 | except OSError: |
|
1093 | except OSError: | |
1094 | self.dir_hist = [] |
|
1094 | self.dir_hist = [] | |
1095 |
|
1095 | |||
1096 | # dict of output history |
|
1096 | # dict of output history | |
1097 | self.output_hist = {} |
|
1097 | self.output_hist = {} | |
1098 |
|
1098 | |||
1099 | # Now the history file |
|
1099 | # Now the history file | |
1100 | if self.profile: |
|
1100 | if self.profile: | |
1101 | histfname = 'history-%s' % self.profile |
|
1101 | histfname = 'history-%s' % self.profile | |
1102 | else: |
|
1102 | else: | |
1103 | histfname = 'history' |
|
1103 | histfname = 'history' | |
1104 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1104 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1105 |
|
1105 | |||
1106 | # Fill the history zero entry, user counter starts at 1 |
|
1106 | # Fill the history zero entry, user counter starts at 1 | |
1107 | self.input_hist.append('\n') |
|
1107 | self.input_hist.append('\n') | |
1108 | self.input_hist_raw.append('\n') |
|
1108 | self.input_hist_raw.append('\n') | |
1109 |
|
1109 | |||
1110 | def init_shadow_hist(self): |
|
1110 | def init_shadow_hist(self): | |
1111 | try: |
|
1111 | try: | |
1112 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1112 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1113 | except exceptions.UnicodeDecodeError: |
|
1113 | except exceptions.UnicodeDecodeError: | |
1114 | print "Your ipython_dir can't be decoded to unicode!" |
|
1114 | print "Your ipython_dir can't be decoded to unicode!" | |
1115 | print "Please set HOME environment variable to something that" |
|
1115 | print "Please set HOME environment variable to something that" | |
1116 | print r"only has ASCII characters, e.g. c:\home" |
|
1116 | print r"only has ASCII characters, e.g. c:\home" | |
1117 | print "Now it is", self.ipython_dir |
|
1117 | print "Now it is", self.ipython_dir | |
1118 | sys.exit() |
|
1118 | sys.exit() | |
1119 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1119 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1120 |
|
1120 | |||
1121 | def savehist(self): |
|
1121 | def savehist(self): | |
1122 | """Save input history to a file (via readline library).""" |
|
1122 | """Save input history to a file (via readline library).""" | |
1123 |
|
1123 | |||
1124 | try: |
|
1124 | try: | |
1125 | self.readline.write_history_file(self.histfile) |
|
1125 | self.readline.write_history_file(self.histfile) | |
1126 | except: |
|
1126 | except: | |
1127 | print 'Unable to save IPython command history to file: ' + \ |
|
1127 | print 'Unable to save IPython command history to file: ' + \ | |
1128 | `self.histfile` |
|
1128 | `self.histfile` | |
1129 |
|
1129 | |||
1130 | def reloadhist(self): |
|
1130 | def reloadhist(self): | |
1131 | """Reload the input history from disk file.""" |
|
1131 | """Reload the input history from disk file.""" | |
1132 |
|
1132 | |||
1133 | try: |
|
1133 | try: | |
1134 | self.readline.clear_history() |
|
1134 | self.readline.clear_history() | |
1135 | self.readline.read_history_file(self.shell.histfile) |
|
1135 | self.readline.read_history_file(self.shell.histfile) | |
1136 | except AttributeError: |
|
1136 | except AttributeError: | |
1137 | pass |
|
1137 | pass | |
1138 |
|
1138 | |||
1139 | def history_saving_wrapper(self, func): |
|
1139 | def history_saving_wrapper(self, func): | |
1140 | """ Wrap func for readline history saving |
|
1140 | """ Wrap func for readline history saving | |
1141 |
|
1141 | |||
1142 | Convert func into callable that saves & restores |
|
1142 | Convert func into callable that saves & restores | |
1143 | history around the call """ |
|
1143 | history around the call """ | |
1144 |
|
1144 | |||
1145 | if not self.has_readline: |
|
1145 | if not self.has_readline: | |
1146 | return func |
|
1146 | return func | |
1147 |
|
1147 | |||
1148 | def wrapper(): |
|
1148 | def wrapper(): | |
1149 | self.savehist() |
|
1149 | self.savehist() | |
1150 | try: |
|
1150 | try: | |
1151 | func() |
|
1151 | func() | |
1152 | finally: |
|
1152 | finally: | |
1153 | readline.read_history_file(self.histfile) |
|
1153 | readline.read_history_file(self.histfile) | |
1154 | return wrapper |
|
1154 | return wrapper | |
1155 |
|
1155 | |||
1156 | #------------------------------------------------------------------------- |
|
1156 | #------------------------------------------------------------------------- | |
1157 | # Things related to exception handling and tracebacks (not debugging) |
|
1157 | # Things related to exception handling and tracebacks (not debugging) | |
1158 | #------------------------------------------------------------------------- |
|
1158 | #------------------------------------------------------------------------- | |
1159 |
|
1159 | |||
1160 | def init_traceback_handlers(self, custom_exceptions): |
|
1160 | def init_traceback_handlers(self, custom_exceptions): | |
1161 | # Syntax error handler. |
|
1161 | # Syntax error handler. | |
1162 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1162 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
1163 |
|
1163 | |||
1164 | # The interactive one is initialized with an offset, meaning we always |
|
1164 | # The interactive one is initialized with an offset, meaning we always | |
1165 | # want to remove the topmost item in the traceback, which is our own |
|
1165 | # want to remove the topmost item in the traceback, which is our own | |
1166 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1166 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1167 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1167 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1168 | color_scheme='NoColor', |
|
1168 | color_scheme='NoColor', | |
1169 | tb_offset = 1) |
|
1169 | tb_offset = 1) | |
1170 |
|
1170 | |||
1171 | # The instance will store a pointer to the system-wide exception hook, |
|
1171 | # The instance will store a pointer to the system-wide exception hook, | |
1172 | # so that runtime code (such as magics) can access it. This is because |
|
1172 | # so that runtime code (such as magics) can access it. This is because | |
1173 | # during the read-eval loop, it may get temporarily overwritten. |
|
1173 | # during the read-eval loop, it may get temporarily overwritten. | |
1174 | self.sys_excepthook = sys.excepthook |
|
1174 | self.sys_excepthook = sys.excepthook | |
1175 |
|
1175 | |||
1176 | # and add any custom exception handlers the user may have specified |
|
1176 | # and add any custom exception handlers the user may have specified | |
1177 | self.set_custom_exc(*custom_exceptions) |
|
1177 | self.set_custom_exc(*custom_exceptions) | |
1178 |
|
1178 | |||
1179 | def set_custom_exc(self,exc_tuple,handler): |
|
1179 | def set_custom_exc(self,exc_tuple,handler): | |
1180 | """set_custom_exc(exc_tuple,handler) |
|
1180 | """set_custom_exc(exc_tuple,handler) | |
1181 |
|
1181 | |||
1182 | Set a custom exception handler, which will be called if any of the |
|
1182 | Set a custom exception handler, which will be called if any of the | |
1183 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1183 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1184 | runcode() method. |
|
1184 | runcode() method. | |
1185 |
|
1185 | |||
1186 | Inputs: |
|
1186 | Inputs: | |
1187 |
|
1187 | |||
1188 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1188 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1189 | handler for. It is very important that you use a tuple, and NOT A |
|
1189 | handler for. It is very important that you use a tuple, and NOT A | |
1190 | LIST here, because of the way Python's except statement works. If |
|
1190 | LIST here, because of the way Python's except statement works. If | |
1191 | you only want to trap a single exception, use a singleton tuple: |
|
1191 | you only want to trap a single exception, use a singleton tuple: | |
1192 |
|
1192 | |||
1193 | exc_tuple == (MyCustomException,) |
|
1193 | exc_tuple == (MyCustomException,) | |
1194 |
|
1194 | |||
1195 | - handler: this must be defined as a function with the following |
|
1195 | - handler: this must be defined as a function with the following | |
1196 | basic interface: def my_handler(self,etype,value,tb). |
|
1196 | basic interface: def my_handler(self,etype,value,tb). | |
1197 |
|
1197 | |||
1198 | This will be made into an instance method (via new.instancemethod) |
|
1198 | This will be made into an instance method (via new.instancemethod) | |
1199 | of IPython itself, and it will be called if any of the exceptions |
|
1199 | of IPython itself, and it will be called if any of the exceptions | |
1200 | listed in the exc_tuple are caught. If the handler is None, an |
|
1200 | listed in the exc_tuple are caught. If the handler is None, an | |
1201 | internal basic one is used, which just prints basic info. |
|
1201 | internal basic one is used, which just prints basic info. | |
1202 |
|
1202 | |||
1203 | WARNING: by putting in your own exception handler into IPython's main |
|
1203 | WARNING: by putting in your own exception handler into IPython's main | |
1204 | execution loop, you run a very good chance of nasty crashes. This |
|
1204 | execution loop, you run a very good chance of nasty crashes. This | |
1205 | facility should only be used if you really know what you are doing.""" |
|
1205 | facility should only be used if you really know what you are doing.""" | |
1206 |
|
1206 | |||
1207 | assert type(exc_tuple)==type(()) , \ |
|
1207 | assert type(exc_tuple)==type(()) , \ | |
1208 | "The custom exceptions must be given AS A TUPLE." |
|
1208 | "The custom exceptions must be given AS A TUPLE." | |
1209 |
|
1209 | |||
1210 | def dummy_handler(self,etype,value,tb): |
|
1210 | def dummy_handler(self,etype,value,tb): | |
1211 | print '*** Simple custom exception handler ***' |
|
1211 | print '*** Simple custom exception handler ***' | |
1212 | print 'Exception type :',etype |
|
1212 | print 'Exception type :',etype | |
1213 | print 'Exception value:',value |
|
1213 | print 'Exception value:',value | |
1214 | print 'Traceback :',tb |
|
1214 | print 'Traceback :',tb | |
1215 | print 'Source code :','\n'.join(self.buffer) |
|
1215 | print 'Source code :','\n'.join(self.buffer) | |
1216 |
|
1216 | |||
1217 | if handler is None: handler = dummy_handler |
|
1217 | if handler is None: handler = dummy_handler | |
1218 |
|
1218 | |||
1219 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1219 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1220 | self.custom_exceptions = exc_tuple |
|
1220 | self.custom_exceptions = exc_tuple | |
1221 |
|
1221 | |||
1222 | def excepthook(self, etype, value, tb): |
|
1222 | def excepthook(self, etype, value, tb): | |
1223 | """One more defense for GUI apps that call sys.excepthook. |
|
1223 | """One more defense for GUI apps that call sys.excepthook. | |
1224 |
|
1224 | |||
1225 | GUI frameworks like wxPython trap exceptions and call |
|
1225 | GUI frameworks like wxPython trap exceptions and call | |
1226 | sys.excepthook themselves. I guess this is a feature that |
|
1226 | sys.excepthook themselves. I guess this is a feature that | |
1227 | enables them to keep running after exceptions that would |
|
1227 | enables them to keep running after exceptions that would | |
1228 | otherwise kill their mainloop. This is a bother for IPython |
|
1228 | otherwise kill their mainloop. This is a bother for IPython | |
1229 | which excepts to catch all of the program exceptions with a try: |
|
1229 | which excepts to catch all of the program exceptions with a try: | |
1230 | except: statement. |
|
1230 | except: statement. | |
1231 |
|
1231 | |||
1232 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1232 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1233 | any app directly invokes sys.excepthook, it will look to the user like |
|
1233 | any app directly invokes sys.excepthook, it will look to the user like | |
1234 | IPython crashed. In order to work around this, we can disable the |
|
1234 | IPython crashed. In order to work around this, we can disable the | |
1235 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1235 | CrashHandler and replace it with this excepthook instead, which prints a | |
1236 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1236 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1237 | call sys.excepthook will generate a regular-looking exception from |
|
1237 | call sys.excepthook will generate a regular-looking exception from | |
1238 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1238 | IPython, and the CrashHandler will only be triggered by real IPython | |
1239 | crashes. |
|
1239 | crashes. | |
1240 |
|
1240 | |||
1241 | This hook should be used sparingly, only in places which are not likely |
|
1241 | This hook should be used sparingly, only in places which are not likely | |
1242 | to be true IPython errors. |
|
1242 | to be true IPython errors. | |
1243 | """ |
|
1243 | """ | |
1244 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1244 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1245 |
|
1245 | |||
1246 |
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None |
|
1246 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
|
1247 | exception_only=False): | |||
1247 | """Display the exception that just occurred. |
|
1248 | """Display the exception that just occurred. | |
1248 |
|
1249 | |||
1249 | If nothing is known about the exception, this is the method which |
|
1250 | If nothing is known about the exception, this is the method which | |
1250 | should be used throughout the code for presenting user tracebacks, |
|
1251 | should be used throughout the code for presenting user tracebacks, | |
1251 | rather than directly invoking the InteractiveTB object. |
|
1252 | rather than directly invoking the InteractiveTB object. | |
1252 |
|
1253 | |||
1253 | A specific showsyntaxerror() also exists, but this method can take |
|
1254 | A specific showsyntaxerror() also exists, but this method can take | |
1254 | care of calling it if needed, so unless you are explicitly catching a |
|
1255 | care of calling it if needed, so unless you are explicitly catching a | |
1255 | SyntaxError exception, don't try to analyze the stack manually and |
|
1256 | SyntaxError exception, don't try to analyze the stack manually and | |
1256 | simply call this method.""" |
|
1257 | simply call this method.""" | |
1257 |
|
1258 | |||
1258 |
|
||||
1259 | # Though this won't be called by syntax errors in the input line, |
|
|||
1260 | # there may be SyntaxError cases whith imported code. |
|
|||
1261 |
|
||||
1262 | try: |
|
1259 | try: | |
1263 | if exc_tuple is None: |
|
1260 | if exc_tuple is None: | |
1264 | etype, value, tb = sys.exc_info() |
|
1261 | etype, value, tb = sys.exc_info() | |
1265 | else: |
|
1262 | else: | |
1266 | etype, value, tb = exc_tuple |
|
1263 | etype, value, tb = exc_tuple | |
1267 |
|
1264 | |||
|
1265 | if etype is None: | |||
|
1266 | if hasattr(sys, 'last_type'): | |||
|
1267 | etype, value, tb = sys.last_type, sys.last_value, \ | |||
|
1268 | sys.last_traceback | |||
|
1269 | else: | |||
|
1270 | self.write('No traceback available to show.\n') | |||
|
1271 | return | |||
|
1272 | ||||
1268 | if etype is SyntaxError: |
|
1273 | if etype is SyntaxError: | |
|
1274 | # Though this won't be called by syntax errors in the input | |||
|
1275 | # line, there may be SyntaxError cases whith imported code. | |||
1269 | self.showsyntaxerror(filename) |
|
1276 | self.showsyntaxerror(filename) | |
1270 | elif etype is UsageError: |
|
1277 | elif etype is UsageError: | |
1271 | print "UsageError:", value |
|
1278 | print "UsageError:", value | |
1272 | else: |
|
1279 | else: | |
1273 | # WARNING: these variables are somewhat deprecated and not |
|
1280 | # WARNING: these variables are somewhat deprecated and not | |
1274 | # necessarily safe to use in a threaded environment, but tools |
|
1281 | # necessarily safe to use in a threaded environment, but tools | |
1275 | # like pdb depend on their existence, so let's set them. If we |
|
1282 | # like pdb depend on their existence, so let's set them. If we | |
1276 | # find problems in the field, we'll need to revisit their use. |
|
1283 | # find problems in the field, we'll need to revisit their use. | |
1277 | sys.last_type = etype |
|
1284 | sys.last_type = etype | |
1278 | sys.last_value = value |
|
1285 | sys.last_value = value | |
1279 | sys.last_traceback = tb |
|
1286 | sys.last_traceback = tb | |
1280 |
|
1287 | |||
1281 | if etype in self.custom_exceptions: |
|
1288 | if etype in self.custom_exceptions: | |
1282 | self.CustomTB(etype,value,tb) |
|
1289 | self.CustomTB(etype,value,tb) | |
1283 | else: |
|
1290 | else: | |
|
1291 | if exception_only: | |||
|
1292 | m = ('An exception has occurred, use %tb to see the ' | |||
|
1293 | 'full traceback.') | |||
|
1294 | print m | |||
|
1295 | self.InteractiveTB.show_exception_only(etype, value) | |||
|
1296 | else: | |||
1284 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1297 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1285 | if self.InteractiveTB.call_pdb: |
|
1298 | if self.InteractiveTB.call_pdb: | |
1286 | # pdb mucks up readline, fix it back |
|
1299 | # pdb mucks up readline, fix it back | |
1287 | self.set_completer() |
|
1300 | self.set_completer() | |
|
1301 | ||||
1288 | except KeyboardInterrupt: |
|
1302 | except KeyboardInterrupt: | |
1289 | self.write("\nKeyboardInterrupt\n") |
|
1303 | self.write("\nKeyboardInterrupt\n") | |
1290 |
|
1304 | |||
|
1305 | ||||
1291 | def showsyntaxerror(self, filename=None): |
|
1306 | def showsyntaxerror(self, filename=None): | |
1292 | """Display the syntax error that just occurred. |
|
1307 | """Display the syntax error that just occurred. | |
1293 |
|
1308 | |||
1294 | This doesn't display a stack trace because there isn't one. |
|
1309 | This doesn't display a stack trace because there isn't one. | |
1295 |
|
1310 | |||
1296 | If a filename is given, it is stuffed in the exception instead |
|
1311 | If a filename is given, it is stuffed in the exception instead | |
1297 | of what was there before (because Python's parser always uses |
|
1312 | of what was there before (because Python's parser always uses | |
1298 | "<string>" when reading from a string). |
|
1313 | "<string>" when reading from a string). | |
1299 | """ |
|
1314 | """ | |
1300 | etype, value, last_traceback = sys.exc_info() |
|
1315 | etype, value, last_traceback = sys.exc_info() | |
1301 |
|
1316 | |||
1302 |
# See note about these variables in showtraceback() |
|
1317 | # See note about these variables in showtraceback() above | |
1303 | sys.last_type = etype |
|
1318 | sys.last_type = etype | |
1304 | sys.last_value = value |
|
1319 | sys.last_value = value | |
1305 | sys.last_traceback = last_traceback |
|
1320 | sys.last_traceback = last_traceback | |
1306 |
|
1321 | |||
1307 | if filename and etype is SyntaxError: |
|
1322 | if filename and etype is SyntaxError: | |
1308 | # Work hard to stuff the correct filename in the exception |
|
1323 | # Work hard to stuff the correct filename in the exception | |
1309 | try: |
|
1324 | try: | |
1310 | msg, (dummy_filename, lineno, offset, line) = value |
|
1325 | msg, (dummy_filename, lineno, offset, line) = value | |
1311 | except: |
|
1326 | except: | |
1312 | # Not the format we expect; leave it alone |
|
1327 | # Not the format we expect; leave it alone | |
1313 | pass |
|
1328 | pass | |
1314 | else: |
|
1329 | else: | |
1315 | # Stuff in the right filename |
|
1330 | # Stuff in the right filename | |
1316 | try: |
|
1331 | try: | |
1317 | # Assume SyntaxError is a class exception |
|
1332 | # Assume SyntaxError is a class exception | |
1318 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1333 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1319 | except: |
|
1334 | except: | |
1320 | # If that failed, assume SyntaxError is a string |
|
1335 | # If that failed, assume SyntaxError is a string | |
1321 | value = msg, (filename, lineno, offset, line) |
|
1336 | value = msg, (filename, lineno, offset, line) | |
1322 | self.SyntaxTB(etype,value,[]) |
|
1337 | self.SyntaxTB(etype,value,[]) | |
1323 |
|
1338 | |||
1324 | def edit_syntax_error(self): |
|
1339 | def edit_syntax_error(self): | |
1325 | """The bottom half of the syntax error handler called in the main loop. |
|
1340 | """The bottom half of the syntax error handler called in the main loop. | |
1326 |
|
1341 | |||
1327 | Loop until syntax error is fixed or user cancels. |
|
1342 | Loop until syntax error is fixed or user cancels. | |
1328 | """ |
|
1343 | """ | |
1329 |
|
1344 | |||
1330 | while self.SyntaxTB.last_syntax_error: |
|
1345 | while self.SyntaxTB.last_syntax_error: | |
1331 | # copy and clear last_syntax_error |
|
1346 | # copy and clear last_syntax_error | |
1332 | err = self.SyntaxTB.clear_err_state() |
|
1347 | err = self.SyntaxTB.clear_err_state() | |
1333 | if not self._should_recompile(err): |
|
1348 | if not self._should_recompile(err): | |
1334 | return |
|
1349 | return | |
1335 | try: |
|
1350 | try: | |
1336 | # may set last_syntax_error again if a SyntaxError is raised |
|
1351 | # may set last_syntax_error again if a SyntaxError is raised | |
1337 | self.safe_execfile(err.filename,self.user_ns) |
|
1352 | self.safe_execfile(err.filename,self.user_ns) | |
1338 | except: |
|
1353 | except: | |
1339 | self.showtraceback() |
|
1354 | self.showtraceback() | |
1340 | else: |
|
1355 | else: | |
1341 | try: |
|
1356 | try: | |
1342 | f = file(err.filename) |
|
1357 | f = file(err.filename) | |
1343 | try: |
|
1358 | try: | |
1344 | # This should be inside a display_trap block and I |
|
1359 | # This should be inside a display_trap block and I | |
1345 | # think it is. |
|
1360 | # think it is. | |
1346 | sys.displayhook(f.read()) |
|
1361 | sys.displayhook(f.read()) | |
1347 | finally: |
|
1362 | finally: | |
1348 | f.close() |
|
1363 | f.close() | |
1349 | except: |
|
1364 | except: | |
1350 | self.showtraceback() |
|
1365 | self.showtraceback() | |
1351 |
|
1366 | |||
1352 | def _should_recompile(self,e): |
|
1367 | def _should_recompile(self,e): | |
1353 | """Utility routine for edit_syntax_error""" |
|
1368 | """Utility routine for edit_syntax_error""" | |
1354 |
|
1369 | |||
1355 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1370 | if e.filename in ('<ipython console>','<input>','<string>', | |
1356 | '<console>','<BackgroundJob compilation>', |
|
1371 | '<console>','<BackgroundJob compilation>', | |
1357 | None): |
|
1372 | None): | |
1358 |
|
1373 | |||
1359 | return False |
|
1374 | return False | |
1360 | try: |
|
1375 | try: | |
1361 | if (self.autoedit_syntax and |
|
1376 | if (self.autoedit_syntax and | |
1362 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1377 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1363 | '[Y/n] ','y')): |
|
1378 | '[Y/n] ','y')): | |
1364 | return False |
|
1379 | return False | |
1365 | except EOFError: |
|
1380 | except EOFError: | |
1366 | return False |
|
1381 | return False | |
1367 |
|
1382 | |||
1368 | def int0(x): |
|
1383 | def int0(x): | |
1369 | try: |
|
1384 | try: | |
1370 | return int(x) |
|
1385 | return int(x) | |
1371 | except TypeError: |
|
1386 | except TypeError: | |
1372 | return 0 |
|
1387 | return 0 | |
1373 | # always pass integer line and offset values to editor hook |
|
1388 | # always pass integer line and offset values to editor hook | |
1374 | try: |
|
1389 | try: | |
1375 | self.hooks.fix_error_editor(e.filename, |
|
1390 | self.hooks.fix_error_editor(e.filename, | |
1376 | int0(e.lineno),int0(e.offset),e.msg) |
|
1391 | int0(e.lineno),int0(e.offset),e.msg) | |
1377 | except TryNext: |
|
1392 | except TryNext: | |
1378 | warn('Could not open editor') |
|
1393 | warn('Could not open editor') | |
1379 | return False |
|
1394 | return False | |
1380 | return True |
|
1395 | return True | |
1381 |
|
1396 | |||
1382 | #------------------------------------------------------------------------- |
|
1397 | #------------------------------------------------------------------------- | |
1383 | # Things related to tab completion |
|
1398 | # Things related to tab completion | |
1384 | #------------------------------------------------------------------------- |
|
1399 | #------------------------------------------------------------------------- | |
1385 |
|
1400 | |||
1386 | def complete(self, text): |
|
1401 | def complete(self, text): | |
1387 | """Return a sorted list of all possible completions on text. |
|
1402 | """Return a sorted list of all possible completions on text. | |
1388 |
|
1403 | |||
1389 | Inputs: |
|
1404 | Inputs: | |
1390 |
|
1405 | |||
1391 | - text: a string of text to be completed on. |
|
1406 | - text: a string of text to be completed on. | |
1392 |
|
1407 | |||
1393 | This is a wrapper around the completion mechanism, similar to what |
|
1408 | This is a wrapper around the completion mechanism, similar to what | |
1394 | readline does at the command line when the TAB key is hit. By |
|
1409 | readline does at the command line when the TAB key is hit. By | |
1395 | exposing it as a method, it can be used by other non-readline |
|
1410 | exposing it as a method, it can be used by other non-readline | |
1396 | environments (such as GUIs) for text completion. |
|
1411 | environments (such as GUIs) for text completion. | |
1397 |
|
1412 | |||
1398 | Simple usage example: |
|
1413 | Simple usage example: | |
1399 |
|
1414 | |||
1400 | In [7]: x = 'hello' |
|
1415 | In [7]: x = 'hello' | |
1401 |
|
1416 | |||
1402 | In [8]: x |
|
1417 | In [8]: x | |
1403 | Out[8]: 'hello' |
|
1418 | Out[8]: 'hello' | |
1404 |
|
1419 | |||
1405 | In [9]: print x |
|
1420 | In [9]: print x | |
1406 | hello |
|
1421 | hello | |
1407 |
|
1422 | |||
1408 | In [10]: _ip.complete('x.l') |
|
1423 | In [10]: _ip.complete('x.l') | |
1409 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1424 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1410 | """ |
|
1425 | """ | |
1411 |
|
1426 | |||
1412 | # Inject names into __builtin__ so we can complete on the added names. |
|
1427 | # Inject names into __builtin__ so we can complete on the added names. | |
1413 | with self.builtin_trap: |
|
1428 | with self.builtin_trap: | |
1414 | complete = self.Completer.complete |
|
1429 | complete = self.Completer.complete | |
1415 | state = 0 |
|
1430 | state = 0 | |
1416 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1431 | # use a dict so we get unique keys, since ipyhton's multiple | |
1417 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1432 | # completers can return duplicates. When we make 2.4 a requirement, | |
1418 | # start using sets instead, which are faster. |
|
1433 | # start using sets instead, which are faster. | |
1419 | comps = {} |
|
1434 | comps = {} | |
1420 | while True: |
|
1435 | while True: | |
1421 | newcomp = complete(text,state,line_buffer=text) |
|
1436 | newcomp = complete(text,state,line_buffer=text) | |
1422 | if newcomp is None: |
|
1437 | if newcomp is None: | |
1423 | break |
|
1438 | break | |
1424 | comps[newcomp] = 1 |
|
1439 | comps[newcomp] = 1 | |
1425 | state += 1 |
|
1440 | state += 1 | |
1426 | outcomps = comps.keys() |
|
1441 | outcomps = comps.keys() | |
1427 | outcomps.sort() |
|
1442 | outcomps.sort() | |
1428 | #print "T:",text,"OC:",outcomps # dbg |
|
1443 | #print "T:",text,"OC:",outcomps # dbg | |
1429 | #print "vars:",self.user_ns.keys() |
|
1444 | #print "vars:",self.user_ns.keys() | |
1430 | return outcomps |
|
1445 | return outcomps | |
1431 |
|
1446 | |||
1432 | def set_custom_completer(self,completer,pos=0): |
|
1447 | def set_custom_completer(self,completer,pos=0): | |
1433 | """Adds a new custom completer function. |
|
1448 | """Adds a new custom completer function. | |
1434 |
|
1449 | |||
1435 | The position argument (defaults to 0) is the index in the completers |
|
1450 | The position argument (defaults to 0) is the index in the completers | |
1436 | list where you want the completer to be inserted.""" |
|
1451 | list where you want the completer to be inserted.""" | |
1437 |
|
1452 | |||
1438 | newcomp = new.instancemethod(completer,self.Completer, |
|
1453 | newcomp = new.instancemethod(completer,self.Completer, | |
1439 | self.Completer.__class__) |
|
1454 | self.Completer.__class__) | |
1440 | self.Completer.matchers.insert(pos,newcomp) |
|
1455 | self.Completer.matchers.insert(pos,newcomp) | |
1441 |
|
1456 | |||
1442 | def set_completer(self): |
|
1457 | def set_completer(self): | |
1443 | """Reset readline's completer to be our own.""" |
|
1458 | """Reset readline's completer to be our own.""" | |
1444 | self.readline.set_completer(self.Completer.complete) |
|
1459 | self.readline.set_completer(self.Completer.complete) | |
1445 |
|
1460 | |||
1446 | def set_completer_frame(self, frame=None): |
|
1461 | def set_completer_frame(self, frame=None): | |
1447 | """Set the frame of the completer.""" |
|
1462 | """Set the frame of the completer.""" | |
1448 | if frame: |
|
1463 | if frame: | |
1449 | self.Completer.namespace = frame.f_locals |
|
1464 | self.Completer.namespace = frame.f_locals | |
1450 | self.Completer.global_namespace = frame.f_globals |
|
1465 | self.Completer.global_namespace = frame.f_globals | |
1451 | else: |
|
1466 | else: | |
1452 | self.Completer.namespace = self.user_ns |
|
1467 | self.Completer.namespace = self.user_ns | |
1453 | self.Completer.global_namespace = self.user_global_ns |
|
1468 | self.Completer.global_namespace = self.user_global_ns | |
1454 |
|
1469 | |||
1455 | #------------------------------------------------------------------------- |
|
1470 | #------------------------------------------------------------------------- | |
1456 | # Things related to readline |
|
1471 | # Things related to readline | |
1457 | #------------------------------------------------------------------------- |
|
1472 | #------------------------------------------------------------------------- | |
1458 |
|
1473 | |||
1459 | def init_readline(self): |
|
1474 | def init_readline(self): | |
1460 | """Command history completion/saving/reloading.""" |
|
1475 | """Command history completion/saving/reloading.""" | |
1461 |
|
1476 | |||
1462 | if self.readline_use: |
|
1477 | if self.readline_use: | |
1463 | import IPython.utils.rlineimpl as readline |
|
1478 | import IPython.utils.rlineimpl as readline | |
1464 |
|
1479 | |||
1465 | self.rl_next_input = None |
|
1480 | self.rl_next_input = None | |
1466 | self.rl_do_indent = False |
|
1481 | self.rl_do_indent = False | |
1467 |
|
1482 | |||
1468 | if not self.readline_use or not readline.have_readline: |
|
1483 | if not self.readline_use or not readline.have_readline: | |
1469 | self.has_readline = False |
|
1484 | self.has_readline = False | |
1470 | self.readline = None |
|
1485 | self.readline = None | |
1471 | # Set a number of methods that depend on readline to be no-op |
|
1486 | # Set a number of methods that depend on readline to be no-op | |
1472 | self.savehist = no_op |
|
1487 | self.savehist = no_op | |
1473 | self.reloadhist = no_op |
|
1488 | self.reloadhist = no_op | |
1474 | self.set_completer = no_op |
|
1489 | self.set_completer = no_op | |
1475 | self.set_custom_completer = no_op |
|
1490 | self.set_custom_completer = no_op | |
1476 | self.set_completer_frame = no_op |
|
1491 | self.set_completer_frame = no_op | |
1477 | warn('Readline services not available or not loaded.') |
|
1492 | warn('Readline services not available or not loaded.') | |
1478 | else: |
|
1493 | else: | |
1479 | self.has_readline = True |
|
1494 | self.has_readline = True | |
1480 | self.readline = readline |
|
1495 | self.readline = readline | |
1481 | sys.modules['readline'] = readline |
|
1496 | sys.modules['readline'] = readline | |
1482 | import atexit |
|
1497 | import atexit | |
1483 | from IPython.core.completer import IPCompleter |
|
1498 | from IPython.core.completer import IPCompleter | |
1484 | self.Completer = IPCompleter(self, |
|
1499 | self.Completer = IPCompleter(self, | |
1485 | self.user_ns, |
|
1500 | self.user_ns, | |
1486 | self.user_global_ns, |
|
1501 | self.user_global_ns, | |
1487 | self.readline_omit__names, |
|
1502 | self.readline_omit__names, | |
1488 | self.alias_manager.alias_table) |
|
1503 | self.alias_manager.alias_table) | |
1489 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1504 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1490 | self.strdispatchers['complete_command'] = sdisp |
|
1505 | self.strdispatchers['complete_command'] = sdisp | |
1491 | self.Completer.custom_completers = sdisp |
|
1506 | self.Completer.custom_completers = sdisp | |
1492 | # Platform-specific configuration |
|
1507 | # Platform-specific configuration | |
1493 | if os.name == 'nt': |
|
1508 | if os.name == 'nt': | |
1494 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1509 | self.readline_startup_hook = readline.set_pre_input_hook | |
1495 | else: |
|
1510 | else: | |
1496 | self.readline_startup_hook = readline.set_startup_hook |
|
1511 | self.readline_startup_hook = readline.set_startup_hook | |
1497 |
|
1512 | |||
1498 | # Load user's initrc file (readline config) |
|
1513 | # Load user's initrc file (readline config) | |
1499 | # Or if libedit is used, load editrc. |
|
1514 | # Or if libedit is used, load editrc. | |
1500 | inputrc_name = os.environ.get('INPUTRC') |
|
1515 | inputrc_name = os.environ.get('INPUTRC') | |
1501 | if inputrc_name is None: |
|
1516 | if inputrc_name is None: | |
1502 | home_dir = get_home_dir() |
|
1517 | home_dir = get_home_dir() | |
1503 | if home_dir is not None: |
|
1518 | if home_dir is not None: | |
1504 | inputrc_name = '.inputrc' |
|
1519 | inputrc_name = '.inputrc' | |
1505 | if readline.uses_libedit: |
|
1520 | if readline.uses_libedit: | |
1506 | inputrc_name = '.editrc' |
|
1521 | inputrc_name = '.editrc' | |
1507 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1522 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1508 | if os.path.isfile(inputrc_name): |
|
1523 | if os.path.isfile(inputrc_name): | |
1509 | try: |
|
1524 | try: | |
1510 | readline.read_init_file(inputrc_name) |
|
1525 | readline.read_init_file(inputrc_name) | |
1511 | except: |
|
1526 | except: | |
1512 | warn('Problems reading readline initialization file <%s>' |
|
1527 | warn('Problems reading readline initialization file <%s>' | |
1513 | % inputrc_name) |
|
1528 | % inputrc_name) | |
1514 |
|
1529 | |||
1515 | # save this in sys so embedded copies can restore it properly |
|
1530 | # save this in sys so embedded copies can restore it properly | |
1516 | sys.ipcompleter = self.Completer.complete |
|
1531 | sys.ipcompleter = self.Completer.complete | |
1517 | self.set_completer() |
|
1532 | self.set_completer() | |
1518 |
|
1533 | |||
1519 | # Configure readline according to user's prefs |
|
1534 | # Configure readline according to user's prefs | |
1520 | # This is only done if GNU readline is being used. If libedit |
|
1535 | # This is only done if GNU readline is being used. If libedit | |
1521 | # is being used (as on Leopard) the readline config is |
|
1536 | # is being used (as on Leopard) the readline config is | |
1522 | # not run as the syntax for libedit is different. |
|
1537 | # not run as the syntax for libedit is different. | |
1523 | if not readline.uses_libedit: |
|
1538 | if not readline.uses_libedit: | |
1524 | for rlcommand in self.readline_parse_and_bind: |
|
1539 | for rlcommand in self.readline_parse_and_bind: | |
1525 | #print "loading rl:",rlcommand # dbg |
|
1540 | #print "loading rl:",rlcommand # dbg | |
1526 | readline.parse_and_bind(rlcommand) |
|
1541 | readline.parse_and_bind(rlcommand) | |
1527 |
|
1542 | |||
1528 | # Remove some chars from the delimiters list. If we encounter |
|
1543 | # Remove some chars from the delimiters list. If we encounter | |
1529 | # unicode chars, discard them. |
|
1544 | # unicode chars, discard them. | |
1530 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1545 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1531 | delims = delims.translate(string._idmap, |
|
1546 | delims = delims.translate(string._idmap, | |
1532 | self.readline_remove_delims) |
|
1547 | self.readline_remove_delims) | |
1533 | readline.set_completer_delims(delims) |
|
1548 | readline.set_completer_delims(delims) | |
1534 | # otherwise we end up with a monster history after a while: |
|
1549 | # otherwise we end up with a monster history after a while: | |
1535 | readline.set_history_length(1000) |
|
1550 | readline.set_history_length(1000) | |
1536 | try: |
|
1551 | try: | |
1537 | #print '*** Reading readline history' # dbg |
|
1552 | #print '*** Reading readline history' # dbg | |
1538 | readline.read_history_file(self.histfile) |
|
1553 | readline.read_history_file(self.histfile) | |
1539 | except IOError: |
|
1554 | except IOError: | |
1540 | pass # It doesn't exist yet. |
|
1555 | pass # It doesn't exist yet. | |
1541 |
|
1556 | |||
1542 | atexit.register(self.atexit_operations) |
|
1557 | atexit.register(self.atexit_operations) | |
1543 | del atexit |
|
1558 | del atexit | |
1544 |
|
1559 | |||
1545 | # Configure auto-indent for all platforms |
|
1560 | # Configure auto-indent for all platforms | |
1546 | self.set_autoindent(self.autoindent) |
|
1561 | self.set_autoindent(self.autoindent) | |
1547 |
|
1562 | |||
1548 | def set_next_input(self, s): |
|
1563 | def set_next_input(self, s): | |
1549 | """ Sets the 'default' input string for the next command line. |
|
1564 | """ Sets the 'default' input string for the next command line. | |
1550 |
|
1565 | |||
1551 | Requires readline. |
|
1566 | Requires readline. | |
1552 |
|
1567 | |||
1553 | Example: |
|
1568 | Example: | |
1554 |
|
1569 | |||
1555 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1570 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1556 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1571 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1557 | """ |
|
1572 | """ | |
1558 |
|
1573 | |||
1559 | self.rl_next_input = s |
|
1574 | self.rl_next_input = s | |
1560 |
|
1575 | |||
1561 | def pre_readline(self): |
|
1576 | def pre_readline(self): | |
1562 | """readline hook to be used at the start of each line. |
|
1577 | """readline hook to be used at the start of each line. | |
1563 |
|
1578 | |||
1564 | Currently it handles auto-indent only.""" |
|
1579 | Currently it handles auto-indent only.""" | |
1565 |
|
1580 | |||
1566 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1581 | #debugx('self.indent_current_nsp','pre_readline:') | |
1567 |
|
1582 | |||
1568 | if self.rl_do_indent: |
|
1583 | if self.rl_do_indent: | |
1569 | self.readline.insert_text(self._indent_current_str()) |
|
1584 | self.readline.insert_text(self._indent_current_str()) | |
1570 | if self.rl_next_input is not None: |
|
1585 | if self.rl_next_input is not None: | |
1571 | self.readline.insert_text(self.rl_next_input) |
|
1586 | self.readline.insert_text(self.rl_next_input) | |
1572 | self.rl_next_input = None |
|
1587 | self.rl_next_input = None | |
1573 |
|
1588 | |||
1574 | def _indent_current_str(self): |
|
1589 | def _indent_current_str(self): | |
1575 | """return the current level of indentation as a string""" |
|
1590 | """return the current level of indentation as a string""" | |
1576 | return self.indent_current_nsp * ' ' |
|
1591 | return self.indent_current_nsp * ' ' | |
1577 |
|
1592 | |||
1578 | #------------------------------------------------------------------------- |
|
1593 | #------------------------------------------------------------------------- | |
1579 | # Things related to magics |
|
1594 | # Things related to magics | |
1580 | #------------------------------------------------------------------------- |
|
1595 | #------------------------------------------------------------------------- | |
1581 |
|
1596 | |||
1582 | def init_magics(self): |
|
1597 | def init_magics(self): | |
1583 | # Set user colors (don't do it in the constructor above so that it |
|
1598 | # Set user colors (don't do it in the constructor above so that it | |
1584 | # doesn't crash if colors option is invalid) |
|
1599 | # doesn't crash if colors option is invalid) | |
1585 | self.magic_colors(self.colors) |
|
1600 | self.magic_colors(self.colors) | |
1586 | # History was moved to a separate module |
|
1601 | # History was moved to a separate module | |
1587 | from . import history |
|
1602 | from . import history | |
1588 | history.init_ipython(self) |
|
1603 | history.init_ipython(self) | |
1589 |
|
1604 | |||
1590 | def magic(self,arg_s): |
|
1605 | def magic(self,arg_s): | |
1591 | """Call a magic function by name. |
|
1606 | """Call a magic function by name. | |
1592 |
|
1607 | |||
1593 | Input: a string containing the name of the magic function to call and any |
|
1608 | Input: a string containing the name of the magic function to call and any | |
1594 | additional arguments to be passed to the magic. |
|
1609 | additional arguments to be passed to the magic. | |
1595 |
|
1610 | |||
1596 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1611 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1597 | prompt: |
|
1612 | prompt: | |
1598 |
|
1613 | |||
1599 | In[1]: %name -opt foo bar |
|
1614 | In[1]: %name -opt foo bar | |
1600 |
|
1615 | |||
1601 | To call a magic without arguments, simply use magic('name'). |
|
1616 | To call a magic without arguments, simply use magic('name'). | |
1602 |
|
1617 | |||
1603 | This provides a proper Python function to call IPython's magics in any |
|
1618 | This provides a proper Python function to call IPython's magics in any | |
1604 | valid Python code you can type at the interpreter, including loops and |
|
1619 | valid Python code you can type at the interpreter, including loops and | |
1605 | compound statements. |
|
1620 | compound statements. | |
1606 | """ |
|
1621 | """ | |
1607 |
|
1622 | |||
1608 | args = arg_s.split(' ',1) |
|
1623 | args = arg_s.split(' ',1) | |
1609 | magic_name = args[0] |
|
1624 | magic_name = args[0] | |
1610 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1625 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1611 |
|
1626 | |||
1612 | try: |
|
1627 | try: | |
1613 | magic_args = args[1] |
|
1628 | magic_args = args[1] | |
1614 | except IndexError: |
|
1629 | except IndexError: | |
1615 | magic_args = '' |
|
1630 | magic_args = '' | |
1616 | fn = getattr(self,'magic_'+magic_name,None) |
|
1631 | fn = getattr(self,'magic_'+magic_name,None) | |
1617 | if fn is None: |
|
1632 | if fn is None: | |
1618 | error("Magic function `%s` not found." % magic_name) |
|
1633 | error("Magic function `%s` not found." % magic_name) | |
1619 | else: |
|
1634 | else: | |
1620 | magic_args = self.var_expand(magic_args,1) |
|
1635 | magic_args = self.var_expand(magic_args,1) | |
1621 | with nested(self.builtin_trap,): |
|
1636 | with nested(self.builtin_trap,): | |
1622 | result = fn(magic_args) |
|
1637 | result = fn(magic_args) | |
1623 | return result |
|
1638 | return result | |
1624 |
|
1639 | |||
1625 | def define_magic(self, magicname, func): |
|
1640 | def define_magic(self, magicname, func): | |
1626 | """Expose own function as magic function for ipython |
|
1641 | """Expose own function as magic function for ipython | |
1627 |
|
1642 | |||
1628 | def foo_impl(self,parameter_s=''): |
|
1643 | def foo_impl(self,parameter_s=''): | |
1629 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1644 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1630 | print 'Magic function. Passed parameter is between < >:' |
|
1645 | print 'Magic function. Passed parameter is between < >:' | |
1631 | print '<%s>' % parameter_s |
|
1646 | print '<%s>' % parameter_s | |
1632 | print 'The self object is:',self |
|
1647 | print 'The self object is:',self | |
1633 |
|
1648 | |||
1634 | self.define_magic('foo',foo_impl) |
|
1649 | self.define_magic('foo',foo_impl) | |
1635 | """ |
|
1650 | """ | |
1636 |
|
1651 | |||
1637 | import new |
|
1652 | import new | |
1638 | im = new.instancemethod(func,self, self.__class__) |
|
1653 | im = new.instancemethod(func,self, self.__class__) | |
1639 | old = getattr(self, "magic_" + magicname, None) |
|
1654 | old = getattr(self, "magic_" + magicname, None) | |
1640 | setattr(self, "magic_" + magicname, im) |
|
1655 | setattr(self, "magic_" + magicname, im) | |
1641 | return old |
|
1656 | return old | |
1642 |
|
1657 | |||
1643 | #------------------------------------------------------------------------- |
|
1658 | #------------------------------------------------------------------------- | |
1644 | # Things related to macros |
|
1659 | # Things related to macros | |
1645 | #------------------------------------------------------------------------- |
|
1660 | #------------------------------------------------------------------------- | |
1646 |
|
1661 | |||
1647 | def define_macro(self, name, themacro): |
|
1662 | def define_macro(self, name, themacro): | |
1648 | """Define a new macro |
|
1663 | """Define a new macro | |
1649 |
|
1664 | |||
1650 | Parameters |
|
1665 | Parameters | |
1651 | ---------- |
|
1666 | ---------- | |
1652 | name : str |
|
1667 | name : str | |
1653 | The name of the macro. |
|
1668 | The name of the macro. | |
1654 | themacro : str or Macro |
|
1669 | themacro : str or Macro | |
1655 | The action to do upon invoking the macro. If a string, a new |
|
1670 | The action to do upon invoking the macro. If a string, a new | |
1656 | Macro object is created by passing the string to it. |
|
1671 | Macro object is created by passing the string to it. | |
1657 | """ |
|
1672 | """ | |
1658 |
|
1673 | |||
1659 | from IPython.core import macro |
|
1674 | from IPython.core import macro | |
1660 |
|
1675 | |||
1661 | if isinstance(themacro, basestring): |
|
1676 | if isinstance(themacro, basestring): | |
1662 | themacro = macro.Macro(themacro) |
|
1677 | themacro = macro.Macro(themacro) | |
1663 | if not isinstance(themacro, macro.Macro): |
|
1678 | if not isinstance(themacro, macro.Macro): | |
1664 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1679 | raise ValueError('A macro must be a string or a Macro instance.') | |
1665 | self.user_ns[name] = themacro |
|
1680 | self.user_ns[name] = themacro | |
1666 |
|
1681 | |||
1667 | #------------------------------------------------------------------------- |
|
1682 | #------------------------------------------------------------------------- | |
1668 | # Things related to the running of system commands |
|
1683 | # Things related to the running of system commands | |
1669 | #------------------------------------------------------------------------- |
|
1684 | #------------------------------------------------------------------------- | |
1670 |
|
1685 | |||
1671 | def system(self, cmd): |
|
1686 | def system(self, cmd): | |
1672 | """Make a system call, using IPython.""" |
|
1687 | """Make a system call, using IPython.""" | |
1673 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1688 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1674 |
|
1689 | |||
1675 | #------------------------------------------------------------------------- |
|
1690 | #------------------------------------------------------------------------- | |
1676 | # Things related to aliases |
|
1691 | # Things related to aliases | |
1677 | #------------------------------------------------------------------------- |
|
1692 | #------------------------------------------------------------------------- | |
1678 |
|
1693 | |||
1679 | def init_alias(self): |
|
1694 | def init_alias(self): | |
1680 | self.alias_manager = AliasManager(self, config=self.config) |
|
1695 | self.alias_manager = AliasManager(self, config=self.config) | |
1681 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1696 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1682 |
|
1697 | |||
1683 | #------------------------------------------------------------------------- |
|
1698 | #------------------------------------------------------------------------- | |
1684 | # Things related to the running of code |
|
1699 | # Things related to the running of code | |
1685 | #------------------------------------------------------------------------- |
|
1700 | #------------------------------------------------------------------------- | |
1686 |
|
1701 | |||
1687 | def ex(self, cmd): |
|
1702 | def ex(self, cmd): | |
1688 | """Execute a normal python statement in user namespace.""" |
|
1703 | """Execute a normal python statement in user namespace.""" | |
1689 | with nested(self.builtin_trap,): |
|
1704 | with nested(self.builtin_trap,): | |
1690 | exec cmd in self.user_global_ns, self.user_ns |
|
1705 | exec cmd in self.user_global_ns, self.user_ns | |
1691 |
|
1706 | |||
1692 | def ev(self, expr): |
|
1707 | def ev(self, expr): | |
1693 | """Evaluate python expression expr in user namespace. |
|
1708 | """Evaluate python expression expr in user namespace. | |
1694 |
|
1709 | |||
1695 | Returns the result of evaluation |
|
1710 | Returns the result of evaluation | |
1696 | """ |
|
1711 | """ | |
1697 | with nested(self.builtin_trap,): |
|
1712 | with nested(self.builtin_trap,): | |
1698 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1713 | return eval(expr, self.user_global_ns, self.user_ns) | |
1699 |
|
1714 | |||
1700 | def mainloop(self, display_banner=None): |
|
1715 | def mainloop(self, display_banner=None): | |
1701 | """Start the mainloop. |
|
1716 | """Start the mainloop. | |
1702 |
|
1717 | |||
1703 | If an optional banner argument is given, it will override the |
|
1718 | If an optional banner argument is given, it will override the | |
1704 | internally created default banner. |
|
1719 | internally created default banner. | |
1705 | """ |
|
1720 | """ | |
1706 |
|
1721 | |||
1707 | with nested(self.builtin_trap, self.display_trap): |
|
1722 | with nested(self.builtin_trap, self.display_trap): | |
1708 |
|
1723 | |||
1709 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1724 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1710 | # ensure that it's in sync |
|
1725 | # ensure that it's in sync | |
1711 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1726 | if len(self.input_hist) != len (self.input_hist_raw): | |
1712 | self.input_hist_raw = InputList(self.input_hist) |
|
1727 | self.input_hist_raw = InputList(self.input_hist) | |
1713 |
|
1728 | |||
1714 | while 1: |
|
1729 | while 1: | |
1715 | try: |
|
1730 | try: | |
1716 | self.interact(display_banner=display_banner) |
|
1731 | self.interact(display_banner=display_banner) | |
1717 | #self.interact_with_readline() |
|
1732 | #self.interact_with_readline() | |
1718 | # XXX for testing of a readline-decoupled repl loop, call |
|
1733 | # XXX for testing of a readline-decoupled repl loop, call | |
1719 | # interact_with_readline above |
|
1734 | # interact_with_readline above | |
1720 | break |
|
1735 | break | |
1721 | except KeyboardInterrupt: |
|
1736 | except KeyboardInterrupt: | |
1722 | # this should not be necessary, but KeyboardInterrupt |
|
1737 | # this should not be necessary, but KeyboardInterrupt | |
1723 | # handling seems rather unpredictable... |
|
1738 | # handling seems rather unpredictable... | |
1724 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1739 | self.write("\nKeyboardInterrupt in interact()\n") | |
1725 |
|
1740 | |||
1726 | def interact_prompt(self): |
|
1741 | def interact_prompt(self): | |
1727 | """ Print the prompt (in read-eval-print loop) |
|
1742 | """ Print the prompt (in read-eval-print loop) | |
1728 |
|
1743 | |||
1729 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1744 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1730 | used in standard IPython flow. |
|
1745 | used in standard IPython flow. | |
1731 | """ |
|
1746 | """ | |
1732 | if self.more: |
|
1747 | if self.more: | |
1733 | try: |
|
1748 | try: | |
1734 | prompt = self.hooks.generate_prompt(True) |
|
1749 | prompt = self.hooks.generate_prompt(True) | |
1735 | except: |
|
1750 | except: | |
1736 | self.showtraceback() |
|
1751 | self.showtraceback() | |
1737 | if self.autoindent: |
|
1752 | if self.autoindent: | |
1738 | self.rl_do_indent = True |
|
1753 | self.rl_do_indent = True | |
1739 |
|
1754 | |||
1740 | else: |
|
1755 | else: | |
1741 | try: |
|
1756 | try: | |
1742 | prompt = self.hooks.generate_prompt(False) |
|
1757 | prompt = self.hooks.generate_prompt(False) | |
1743 | except: |
|
1758 | except: | |
1744 | self.showtraceback() |
|
1759 | self.showtraceback() | |
1745 | self.write(prompt) |
|
1760 | self.write(prompt) | |
1746 |
|
1761 | |||
1747 | def interact_handle_input(self,line): |
|
1762 | def interact_handle_input(self,line): | |
1748 | """ Handle the input line (in read-eval-print loop) |
|
1763 | """ Handle the input line (in read-eval-print loop) | |
1749 |
|
1764 | |||
1750 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1765 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1751 | used in standard IPython flow. |
|
1766 | used in standard IPython flow. | |
1752 | """ |
|
1767 | """ | |
1753 | if line.lstrip() == line: |
|
1768 | if line.lstrip() == line: | |
1754 | self.shadowhist.add(line.strip()) |
|
1769 | self.shadowhist.add(line.strip()) | |
1755 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1770 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) | |
1756 |
|
1771 | |||
1757 | if line.strip(): |
|
1772 | if line.strip(): | |
1758 | if self.more: |
|
1773 | if self.more: | |
1759 | self.input_hist_raw[-1] += '%s\n' % line |
|
1774 | self.input_hist_raw[-1] += '%s\n' % line | |
1760 | else: |
|
1775 | else: | |
1761 | self.input_hist_raw.append('%s\n' % line) |
|
1776 | self.input_hist_raw.append('%s\n' % line) | |
1762 |
|
1777 | |||
1763 |
|
1778 | |||
1764 | self.more = self.push_line(lineout) |
|
1779 | self.more = self.push_line(lineout) | |
1765 | if (self.SyntaxTB.last_syntax_error and |
|
1780 | if (self.SyntaxTB.last_syntax_error and | |
1766 | self.autoedit_syntax): |
|
1781 | self.autoedit_syntax): | |
1767 | self.edit_syntax_error() |
|
1782 | self.edit_syntax_error() | |
1768 |
|
1783 | |||
1769 | def interact_with_readline(self): |
|
1784 | def interact_with_readline(self): | |
1770 | """ Demo of using interact_handle_input, interact_prompt |
|
1785 | """ Demo of using interact_handle_input, interact_prompt | |
1771 |
|
1786 | |||
1772 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1787 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1773 | it should work like this. |
|
1788 | it should work like this. | |
1774 | """ |
|
1789 | """ | |
1775 | self.readline_startup_hook(self.pre_readline) |
|
1790 | self.readline_startup_hook(self.pre_readline) | |
1776 | while not self.exit_now: |
|
1791 | while not self.exit_now: | |
1777 | self.interact_prompt() |
|
1792 | self.interact_prompt() | |
1778 | if self.more: |
|
1793 | if self.more: | |
1779 | self.rl_do_indent = True |
|
1794 | self.rl_do_indent = True | |
1780 | else: |
|
1795 | else: | |
1781 | self.rl_do_indent = False |
|
1796 | self.rl_do_indent = False | |
1782 | line = raw_input_original().decode(self.stdin_encoding) |
|
1797 | line = raw_input_original().decode(self.stdin_encoding) | |
1783 | self.interact_handle_input(line) |
|
1798 | self.interact_handle_input(line) | |
1784 |
|
1799 | |||
1785 | def interact(self, display_banner=None): |
|
1800 | def interact(self, display_banner=None): | |
1786 | """Closely emulate the interactive Python console.""" |
|
1801 | """Closely emulate the interactive Python console.""" | |
1787 |
|
1802 | |||
1788 | # batch run -> do not interact |
|
1803 | # batch run -> do not interact | |
1789 | if self.exit_now: |
|
1804 | if self.exit_now: | |
1790 | return |
|
1805 | return | |
1791 |
|
1806 | |||
1792 | if display_banner is None: |
|
1807 | if display_banner is None: | |
1793 | display_banner = self.display_banner |
|
1808 | display_banner = self.display_banner | |
1794 | if display_banner: |
|
1809 | if display_banner: | |
1795 | self.show_banner() |
|
1810 | self.show_banner() | |
1796 |
|
1811 | |||
1797 | more = 0 |
|
1812 | more = 0 | |
1798 |
|
1813 | |||
1799 | # Mark activity in the builtins |
|
1814 | # Mark activity in the builtins | |
1800 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1815 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1801 |
|
1816 | |||
1802 | if self.has_readline: |
|
1817 | if self.has_readline: | |
1803 | self.readline_startup_hook(self.pre_readline) |
|
1818 | self.readline_startup_hook(self.pre_readline) | |
1804 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1819 | # exit_now is set by a call to %Exit or %Quit, through the | |
1805 | # ask_exit callback. |
|
1820 | # ask_exit callback. | |
1806 |
|
1821 | |||
1807 | while not self.exit_now: |
|
1822 | while not self.exit_now: | |
1808 | self.hooks.pre_prompt_hook() |
|
1823 | self.hooks.pre_prompt_hook() | |
1809 | if more: |
|
1824 | if more: | |
1810 | try: |
|
1825 | try: | |
1811 | prompt = self.hooks.generate_prompt(True) |
|
1826 | prompt = self.hooks.generate_prompt(True) | |
1812 | except: |
|
1827 | except: | |
1813 | self.showtraceback() |
|
1828 | self.showtraceback() | |
1814 | if self.autoindent: |
|
1829 | if self.autoindent: | |
1815 | self.rl_do_indent = True |
|
1830 | self.rl_do_indent = True | |
1816 |
|
1831 | |||
1817 | else: |
|
1832 | else: | |
1818 | try: |
|
1833 | try: | |
1819 | prompt = self.hooks.generate_prompt(False) |
|
1834 | prompt = self.hooks.generate_prompt(False) | |
1820 | except: |
|
1835 | except: | |
1821 | self.showtraceback() |
|
1836 | self.showtraceback() | |
1822 | try: |
|
1837 | try: | |
1823 | line = self.raw_input(prompt, more) |
|
1838 | line = self.raw_input(prompt, more) | |
1824 | if self.exit_now: |
|
1839 | if self.exit_now: | |
1825 | # quick exit on sys.std[in|out] close |
|
1840 | # quick exit on sys.std[in|out] close | |
1826 | break |
|
1841 | break | |
1827 | if self.autoindent: |
|
1842 | if self.autoindent: | |
1828 | self.rl_do_indent = False |
|
1843 | self.rl_do_indent = False | |
1829 |
|
1844 | |||
1830 | except KeyboardInterrupt: |
|
1845 | except KeyboardInterrupt: | |
1831 | #double-guard against keyboardinterrupts during kbdint handling |
|
1846 | #double-guard against keyboardinterrupts during kbdint handling | |
1832 | try: |
|
1847 | try: | |
1833 | self.write('\nKeyboardInterrupt\n') |
|
1848 | self.write('\nKeyboardInterrupt\n') | |
1834 | self.resetbuffer() |
|
1849 | self.resetbuffer() | |
1835 | # keep cache in sync with the prompt counter: |
|
1850 | # keep cache in sync with the prompt counter: | |
1836 | self.outputcache.prompt_count -= 1 |
|
1851 | self.outputcache.prompt_count -= 1 | |
1837 |
|
1852 | |||
1838 | if self.autoindent: |
|
1853 | if self.autoindent: | |
1839 | self.indent_current_nsp = 0 |
|
1854 | self.indent_current_nsp = 0 | |
1840 | more = 0 |
|
1855 | more = 0 | |
1841 | except KeyboardInterrupt: |
|
1856 | except KeyboardInterrupt: | |
1842 | pass |
|
1857 | pass | |
1843 | except EOFError: |
|
1858 | except EOFError: | |
1844 | if self.autoindent: |
|
1859 | if self.autoindent: | |
1845 | self.rl_do_indent = False |
|
1860 | self.rl_do_indent = False | |
1846 | if self.has_readline: |
|
1861 | if self.has_readline: | |
1847 | self.readline_startup_hook(None) |
|
1862 | self.readline_startup_hook(None) | |
1848 | self.write('\n') |
|
1863 | self.write('\n') | |
1849 | self.exit() |
|
1864 | self.exit() | |
1850 | except bdb.BdbQuit: |
|
1865 | except bdb.BdbQuit: | |
1851 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1866 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1852 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1867 | 'Because of how pdb handles the stack, it is impossible\n' | |
1853 | 'for IPython to properly format this particular exception.\n' |
|
1868 | 'for IPython to properly format this particular exception.\n' | |
1854 | 'IPython will resume normal operation.') |
|
1869 | 'IPython will resume normal operation.') | |
1855 | except: |
|
1870 | except: | |
1856 | # exceptions here are VERY RARE, but they can be triggered |
|
1871 | # exceptions here are VERY RARE, but they can be triggered | |
1857 | # asynchronously by signal handlers, for example. |
|
1872 | # asynchronously by signal handlers, for example. | |
1858 | self.showtraceback() |
|
1873 | self.showtraceback() | |
1859 | else: |
|
1874 | else: | |
1860 | more = self.push_line(line) |
|
1875 | more = self.push_line(line) | |
1861 | if (self.SyntaxTB.last_syntax_error and |
|
1876 | if (self.SyntaxTB.last_syntax_error and | |
1862 | self.autoedit_syntax): |
|
1877 | self.autoedit_syntax): | |
1863 | self.edit_syntax_error() |
|
1878 | self.edit_syntax_error() | |
1864 |
|
1879 | |||
1865 | # We are off again... |
|
1880 | # We are off again... | |
1866 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1881 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1867 |
|
1882 | |||
|
1883 | # Turn off the exit flag, so the mainloop can be restarted if desired | |||
|
1884 | self.exit_now = False | |||
|
1885 | ||||
1868 | def safe_execfile(self, fname, *where, **kw): |
|
1886 | def safe_execfile(self, fname, *where, **kw): | |
1869 | """A safe version of the builtin execfile(). |
|
1887 | """A safe version of the builtin execfile(). | |
1870 |
|
1888 | |||
1871 | This version will never throw an exception, but instead print |
|
1889 | This version will never throw an exception, but instead print | |
1872 | helpful error messages to the screen. This only works on pure |
|
1890 | helpful error messages to the screen. This only works on pure | |
1873 | Python files with the .py extension. |
|
1891 | Python files with the .py extension. | |
1874 |
|
1892 | |||
1875 | Parameters |
|
1893 | Parameters | |
1876 | ---------- |
|
1894 | ---------- | |
1877 | fname : string |
|
1895 | fname : string | |
1878 | The name of the file to be executed. |
|
1896 | The name of the file to be executed. | |
1879 | where : tuple |
|
1897 | where : tuple | |
1880 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1898 | One or two namespaces, passed to execfile() as (globals,locals). | |
1881 | If only one is given, it is passed as both. |
|
1899 | If only one is given, it is passed as both. | |
1882 | exit_ignore : bool (False) |
|
1900 | exit_ignore : bool (False) | |
1883 |
If True, then |
|
1901 | If True, then silence SystemExit for non-zero status (it is always | |
|
1902 | silenced for zero status, as it is so common). | |||
1884 | """ |
|
1903 | """ | |
1885 | kw.setdefault('exit_ignore', False) |
|
1904 | kw.setdefault('exit_ignore', False) | |
1886 |
|
1905 | |||
1887 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1906 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1888 |
|
1907 | |||
1889 | # Make sure we have a .py file |
|
1908 | # Make sure we have a .py file | |
1890 | if not fname.endswith('.py'): |
|
1909 | if not fname.endswith('.py'): | |
1891 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1910 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1892 |
|
1911 | |||
1893 | # Make sure we can open the file |
|
1912 | # Make sure we can open the file | |
1894 | try: |
|
1913 | try: | |
1895 | with open(fname) as thefile: |
|
1914 | with open(fname) as thefile: | |
1896 | pass |
|
1915 | pass | |
1897 | except: |
|
1916 | except: | |
1898 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1917 | warn('Could not open file <%s> for safe execution.' % fname) | |
1899 | return |
|
1918 | return | |
1900 |
|
1919 | |||
1901 | # Find things also in current directory. This is needed to mimic the |
|
1920 | # Find things also in current directory. This is needed to mimic the | |
1902 | # behavior of running a script from the system command line, where |
|
1921 | # behavior of running a script from the system command line, where | |
1903 | # Python inserts the script's directory into sys.path |
|
1922 | # Python inserts the script's directory into sys.path | |
1904 | dname = os.path.dirname(fname) |
|
1923 | dname = os.path.dirname(fname) | |
1905 |
|
1924 | |||
1906 | with prepended_to_syspath(dname): |
|
1925 | with prepended_to_syspath(dname): | |
1907 | try: |
|
1926 | try: | |
1908 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
|||
1909 | # Work around a bug in Python for Windows. The bug was |
|
|||
1910 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
|||
1911 | # SVN Python as of March/07. For details, see: |
|
|||
1912 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
|||
1913 | try: |
|
|||
1914 | globs,locs = where[0:2] |
|
|||
1915 | except: |
|
|||
1916 | try: |
|
|||
1917 | globs = locs = where[0] |
|
|||
1918 | except: |
|
|||
1919 | globs = locs = globals() |
|
|||
1920 | exec file(fname) in globs,locs |
|
|||
1921 | else: |
|
|||
1922 |
|
|
1927 | execfile(fname,*where) | |
1923 | except SyntaxError: |
|
|||
1924 | self.showsyntaxerror() |
|
|||
1925 | warn('Failure executing file: <%s>' % fname) |
|
|||
1926 | except SystemExit, status: |
|
1928 | except SystemExit, status: | |
1927 | # Code that correctly sets the exit status flag to success (0) |
|
1929 | # If the call was made with 0 or None exit status (sys.exit(0) | |
1928 |
# |
|
1930 | # or sys.exit() ), don't bother showing a traceback, as both of | |
1929 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
1931 | # these are considered normal by the OS: | |
1930 | # will still get a traceback. Note that the structure of the |
|
1932 | # > python -c'import sys;sys.exit(0)'; echo $? | |
1931 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
1933 | # 0 | |
1932 | # the checks must be done in a version-dependent way. |
|
1934 | # > python -c'import sys;sys.exit()'; echo $? | |
1933 |
|
|
1935 | # 0 | |
1934 | if status.args[0]==0 and not kw['exit_ignore']: |
|
1936 | # For other exit status, we show the exception unless | |
1935 | show = True |
|
1937 | # explicitly silenced, but only in short form. | |
1936 | if show: |
|
1938 | if status.code not in (0, None) and not kw['exit_ignore']: | |
1937 | self.showtraceback() |
|
1939 | self.showtraceback(exception_only=True) | |
1938 | warn('Failure executing file: <%s>' % fname) |
|
|||
1939 | except: |
|
1940 | except: | |
1940 | self.showtraceback() |
|
1941 | self.showtraceback() | |
1941 | warn('Failure executing file: <%s>' % fname) |
|
|||
1942 |
|
1942 | |||
1943 | def safe_execfile_ipy(self, fname): |
|
1943 | def safe_execfile_ipy(self, fname): | |
1944 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1944 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1945 |
|
1945 | |||
1946 | Parameters |
|
1946 | Parameters | |
1947 | ---------- |
|
1947 | ---------- | |
1948 | fname : str |
|
1948 | fname : str | |
1949 | The name of the file to execute. The filename must have a |
|
1949 | The name of the file to execute. The filename must have a | |
1950 | .ipy extension. |
|
1950 | .ipy extension. | |
1951 | """ |
|
1951 | """ | |
1952 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1952 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1953 |
|
1953 | |||
1954 | # Make sure we have a .py file |
|
1954 | # Make sure we have a .py file | |
1955 | if not fname.endswith('.ipy'): |
|
1955 | if not fname.endswith('.ipy'): | |
1956 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1956 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1957 |
|
1957 | |||
1958 | # Make sure we can open the file |
|
1958 | # Make sure we can open the file | |
1959 | try: |
|
1959 | try: | |
1960 | with open(fname) as thefile: |
|
1960 | with open(fname) as thefile: | |
1961 | pass |
|
1961 | pass | |
1962 | except: |
|
1962 | except: | |
1963 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1963 | warn('Could not open file <%s> for safe execution.' % fname) | |
1964 | return |
|
1964 | return | |
1965 |
|
1965 | |||
1966 | # Find things also in current directory. This is needed to mimic the |
|
1966 | # Find things also in current directory. This is needed to mimic the | |
1967 | # behavior of running a script from the system command line, where |
|
1967 | # behavior of running a script from the system command line, where | |
1968 | # Python inserts the script's directory into sys.path |
|
1968 | # Python inserts the script's directory into sys.path | |
1969 | dname = os.path.dirname(fname) |
|
1969 | dname = os.path.dirname(fname) | |
1970 |
|
1970 | |||
1971 | with prepended_to_syspath(dname): |
|
1971 | with prepended_to_syspath(dname): | |
1972 | try: |
|
1972 | try: | |
1973 | with open(fname) as thefile: |
|
1973 | with open(fname) as thefile: | |
1974 | script = thefile.read() |
|
1974 | script = thefile.read() | |
1975 | # self.runlines currently captures all exceptions |
|
1975 | # self.runlines currently captures all exceptions | |
1976 | # raise in user code. It would be nice if there were |
|
1976 | # raise in user code. It would be nice if there were | |
1977 | # versions of runlines, execfile that did raise, so |
|
1977 | # versions of runlines, execfile that did raise, so | |
1978 | # we could catch the errors. |
|
1978 | # we could catch the errors. | |
1979 | self.runlines(script, clean=True) |
|
1979 | self.runlines(script, clean=True) | |
1980 | except: |
|
1980 | except: | |
1981 | self.showtraceback() |
|
1981 | self.showtraceback() | |
1982 | warn('Unknown failure executing file: <%s>' % fname) |
|
1982 | warn('Unknown failure executing file: <%s>' % fname) | |
1983 |
|
1983 | |||
1984 | def _is_secondary_block_start(self, s): |
|
1984 | def _is_secondary_block_start(self, s): | |
1985 | if not s.endswith(':'): |
|
1985 | if not s.endswith(':'): | |
1986 | return False |
|
1986 | return False | |
1987 | if (s.startswith('elif') or |
|
1987 | if (s.startswith('elif') or | |
1988 | s.startswith('else') or |
|
1988 | s.startswith('else') or | |
1989 | s.startswith('except') or |
|
1989 | s.startswith('except') or | |
1990 | s.startswith('finally')): |
|
1990 | s.startswith('finally')): | |
1991 | return True |
|
1991 | return True | |
1992 |
|
1992 | |||
1993 | def cleanup_ipy_script(self, script): |
|
1993 | def cleanup_ipy_script(self, script): | |
1994 | """Make a script safe for self.runlines() |
|
1994 | """Make a script safe for self.runlines() | |
1995 |
|
1995 | |||
1996 | Currently, IPython is lines based, with blocks being detected by |
|
1996 | Currently, IPython is lines based, with blocks being detected by | |
1997 | empty lines. This is a problem for block based scripts that may |
|
1997 | empty lines. This is a problem for block based scripts that may | |
1998 | not have empty lines after blocks. This script adds those empty |
|
1998 | not have empty lines after blocks. This script adds those empty | |
1999 | lines to make scripts safe for running in the current line based |
|
1999 | lines to make scripts safe for running in the current line based | |
2000 | IPython. |
|
2000 | IPython. | |
2001 | """ |
|
2001 | """ | |
2002 | res = [] |
|
2002 | res = [] | |
2003 | lines = script.splitlines() |
|
2003 | lines = script.splitlines() | |
2004 | level = 0 |
|
2004 | level = 0 | |
2005 |
|
2005 | |||
2006 | for l in lines: |
|
2006 | for l in lines: | |
2007 | lstripped = l.lstrip() |
|
2007 | lstripped = l.lstrip() | |
2008 | stripped = l.strip() |
|
2008 | stripped = l.strip() | |
2009 | if not stripped: |
|
2009 | if not stripped: | |
2010 | continue |
|
2010 | continue | |
2011 | newlevel = len(l) - len(lstripped) |
|
2011 | newlevel = len(l) - len(lstripped) | |
2012 | if level > 0 and newlevel == 0 and \ |
|
2012 | if level > 0 and newlevel == 0 and \ | |
2013 | not self._is_secondary_block_start(stripped): |
|
2013 | not self._is_secondary_block_start(stripped): | |
2014 | # add empty line |
|
2014 | # add empty line | |
2015 | res.append('') |
|
2015 | res.append('') | |
2016 | res.append(l) |
|
2016 | res.append(l) | |
2017 | level = newlevel |
|
2017 | level = newlevel | |
2018 |
|
2018 | |||
2019 | return '\n'.join(res) + '\n' |
|
2019 | return '\n'.join(res) + '\n' | |
2020 |
|
2020 | |||
2021 | def runlines(self, lines, clean=False): |
|
2021 | def runlines(self, lines, clean=False): | |
2022 | """Run a string of one or more lines of source. |
|
2022 | """Run a string of one or more lines of source. | |
2023 |
|
2023 | |||
2024 | This method is capable of running a string containing multiple source |
|
2024 | This method is capable of running a string containing multiple source | |
2025 | lines, as if they had been entered at the IPython prompt. Since it |
|
2025 | lines, as if they had been entered at the IPython prompt. Since it | |
2026 | exposes IPython's processing machinery, the given strings can contain |
|
2026 | exposes IPython's processing machinery, the given strings can contain | |
2027 | magic calls (%magic), special shell access (!cmd), etc. |
|
2027 | magic calls (%magic), special shell access (!cmd), etc. | |
2028 | """ |
|
2028 | """ | |
2029 |
|
2029 | |||
2030 | if isinstance(lines, (list, tuple)): |
|
2030 | if isinstance(lines, (list, tuple)): | |
2031 | lines = '\n'.join(lines) |
|
2031 | lines = '\n'.join(lines) | |
2032 |
|
2032 | |||
2033 | if clean: |
|
2033 | if clean: | |
2034 | lines = self.cleanup_ipy_script(lines) |
|
2034 | lines = self.cleanup_ipy_script(lines) | |
2035 |
|
2035 | |||
2036 | # We must start with a clean buffer, in case this is run from an |
|
2036 | # We must start with a clean buffer, in case this is run from an | |
2037 | # interactive IPython session (via a magic, for example). |
|
2037 | # interactive IPython session (via a magic, for example). | |
2038 | self.resetbuffer() |
|
2038 | self.resetbuffer() | |
2039 | lines = lines.splitlines() |
|
2039 | lines = lines.splitlines() | |
2040 | more = 0 |
|
2040 | more = 0 | |
2041 |
|
2041 | |||
2042 | with nested(self.builtin_trap, self.display_trap): |
|
2042 | with nested(self.builtin_trap, self.display_trap): | |
2043 | for line in lines: |
|
2043 | for line in lines: | |
2044 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2044 | # skip blank lines so we don't mess up the prompt counter, but do | |
2045 | # NOT skip even a blank line if we are in a code block (more is |
|
2045 | # NOT skip even a blank line if we are in a code block (more is | |
2046 | # true) |
|
2046 | # true) | |
2047 |
|
2047 | |||
2048 | if line or more: |
|
2048 | if line or more: | |
2049 | # push to raw history, so hist line numbers stay in sync |
|
2049 | # push to raw history, so hist line numbers stay in sync | |
2050 | self.input_hist_raw.append("# " + line + "\n") |
|
2050 | self.input_hist_raw.append("# " + line + "\n") | |
2051 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2051 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) | |
2052 | more = self.push_line(prefiltered) |
|
2052 | more = self.push_line(prefiltered) | |
2053 | # IPython's runsource returns None if there was an error |
|
2053 | # IPython's runsource returns None if there was an error | |
2054 | # compiling the code. This allows us to stop processing right |
|
2054 | # compiling the code. This allows us to stop processing right | |
2055 | # away, so the user gets the error message at the right place. |
|
2055 | # away, so the user gets the error message at the right place. | |
2056 | if more is None: |
|
2056 | if more is None: | |
2057 | break |
|
2057 | break | |
2058 | else: |
|
2058 | else: | |
2059 | self.input_hist_raw.append("\n") |
|
2059 | self.input_hist_raw.append("\n") | |
2060 | # final newline in case the input didn't have it, so that the code |
|
2060 | # final newline in case the input didn't have it, so that the code | |
2061 | # actually does get executed |
|
2061 | # actually does get executed | |
2062 | if more: |
|
2062 | if more: | |
2063 | self.push_line('\n') |
|
2063 | self.push_line('\n') | |
2064 |
|
2064 | |||
2065 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2065 | def runsource(self, source, filename='<input>', symbol='single'): | |
2066 | """Compile and run some source in the interpreter. |
|
2066 | """Compile and run some source in the interpreter. | |
2067 |
|
2067 | |||
2068 | Arguments are as for compile_command(). |
|
2068 | Arguments are as for compile_command(). | |
2069 |
|
2069 | |||
2070 | One several things can happen: |
|
2070 | One several things can happen: | |
2071 |
|
2071 | |||
2072 | 1) The input is incorrect; compile_command() raised an |
|
2072 | 1) The input is incorrect; compile_command() raised an | |
2073 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2073 | exception (SyntaxError or OverflowError). A syntax traceback | |
2074 | will be printed by calling the showsyntaxerror() method. |
|
2074 | will be printed by calling the showsyntaxerror() method. | |
2075 |
|
2075 | |||
2076 | 2) The input is incomplete, and more input is required; |
|
2076 | 2) The input is incomplete, and more input is required; | |
2077 | compile_command() returned None. Nothing happens. |
|
2077 | compile_command() returned None. Nothing happens. | |
2078 |
|
2078 | |||
2079 | 3) The input is complete; compile_command() returned a code |
|
2079 | 3) The input is complete; compile_command() returned a code | |
2080 | object. The code is executed by calling self.runcode() (which |
|
2080 | object. The code is executed by calling self.runcode() (which | |
2081 | also handles run-time exceptions, except for SystemExit). |
|
2081 | also handles run-time exceptions, except for SystemExit). | |
2082 |
|
2082 | |||
2083 | The return value is: |
|
2083 | The return value is: | |
2084 |
|
2084 | |||
2085 | - True in case 2 |
|
2085 | - True in case 2 | |
2086 |
|
2086 | |||
2087 | - False in the other cases, unless an exception is raised, where |
|
2087 | - False in the other cases, unless an exception is raised, where | |
2088 | None is returned instead. This can be used by external callers to |
|
2088 | None is returned instead. This can be used by external callers to | |
2089 | know whether to continue feeding input or not. |
|
2089 | know whether to continue feeding input or not. | |
2090 |
|
2090 | |||
2091 | The return value can be used to decide whether to use sys.ps1 or |
|
2091 | The return value can be used to decide whether to use sys.ps1 or | |
2092 | sys.ps2 to prompt the next line.""" |
|
2092 | sys.ps2 to prompt the next line.""" | |
2093 |
|
2093 | |||
2094 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2094 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2095 | # this allows execution of indented pasted code. It is tempting |
|
2095 | # this allows execution of indented pasted code. It is tempting | |
2096 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2096 | # to add '\n' at the end of source to run commands like ' a=1' | |
2097 | # directly, but this fails for more complicated scenarios |
|
2097 | # directly, but this fails for more complicated scenarios | |
2098 | source=source.encode(self.stdin_encoding) |
|
2098 | source=source.encode(self.stdin_encoding) | |
2099 | if source[:1] in [' ', '\t']: |
|
2099 | if source[:1] in [' ', '\t']: | |
2100 | source = 'if 1:\n%s' % source |
|
2100 | source = 'if 1:\n%s' % source | |
2101 |
|
2101 | |||
2102 | try: |
|
2102 | try: | |
2103 | code = self.compile(source,filename,symbol) |
|
2103 | code = self.compile(source,filename,symbol) | |
2104 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2104 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2105 | # Case 1 |
|
2105 | # Case 1 | |
2106 | self.showsyntaxerror(filename) |
|
2106 | self.showsyntaxerror(filename) | |
2107 | return None |
|
2107 | return None | |
2108 |
|
2108 | |||
2109 | if code is None: |
|
2109 | if code is None: | |
2110 | # Case 2 |
|
2110 | # Case 2 | |
2111 | return True |
|
2111 | return True | |
2112 |
|
2112 | |||
2113 | # Case 3 |
|
2113 | # Case 3 | |
2114 | # We store the code object so that threaded shells and |
|
2114 | # We store the code object so that threaded shells and | |
2115 | # custom exception handlers can access all this info if needed. |
|
2115 | # custom exception handlers can access all this info if needed. | |
2116 | # The source corresponding to this can be obtained from the |
|
2116 | # The source corresponding to this can be obtained from the | |
2117 | # buffer attribute as '\n'.join(self.buffer). |
|
2117 | # buffer attribute as '\n'.join(self.buffer). | |
2118 | self.code_to_run = code |
|
2118 | self.code_to_run = code | |
2119 | # now actually execute the code object |
|
2119 | # now actually execute the code object | |
2120 | if self.runcode(code) == 0: |
|
2120 | if self.runcode(code) == 0: | |
2121 | return False |
|
2121 | return False | |
2122 | else: |
|
2122 | else: | |
2123 | return None |
|
2123 | return None | |
2124 |
|
2124 | |||
2125 | def runcode(self,code_obj): |
|
2125 | def runcode(self,code_obj): | |
2126 | """Execute a code object. |
|
2126 | """Execute a code object. | |
2127 |
|
2127 | |||
2128 | When an exception occurs, self.showtraceback() is called to display a |
|
2128 | When an exception occurs, self.showtraceback() is called to display a | |
2129 | traceback. |
|
2129 | traceback. | |
2130 |
|
2130 | |||
2131 | Return value: a flag indicating whether the code to be run completed |
|
2131 | Return value: a flag indicating whether the code to be run completed | |
2132 | successfully: |
|
2132 | successfully: | |
2133 |
|
2133 | |||
2134 | - 0: successful execution. |
|
2134 | - 0: successful execution. | |
2135 | - 1: an error occurred. |
|
2135 | - 1: an error occurred. | |
2136 | """ |
|
2136 | """ | |
2137 |
|
2137 | |||
2138 | # Set our own excepthook in case the user code tries to call it |
|
2138 | # Set our own excepthook in case the user code tries to call it | |
2139 | # directly, so that the IPython crash handler doesn't get triggered |
|
2139 | # directly, so that the IPython crash handler doesn't get triggered | |
2140 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2140 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2141 |
|
2141 | |||
2142 | # we save the original sys.excepthook in the instance, in case config |
|
2142 | # we save the original sys.excepthook in the instance, in case config | |
2143 | # code (such as magics) needs access to it. |
|
2143 | # code (such as magics) needs access to it. | |
2144 | self.sys_excepthook = old_excepthook |
|
2144 | self.sys_excepthook = old_excepthook | |
2145 | outflag = 1 # happens in more places, so it's easier as default |
|
2145 | outflag = 1 # happens in more places, so it's easier as default | |
2146 | try: |
|
2146 | try: | |
2147 | try: |
|
2147 | try: | |
2148 | self.hooks.pre_runcode_hook() |
|
2148 | self.hooks.pre_runcode_hook() | |
2149 | exec code_obj in self.user_global_ns, self.user_ns |
|
2149 | exec code_obj in self.user_global_ns, self.user_ns | |
2150 | finally: |
|
2150 | finally: | |
2151 | # Reset our crash handler in place |
|
2151 | # Reset our crash handler in place | |
2152 | sys.excepthook = old_excepthook |
|
2152 | sys.excepthook = old_excepthook | |
2153 | except SystemExit: |
|
2153 | except SystemExit: | |
2154 | self.resetbuffer() |
|
2154 | self.resetbuffer() | |
2155 | self.showtraceback() |
|
2155 | self.showtraceback(exception_only=True) | |
2156 | warn("Type %exit or %quit to exit IPython " |
|
2156 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2157 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
|||
2158 | except self.custom_exceptions: |
|
2157 | except self.custom_exceptions: | |
2159 | etype,value,tb = sys.exc_info() |
|
2158 | etype,value,tb = sys.exc_info() | |
2160 | self.CustomTB(etype,value,tb) |
|
2159 | self.CustomTB(etype,value,tb) | |
2161 | except: |
|
2160 | except: | |
2162 | self.showtraceback() |
|
2161 | self.showtraceback() | |
2163 | else: |
|
2162 | else: | |
2164 | outflag = 0 |
|
2163 | outflag = 0 | |
2165 | if softspace(sys.stdout, 0): |
|
2164 | if softspace(sys.stdout, 0): | |
2166 |
|
2165 | |||
2167 | # Flush out code object which has been run (and source) |
|
2166 | # Flush out code object which has been run (and source) | |
2168 | self.code_to_run = None |
|
2167 | self.code_to_run = None | |
2169 | return outflag |
|
2168 | return outflag | |
2170 |
|
2169 | |||
2171 | def push_line(self, line): |
|
2170 | def push_line(self, line): | |
2172 | """Push a line to the interpreter. |
|
2171 | """Push a line to the interpreter. | |
2173 |
|
2172 | |||
2174 | The line should not have a trailing newline; it may have |
|
2173 | The line should not have a trailing newline; it may have | |
2175 | internal newlines. The line is appended to a buffer and the |
|
2174 | internal newlines. The line is appended to a buffer and the | |
2176 | interpreter's runsource() method is called with the |
|
2175 | interpreter's runsource() method is called with the | |
2177 | concatenated contents of the buffer as source. If this |
|
2176 | concatenated contents of the buffer as source. If this | |
2178 | indicates that the command was executed or invalid, the buffer |
|
2177 | indicates that the command was executed or invalid, the buffer | |
2179 | is reset; otherwise, the command is incomplete, and the buffer |
|
2178 | is reset; otherwise, the command is incomplete, and the buffer | |
2180 | is left as it was after the line was appended. The return |
|
2179 | is left as it was after the line was appended. The return | |
2181 | value is 1 if more input is required, 0 if the line was dealt |
|
2180 | value is 1 if more input is required, 0 if the line was dealt | |
2182 | with in some way (this is the same as runsource()). |
|
2181 | with in some way (this is the same as runsource()). | |
2183 | """ |
|
2182 | """ | |
2184 |
|
2183 | |||
2185 | # autoindent management should be done here, and not in the |
|
2184 | # autoindent management should be done here, and not in the | |
2186 | # interactive loop, since that one is only seen by keyboard input. We |
|
2185 | # interactive loop, since that one is only seen by keyboard input. We | |
2187 | # need this done correctly even for code run via runlines (which uses |
|
2186 | # need this done correctly even for code run via runlines (which uses | |
2188 | # push). |
|
2187 | # push). | |
2189 |
|
2188 | |||
2190 | #print 'push line: <%s>' % line # dbg |
|
2189 | #print 'push line: <%s>' % line # dbg | |
2191 | for subline in line.splitlines(): |
|
2190 | for subline in line.splitlines(): | |
2192 | self._autoindent_update(subline) |
|
2191 | self._autoindent_update(subline) | |
2193 | self.buffer.append(line) |
|
2192 | self.buffer.append(line) | |
2194 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2193 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2195 | if not more: |
|
2194 | if not more: | |
2196 | self.resetbuffer() |
|
2195 | self.resetbuffer() | |
2197 | return more |
|
2196 | return more | |
2198 |
|
2197 | |||
2199 | def _autoindent_update(self,line): |
|
2198 | def _autoindent_update(self,line): | |
2200 | """Keep track of the indent level.""" |
|
2199 | """Keep track of the indent level.""" | |
2201 |
|
2200 | |||
2202 | #debugx('line') |
|
2201 | #debugx('line') | |
2203 | #debugx('self.indent_current_nsp') |
|
2202 | #debugx('self.indent_current_nsp') | |
2204 | if self.autoindent: |
|
2203 | if self.autoindent: | |
2205 | if line: |
|
2204 | if line: | |
2206 | inisp = num_ini_spaces(line) |
|
2205 | inisp = num_ini_spaces(line) | |
2207 | if inisp < self.indent_current_nsp: |
|
2206 | if inisp < self.indent_current_nsp: | |
2208 | self.indent_current_nsp = inisp |
|
2207 | self.indent_current_nsp = inisp | |
2209 |
|
2208 | |||
2210 | if line[-1] == ':': |
|
2209 | if line[-1] == ':': | |
2211 | self.indent_current_nsp += 4 |
|
2210 | self.indent_current_nsp += 4 | |
2212 | elif dedent_re.match(line): |
|
2211 | elif dedent_re.match(line): | |
2213 | self.indent_current_nsp -= 4 |
|
2212 | self.indent_current_nsp -= 4 | |
2214 | else: |
|
2213 | else: | |
2215 | self.indent_current_nsp = 0 |
|
2214 | self.indent_current_nsp = 0 | |
2216 |
|
2215 | |||
2217 | def resetbuffer(self): |
|
2216 | def resetbuffer(self): | |
2218 | """Reset the input buffer.""" |
|
2217 | """Reset the input buffer.""" | |
2219 | self.buffer[:] = [] |
|
2218 | self.buffer[:] = [] | |
2220 |
|
2219 | |||
2221 | def raw_input(self,prompt='',continue_prompt=False): |
|
2220 | def raw_input(self,prompt='',continue_prompt=False): | |
2222 | """Write a prompt and read a line. |
|
2221 | """Write a prompt and read a line. | |
2223 |
|
2222 | |||
2224 | The returned line does not include the trailing newline. |
|
2223 | The returned line does not include the trailing newline. | |
2225 | When the user enters the EOF key sequence, EOFError is raised. |
|
2224 | When the user enters the EOF key sequence, EOFError is raised. | |
2226 |
|
2225 | |||
2227 | Optional inputs: |
|
2226 | Optional inputs: | |
2228 |
|
2227 | |||
2229 | - prompt(''): a string to be printed to prompt the user. |
|
2228 | - prompt(''): a string to be printed to prompt the user. | |
2230 |
|
2229 | |||
2231 | - continue_prompt(False): whether this line is the first one or a |
|
2230 | - continue_prompt(False): whether this line is the first one or a | |
2232 | continuation in a sequence of inputs. |
|
2231 | continuation in a sequence of inputs. | |
2233 | """ |
|
2232 | """ | |
2234 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2233 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) | |
2235 |
|
2234 | |||
2236 | # Code run by the user may have modified the readline completer state. |
|
2235 | # Code run by the user may have modified the readline completer state. | |
2237 | # We must ensure that our completer is back in place. |
|
2236 | # We must ensure that our completer is back in place. | |
2238 |
|
2237 | |||
2239 | if self.has_readline: |
|
2238 | if self.has_readline: | |
2240 | self.set_completer() |
|
2239 | self.set_completer() | |
2241 |
|
2240 | |||
2242 | try: |
|
2241 | try: | |
2243 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2242 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2244 | except ValueError: |
|
2243 | except ValueError: | |
2245 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2244 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2246 | " or sys.stdout.close()!\nExiting IPython!") |
|
2245 | " or sys.stdout.close()!\nExiting IPython!") | |
2247 | self.ask_exit() |
|
2246 | self.ask_exit() | |
2248 | return "" |
|
2247 | return "" | |
2249 |
|
2248 | |||
2250 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2249 | # Try to be reasonably smart about not re-indenting pasted input more | |
2251 | # than necessary. We do this by trimming out the auto-indent initial |
|
2250 | # than necessary. We do this by trimming out the auto-indent initial | |
2252 | # spaces, if the user's actual input started itself with whitespace. |
|
2251 | # spaces, if the user's actual input started itself with whitespace. | |
2253 | #debugx('self.buffer[-1]') |
|
2252 | #debugx('self.buffer[-1]') | |
2254 |
|
2253 | |||
2255 | if self.autoindent: |
|
2254 | if self.autoindent: | |
2256 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2255 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2257 | line = line[self.indent_current_nsp:] |
|
2256 | line = line[self.indent_current_nsp:] | |
2258 | self.indent_current_nsp = 0 |
|
2257 | self.indent_current_nsp = 0 | |
2259 |
|
2258 | |||
2260 | # store the unfiltered input before the user has any chance to modify |
|
2259 | # store the unfiltered input before the user has any chance to modify | |
2261 | # it. |
|
2260 | # it. | |
2262 | if line.strip(): |
|
2261 | if line.strip(): | |
2263 | if continue_prompt: |
|
2262 | if continue_prompt: | |
2264 | self.input_hist_raw[-1] += '%s\n' % line |
|
2263 | self.input_hist_raw[-1] += '%s\n' % line | |
2265 | if self.has_readline and self.readline_use: |
|
2264 | if self.has_readline and self.readline_use: | |
2266 | try: |
|
2265 | try: | |
2267 | histlen = self.readline.get_current_history_length() |
|
2266 | histlen = self.readline.get_current_history_length() | |
2268 | if histlen > 1: |
|
2267 | if histlen > 1: | |
2269 | newhist = self.input_hist_raw[-1].rstrip() |
|
2268 | newhist = self.input_hist_raw[-1].rstrip() | |
2270 | self.readline.remove_history_item(histlen-1) |
|
2269 | self.readline.remove_history_item(histlen-1) | |
2271 | self.readline.replace_history_item(histlen-2, |
|
2270 | self.readline.replace_history_item(histlen-2, | |
2272 | newhist.encode(self.stdin_encoding)) |
|
2271 | newhist.encode(self.stdin_encoding)) | |
2273 | except AttributeError: |
|
2272 | except AttributeError: | |
2274 | pass # re{move,place}_history_item are new in 2.4. |
|
2273 | pass # re{move,place}_history_item are new in 2.4. | |
2275 | else: |
|
2274 | else: | |
2276 | self.input_hist_raw.append('%s\n' % line) |
|
2275 | self.input_hist_raw.append('%s\n' % line) | |
2277 | # only entries starting at first column go to shadow history |
|
2276 | # only entries starting at first column go to shadow history | |
2278 | if line.lstrip() == line: |
|
2277 | if line.lstrip() == line: | |
2279 | self.shadowhist.add(line.strip()) |
|
2278 | self.shadowhist.add(line.strip()) | |
2280 | elif not continue_prompt: |
|
2279 | elif not continue_prompt: | |
2281 | self.input_hist_raw.append('\n') |
|
2280 | self.input_hist_raw.append('\n') | |
2282 | try: |
|
2281 | try: | |
2283 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2282 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
2284 | except: |
|
2283 | except: | |
2285 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2284 | # blanket except, in case a user-defined prefilter crashes, so it | |
2286 | # can't take all of ipython with it. |
|
2285 | # can't take all of ipython with it. | |
2287 | self.showtraceback() |
|
2286 | self.showtraceback() | |
2288 | return '' |
|
2287 | return '' | |
2289 | else: |
|
2288 | else: | |
2290 | return lineout |
|
2289 | return lineout | |
2291 |
|
2290 | |||
2292 | #------------------------------------------------------------------------- |
|
2291 | #------------------------------------------------------------------------- | |
2293 | # Working with components |
|
2292 | # Working with components | |
2294 | #------------------------------------------------------------------------- |
|
2293 | #------------------------------------------------------------------------- | |
2295 |
|
2294 | |||
2296 | def get_component(self, name=None, klass=None): |
|
2295 | def get_component(self, name=None, klass=None): | |
2297 | """Fetch a component by name and klass in my tree.""" |
|
2296 | """Fetch a component by name and klass in my tree.""" | |
2298 | c = Component.get_instances(root=self, name=name, klass=klass) |
|
2297 | c = Component.get_instances(root=self, name=name, klass=klass) | |
2299 | if len(c) == 0: |
|
2298 | if len(c) == 0: | |
2300 | return None |
|
2299 | return None | |
2301 | if len(c) == 1: |
|
2300 | if len(c) == 1: | |
2302 | return c[0] |
|
2301 | return c[0] | |
2303 | else: |
|
2302 | else: | |
2304 | return c |
|
2303 | return c | |
2305 |
|
2304 | |||
2306 | #------------------------------------------------------------------------- |
|
2305 | #------------------------------------------------------------------------- | |
2307 | # IPython extensions |
|
2306 | # IPython extensions | |
2308 | #------------------------------------------------------------------------- |
|
2307 | #------------------------------------------------------------------------- | |
2309 |
|
2308 | |||
2310 | def load_extension(self, module_str): |
|
2309 | def load_extension(self, module_str): | |
2311 | """Load an IPython extension by its module name. |
|
2310 | """Load an IPython extension by its module name. | |
2312 |
|
2311 | |||
2313 | An IPython extension is an importable Python module that has |
|
2312 | An IPython extension is an importable Python module that has | |
2314 | a function with the signature:: |
|
2313 | a function with the signature:: | |
2315 |
|
2314 | |||
2316 | def load_ipython_extension(ipython): |
|
2315 | def load_ipython_extension(ipython): | |
2317 | # Do things with ipython |
|
2316 | # Do things with ipython | |
2318 |
|
2317 | |||
2319 | This function is called after your extension is imported and the |
|
2318 | This function is called after your extension is imported and the | |
2320 | currently active :class:`InteractiveShell` instance is passed as |
|
2319 | currently active :class:`InteractiveShell` instance is passed as | |
2321 | the only argument. You can do anything you want with IPython at |
|
2320 | the only argument. You can do anything you want with IPython at | |
2322 | that point, including defining new magic and aliases, adding new |
|
2321 | that point, including defining new magic and aliases, adding new | |
2323 | components, etc. |
|
2322 | components, etc. | |
2324 |
|
2323 | |||
2325 | The :func:`load_ipython_extension` will be called again is you |
|
2324 | The :func:`load_ipython_extension` will be called again is you | |
2326 | load or reload the extension again. It is up to the extension |
|
2325 | load or reload the extension again. It is up to the extension | |
2327 | author to add code to manage that. |
|
2326 | author to add code to manage that. | |
2328 |
|
2327 | |||
2329 | You can put your extension modules anywhere you want, as long as |
|
2328 | You can put your extension modules anywhere you want, as long as | |
2330 | they can be imported by Python's standard import mechanism. However, |
|
2329 | they can be imported by Python's standard import mechanism. However, | |
2331 | to make it easy to write extensions, you can also put your extensions |
|
2330 | to make it easy to write extensions, you can also put your extensions | |
2332 | in ``os.path.join(self.ipython_dir, 'extensions')``. This directory |
|
2331 | in ``os.path.join(self.ipython_dir, 'extensions')``. This directory | |
2333 | is added to ``sys.path`` automatically. |
|
2332 | is added to ``sys.path`` automatically. | |
2334 | """ |
|
2333 | """ | |
2335 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2334 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2336 |
|
2335 | |||
2337 | if module_str not in sys.modules: |
|
2336 | if module_str not in sys.modules: | |
2338 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2337 | with prepended_to_syspath(self.ipython_extension_dir): | |
2339 | __import__(module_str) |
|
2338 | __import__(module_str) | |
2340 | mod = sys.modules[module_str] |
|
2339 | mod = sys.modules[module_str] | |
2341 | return self._call_load_ipython_extension(mod) |
|
2340 | return self._call_load_ipython_extension(mod) | |
2342 |
|
2341 | |||
2343 | def unload_extension(self, module_str): |
|
2342 | def unload_extension(self, module_str): | |
2344 | """Unload an IPython extension by its module name. |
|
2343 | """Unload an IPython extension by its module name. | |
2345 |
|
2344 | |||
2346 | This function looks up the extension's name in ``sys.modules`` and |
|
2345 | This function looks up the extension's name in ``sys.modules`` and | |
2347 | simply calls ``mod.unload_ipython_extension(self)``. |
|
2346 | simply calls ``mod.unload_ipython_extension(self)``. | |
2348 | """ |
|
2347 | """ | |
2349 | if module_str in sys.modules: |
|
2348 | if module_str in sys.modules: | |
2350 | mod = sys.modules[module_str] |
|
2349 | mod = sys.modules[module_str] | |
2351 | self._call_unload_ipython_extension(mod) |
|
2350 | self._call_unload_ipython_extension(mod) | |
2352 |
|
2351 | |||
2353 | def reload_extension(self, module_str): |
|
2352 | def reload_extension(self, module_str): | |
2354 | """Reload an IPython extension by calling reload. |
|
2353 | """Reload an IPython extension by calling reload. | |
2355 |
|
2354 | |||
2356 | If the module has not been loaded before, |
|
2355 | If the module has not been loaded before, | |
2357 | :meth:`InteractiveShell.load_extension` is called. Otherwise |
|
2356 | :meth:`InteractiveShell.load_extension` is called. Otherwise | |
2358 | :func:`reload` is called and then the :func:`load_ipython_extension` |
|
2357 | :func:`reload` is called and then the :func:`load_ipython_extension` | |
2359 | function of the module, if it exists is called. |
|
2358 | function of the module, if it exists is called. | |
2360 | """ |
|
2359 | """ | |
2361 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2360 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2362 |
|
2361 | |||
2363 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2362 | with prepended_to_syspath(self.ipython_extension_dir): | |
2364 | if module_str in sys.modules: |
|
2363 | if module_str in sys.modules: | |
2365 | mod = sys.modules[module_str] |
|
2364 | mod = sys.modules[module_str] | |
2366 | reload(mod) |
|
2365 | reload(mod) | |
2367 | self._call_load_ipython_extension(mod) |
|
2366 | self._call_load_ipython_extension(mod) | |
2368 | else: |
|
2367 | else: | |
2369 | self.load_extension(module_str) |
|
2368 | self.load_extension(module_str) | |
2370 |
|
2369 | |||
2371 | def _call_load_ipython_extension(self, mod): |
|
2370 | def _call_load_ipython_extension(self, mod): | |
2372 | if hasattr(mod, 'load_ipython_extension'): |
|
2371 | if hasattr(mod, 'load_ipython_extension'): | |
2373 | return mod.load_ipython_extension(self) |
|
2372 | return mod.load_ipython_extension(self) | |
2374 |
|
2373 | |||
2375 | def _call_unload_ipython_extension(self, mod): |
|
2374 | def _call_unload_ipython_extension(self, mod): | |
2376 | if hasattr(mod, 'unload_ipython_extension'): |
|
2375 | if hasattr(mod, 'unload_ipython_extension'): | |
2377 | return mod.unload_ipython_extension(self) |
|
2376 | return mod.unload_ipython_extension(self) | |
2378 |
|
2377 | |||
2379 | #------------------------------------------------------------------------- |
|
2378 | #------------------------------------------------------------------------- | |
2380 | # Things related to the prefilter |
|
2379 | # Things related to the prefilter | |
2381 | #------------------------------------------------------------------------- |
|
2380 | #------------------------------------------------------------------------- | |
2382 |
|
2381 | |||
2383 | def init_prefilter(self): |
|
2382 | def init_prefilter(self): | |
2384 | self.prefilter_manager = PrefilterManager(self, config=self.config) |
|
2383 | self.prefilter_manager = PrefilterManager(self, config=self.config) | |
2385 | # Ultimately this will be refactored in the new interpreter code, but |
|
2384 | # Ultimately this will be refactored in the new interpreter code, but | |
2386 | # for now, we should expose the main prefilter method (there's legacy |
|
2385 | # for now, we should expose the main prefilter method (there's legacy | |
2387 | # code out there that may rely on this). |
|
2386 | # code out there that may rely on this). | |
2388 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2387 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2389 |
|
2388 | |||
2390 | #------------------------------------------------------------------------- |
|
2389 | #------------------------------------------------------------------------- | |
2391 | # Utilities |
|
2390 | # Utilities | |
2392 | #------------------------------------------------------------------------- |
|
2391 | #------------------------------------------------------------------------- | |
2393 |
|
2392 | |||
2394 | def getoutput(self, cmd): |
|
2393 | def getoutput(self, cmd): | |
2395 | return getoutput(self.var_expand(cmd,depth=2), |
|
2394 | return getoutput(self.var_expand(cmd,depth=2), | |
2396 | header=self.system_header, |
|
2395 | header=self.system_header, | |
2397 | verbose=self.system_verbose) |
|
2396 | verbose=self.system_verbose) | |
2398 |
|
2397 | |||
2399 | def getoutputerror(self, cmd): |
|
2398 | def getoutputerror(self, cmd): | |
2400 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2399 | return getoutputerror(self.var_expand(cmd,depth=2), | |
2401 | header=self.system_header, |
|
2400 | header=self.system_header, | |
2402 | verbose=self.system_verbose) |
|
2401 | verbose=self.system_verbose) | |
2403 |
|
2402 | |||
2404 | def var_expand(self,cmd,depth=0): |
|
2403 | def var_expand(self,cmd,depth=0): | |
2405 | """Expand python variables in a string. |
|
2404 | """Expand python variables in a string. | |
2406 |
|
2405 | |||
2407 | The depth argument indicates how many frames above the caller should |
|
2406 | The depth argument indicates how many frames above the caller should | |
2408 | be walked to look for the local namespace where to expand variables. |
|
2407 | be walked to look for the local namespace where to expand variables. | |
2409 |
|
2408 | |||
2410 | The global namespace for expansion is always the user's interactive |
|
2409 | The global namespace for expansion is always the user's interactive | |
2411 | namespace. |
|
2410 | namespace. | |
2412 | """ |
|
2411 | """ | |
2413 |
|
2412 | |||
2414 | return str(ItplNS(cmd, |
|
2413 | return str(ItplNS(cmd, | |
2415 | self.user_ns, # globals |
|
2414 | self.user_ns, # globals | |
2416 | # Skip our own frame in searching for locals: |
|
2415 | # Skip our own frame in searching for locals: | |
2417 | sys._getframe(depth+1).f_locals # locals |
|
2416 | sys._getframe(depth+1).f_locals # locals | |
2418 | )) |
|
2417 | )) | |
2419 |
|
2418 | |||
2420 | def mktempfile(self,data=None): |
|
2419 | def mktempfile(self,data=None): | |
2421 | """Make a new tempfile and return its filename. |
|
2420 | """Make a new tempfile and return its filename. | |
2422 |
|
2421 | |||
2423 | This makes a call to tempfile.mktemp, but it registers the created |
|
2422 | This makes a call to tempfile.mktemp, but it registers the created | |
2424 | filename internally so ipython cleans it up at exit time. |
|
2423 | filename internally so ipython cleans it up at exit time. | |
2425 |
|
2424 | |||
2426 | Optional inputs: |
|
2425 | Optional inputs: | |
2427 |
|
2426 | |||
2428 | - data(None): if data is given, it gets written out to the temp file |
|
2427 | - data(None): if data is given, it gets written out to the temp file | |
2429 | immediately, and the file is closed again.""" |
|
2428 | immediately, and the file is closed again.""" | |
2430 |
|
2429 | |||
2431 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2430 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2432 | self.tempfiles.append(filename) |
|
2431 | self.tempfiles.append(filename) | |
2433 |
|
2432 | |||
2434 | if data: |
|
2433 | if data: | |
2435 | tmp_file = open(filename,'w') |
|
2434 | tmp_file = open(filename,'w') | |
2436 | tmp_file.write(data) |
|
2435 | tmp_file.write(data) | |
2437 | tmp_file.close() |
|
2436 | tmp_file.close() | |
2438 | return filename |
|
2437 | return filename | |
2439 |
|
2438 | |||
2440 | def write(self,data): |
|
2439 | def write(self,data): | |
2441 | """Write a string to the default output""" |
|
2440 | """Write a string to the default output""" | |
2442 | Term.cout.write(data) |
|
2441 | Term.cout.write(data) | |
2443 |
|
2442 | |||
2444 | def write_err(self,data): |
|
2443 | def write_err(self,data): | |
2445 | """Write a string to the default error output""" |
|
2444 | """Write a string to the default error output""" | |
2446 | Term.cerr.write(data) |
|
2445 | Term.cerr.write(data) | |
2447 |
|
2446 | |||
2448 | def ask_yes_no(self,prompt,default=True): |
|
2447 | def ask_yes_no(self,prompt,default=True): | |
2449 | if self.quiet: |
|
2448 | if self.quiet: | |
2450 | return True |
|
2449 | return True | |
2451 | return ask_yes_no(prompt,default) |
|
2450 | return ask_yes_no(prompt,default) | |
2452 |
|
2451 | |||
2453 | #------------------------------------------------------------------------- |
|
2452 | #------------------------------------------------------------------------- | |
2454 | # Things related to GUI support and pylab |
|
2453 | # Things related to GUI support and pylab | |
2455 | #------------------------------------------------------------------------- |
|
2454 | #------------------------------------------------------------------------- | |
2456 |
|
2455 | |||
2457 | def enable_pylab(self, gui=None): |
|
2456 | def enable_pylab(self, gui=None): | |
2458 | """Activate pylab support at runtime. |
|
2457 | """Activate pylab support at runtime. | |
2459 |
|
2458 | |||
2460 | This turns on support for matplotlib, preloads into the interactive |
|
2459 | This turns on support for matplotlib, preloads into the interactive | |
2461 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
2460 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
2462 | interact with the GUI event loop. The GUI backend to be used can be |
|
2461 | interact with the GUI event loop. The GUI backend to be used can be | |
2463 | optionally selected with the optional :param:`gui` argument. |
|
2462 | optionally selected with the optional :param:`gui` argument. | |
2464 |
|
2463 | |||
2465 | Parameters |
|
2464 | Parameters | |
2466 | ---------- |
|
2465 | ---------- | |
2467 | gui : optional, string |
|
2466 | gui : optional, string | |
2468 |
|
2467 | |||
2469 | If given, dictates the choice of matplotlib GUI backend to use |
|
2468 | If given, dictates the choice of matplotlib GUI backend to use | |
2470 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
2469 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
2471 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
2470 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
2472 | dictated by the matplotlib build-time options plus the user's |
|
2471 | dictated by the matplotlib build-time options plus the user's | |
2473 | matplotlibrc configuration file). |
|
2472 | matplotlibrc configuration file). | |
2474 | """ |
|
2473 | """ | |
2475 | # We want to prevent the loading of pylab to pollute the user's |
|
2474 | # We want to prevent the loading of pylab to pollute the user's | |
2476 | # namespace as shown by the %who* magics, so we execute the activation |
|
2475 | # namespace as shown by the %who* magics, so we execute the activation | |
2477 | # code in an empty namespace, and we update *both* user_ns and |
|
2476 | # code in an empty namespace, and we update *both* user_ns and | |
2478 | # user_config_ns with this information. |
|
2477 | # user_config_ns with this information. | |
2479 | ns = {} |
|
2478 | ns = {} | |
2480 | gui = pylab_activate(ns, gui) |
|
2479 | gui = pylab_activate(ns, gui) | |
2481 | self.user_ns.update(ns) |
|
2480 | self.user_ns.update(ns) | |
2482 | self.user_config_ns.update(ns) |
|
2481 | self.user_config_ns.update(ns) | |
2483 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2482 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2484 | # plot updates into account |
|
2483 | # plot updates into account | |
2485 | enable_gui(gui) |
|
2484 | enable_gui(gui) | |
2486 | self.magic_run = self._pylab_magic_run |
|
2485 | self.magic_run = self._pylab_magic_run | |
2487 |
|
2486 | |||
2488 | #------------------------------------------------------------------------- |
|
2487 | #------------------------------------------------------------------------- | |
2489 | # Things related to IPython exiting |
|
2488 | # Things related to IPython exiting | |
2490 | #------------------------------------------------------------------------- |
|
2489 | #------------------------------------------------------------------------- | |
2491 |
|
2490 | |||
2492 | def ask_exit(self): |
|
2491 | def ask_exit(self): | |
2493 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
2492 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
2494 | self.exit_now = True |
|
2493 | self.exit_now = True | |
2495 |
|
2494 | |||
2496 | def exit(self): |
|
2495 | def exit(self): | |
2497 | """Handle interactive exit. |
|
2496 | """Handle interactive exit. | |
2498 |
|
2497 | |||
2499 | This method calls the ask_exit callback.""" |
|
2498 | This method calls the ask_exit callback.""" | |
2500 | if self.confirm_exit: |
|
2499 | if self.confirm_exit: | |
2501 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2500 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2502 | self.ask_exit() |
|
2501 | self.ask_exit() | |
2503 | else: |
|
2502 | else: | |
2504 | self.ask_exit() |
|
2503 | self.ask_exit() | |
2505 |
|
2504 | |||
2506 | def atexit_operations(self): |
|
2505 | def atexit_operations(self): | |
2507 | """This will be executed at the time of exit. |
|
2506 | """This will be executed at the time of exit. | |
2508 |
|
2507 | |||
2509 | Saving of persistent data should be performed here. |
|
2508 | Saving of persistent data should be performed here. | |
2510 | """ |
|
2509 | """ | |
2511 | self.savehist() |
|
2510 | self.savehist() | |
2512 |
|
2511 | |||
2513 | # Cleanup all tempfiles left around |
|
2512 | # Cleanup all tempfiles left around | |
2514 | for tfile in self.tempfiles: |
|
2513 | for tfile in self.tempfiles: | |
2515 | try: |
|
2514 | try: | |
2516 | os.unlink(tfile) |
|
2515 | os.unlink(tfile) | |
2517 | except OSError: |
|
2516 | except OSError: | |
2518 | pass |
|
2517 | pass | |
2519 |
|
2518 | |||
2520 | # Clear all user namespaces to release all references cleanly. |
|
2519 | # Clear all user namespaces to release all references cleanly. | |
2521 | self.reset() |
|
2520 | self.reset() | |
2522 |
|
2521 | |||
2523 | # Run user hooks |
|
2522 | # Run user hooks | |
2524 | self.hooks.shutdown_hook() |
|
2523 | self.hooks.shutdown_hook() | |
2525 |
|
2524 | |||
2526 | def cleanup(self): |
|
2525 | def cleanup(self): | |
2527 | self.restore_sys_module_state() |
|
2526 | self.restore_sys_module_state() | |
2528 |
|
2527 | |||
2529 |
|
2528 |
@@ -1,3606 +1,3612 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: 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-2006 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
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 | # Modules and globals |
|
14 | # Modules and globals | |
15 |
|
15 | |||
16 | # Python standard modules |
|
16 | # Python standard modules | |
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import pdb |
|
21 | import pdb | |
22 | import pydoc |
|
22 | import pydoc | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import tempfile |
|
26 | import tempfile | |
27 | import time |
|
27 | import time | |
28 | import cPickle as pickle |
|
28 | import cPickle as pickle | |
29 | import textwrap |
|
29 | import textwrap | |
30 | from cStringIO import StringIO |
|
30 | from cStringIO import StringIO | |
31 | from getopt import getopt,GetoptError |
|
31 | from getopt import getopt,GetoptError | |
32 | from pprint import pprint, pformat |
|
32 | from pprint import pprint, pformat | |
33 |
|
33 | |||
34 | # cProfile was added in Python2.5 |
|
34 | # cProfile was added in Python2.5 | |
35 | try: |
|
35 | try: | |
36 | import cProfile as profile |
|
36 | import cProfile as profile | |
37 | import pstats |
|
37 | import pstats | |
38 | except ImportError: |
|
38 | except ImportError: | |
39 | # profile isn't bundled by default in Debian for license reasons |
|
39 | # profile isn't bundled by default in Debian for license reasons | |
40 | try: |
|
40 | try: | |
41 | import profile,pstats |
|
41 | import profile,pstats | |
42 | except ImportError: |
|
42 | except ImportError: | |
43 | profile = pstats = None |
|
43 | profile = pstats = None | |
44 |
|
44 | |||
45 | # Homebrewed |
|
45 | # Homebrewed | |
46 | import IPython |
|
46 | import IPython | |
47 | import IPython.utils.generics |
|
47 | import IPython.utils.generics | |
48 |
|
48 | |||
49 | from IPython.core import debugger, oinspect |
|
49 | from IPython.core import debugger, oinspect | |
50 | from IPython.core.error import TryNext |
|
50 | from IPython.core.error import TryNext | |
51 | from IPython.core.error import UsageError |
|
51 | from IPython.core.error import UsageError | |
52 | from IPython.core.fakemodule import FakeModule |
|
52 | from IPython.core.fakemodule import FakeModule | |
53 | from IPython.core.macro import Macro |
|
53 | from IPython.core.macro import Macro | |
54 | from IPython.core.page import page |
|
54 | from IPython.core.page import page | |
55 | from IPython.core.prefilter import ESC_MAGIC |
|
55 | from IPython.core.prefilter import ESC_MAGIC | |
56 | from IPython.core.pylabtools import mpl_runner |
|
56 | from IPython.core.pylabtools import mpl_runner | |
57 | from IPython.lib.inputhook import enable_gui |
|
57 | from IPython.lib.inputhook import enable_gui | |
58 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
58 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns | |
59 | from IPython.testing import decorators as testdec |
|
59 | from IPython.testing import decorators as testdec | |
60 | from IPython.utils import platutils |
|
60 | from IPython.utils import platutils | |
61 | from IPython.utils import wildcard |
|
61 | from IPython.utils import wildcard | |
62 | from IPython.utils.PyColorize import Parser |
|
62 | from IPython.utils.PyColorize import Parser | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 |
|
64 | |||
65 | # XXX - We need to switch to explicit imports here with genutils |
|
65 | # XXX - We need to switch to explicit imports here with genutils | |
66 | from IPython.utils.genutils import * |
|
66 | from IPython.utils.genutils import * | |
67 |
|
67 | |||
68 | #*************************************************************************** |
|
68 | #*************************************************************************** | |
69 | # Utility functions |
|
69 | # Utility functions | |
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Component and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Component and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 |
|
97 | |||
98 | class Magic: |
|
98 | class Magic: | |
99 | """Magic functions for InteractiveShell. |
|
99 | """Magic functions for InteractiveShell. | |
100 |
|
100 | |||
101 | Shell functions which can be reached as %function_name. All magic |
|
101 | Shell functions which can be reached as %function_name. All magic | |
102 | functions should accept a string, which they can parse for their own |
|
102 | functions should accept a string, which they can parse for their own | |
103 | needs. This can make some functions easier to type, eg `%cd ../` |
|
103 | needs. This can make some functions easier to type, eg `%cd ../` | |
104 | vs. `%cd("../")` |
|
104 | vs. `%cd("../")` | |
105 |
|
105 | |||
106 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
106 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
107 | at the command line, but it is is needed in the definition. """ |
|
107 | at the command line, but it is is needed in the definition. """ | |
108 |
|
108 | |||
109 | # class globals |
|
109 | # class globals | |
110 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
110 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
111 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
111 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
112 |
|
112 | |||
113 | #...................................................................... |
|
113 | #...................................................................... | |
114 | # some utility functions |
|
114 | # some utility functions | |
115 |
|
115 | |||
116 | def __init__(self,shell): |
|
116 | def __init__(self,shell): | |
117 |
|
117 | |||
118 | self.options_table = {} |
|
118 | self.options_table = {} | |
119 | if profile is None: |
|
119 | if profile is None: | |
120 | self.magic_prun = self.profile_missing_notice |
|
120 | self.magic_prun = self.profile_missing_notice | |
121 | self.shell = shell |
|
121 | self.shell = shell | |
122 |
|
122 | |||
123 | # namespace for holding state we may need |
|
123 | # namespace for holding state we may need | |
124 | self._magic_state = Bunch() |
|
124 | self._magic_state = Bunch() | |
125 |
|
125 | |||
126 | def profile_missing_notice(self, *args, **kwargs): |
|
126 | def profile_missing_notice(self, *args, **kwargs): | |
127 | error("""\ |
|
127 | error("""\ | |
128 | The profile module could not be found. It has been removed from the standard |
|
128 | The profile module could not be found. It has been removed from the standard | |
129 | python packages because of its non-free license. To use profiling, install the |
|
129 | python packages because of its non-free license. To use profiling, install the | |
130 | python-profiler package from non-free.""") |
|
130 | python-profiler package from non-free.""") | |
131 |
|
131 | |||
132 | def default_option(self,fn,optstr): |
|
132 | def default_option(self,fn,optstr): | |
133 | """Make an entry in the options_table for fn, with value optstr""" |
|
133 | """Make an entry in the options_table for fn, with value optstr""" | |
134 |
|
134 | |||
135 | if fn not in self.lsmagic(): |
|
135 | if fn not in self.lsmagic(): | |
136 | error("%s is not a magic function" % fn) |
|
136 | error("%s is not a magic function" % fn) | |
137 | self.options_table[fn] = optstr |
|
137 | self.options_table[fn] = optstr | |
138 |
|
138 | |||
139 | def lsmagic(self): |
|
139 | def lsmagic(self): | |
140 | """Return a list of currently available magic functions. |
|
140 | """Return a list of currently available magic functions. | |
141 |
|
141 | |||
142 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
142 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
143 | ['magic_ls','magic_cd',...]""" |
|
143 | ['magic_ls','magic_cd',...]""" | |
144 |
|
144 | |||
145 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
145 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
146 |
|
146 | |||
147 | # magics in class definition |
|
147 | # magics in class definition | |
148 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
148 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
149 | callable(Magic.__dict__[fn]) |
|
149 | callable(Magic.__dict__[fn]) | |
150 | # in instance namespace (run-time user additions) |
|
150 | # in instance namespace (run-time user additions) | |
151 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(self.__dict__[fn]) |
|
152 | callable(self.__dict__[fn]) | |
153 | # and bound magics by user (so they can access self): |
|
153 | # and bound magics by user (so they can access self): | |
154 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__class__.__dict__[fn]) |
|
155 | callable(self.__class__.__dict__[fn]) | |
156 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
156 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
157 | filter(inst_magic,self.__dict__.keys()) + \ |
|
157 | filter(inst_magic,self.__dict__.keys()) + \ | |
158 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
158 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
159 | out = [] |
|
159 | out = [] | |
160 | for fn in set(magics): |
|
160 | for fn in set(magics): | |
161 | out.append(fn.replace('magic_','',1)) |
|
161 | out.append(fn.replace('magic_','',1)) | |
162 | out.sort() |
|
162 | out.sort() | |
163 | return out |
|
163 | return out | |
164 |
|
164 | |||
165 | def extract_input_slices(self,slices,raw=False): |
|
165 | def extract_input_slices(self,slices,raw=False): | |
166 | """Return as a string a set of input history slices. |
|
166 | """Return as a string a set of input history slices. | |
167 |
|
167 | |||
168 | Inputs: |
|
168 | Inputs: | |
169 |
|
169 | |||
170 | - slices: the set of slices is given as a list of strings (like |
|
170 | - slices: the set of slices is given as a list of strings (like | |
171 | ['1','4:8','9'], since this function is for use by magic functions |
|
171 | ['1','4:8','9'], since this function is for use by magic functions | |
172 | which get their arguments as strings. |
|
172 | which get their arguments as strings. | |
173 |
|
173 | |||
174 | Optional inputs: |
|
174 | Optional inputs: | |
175 |
|
175 | |||
176 | - raw(False): by default, the processed input is used. If this is |
|
176 | - raw(False): by default, the processed input is used. If this is | |
177 | true, the raw input history is used instead. |
|
177 | true, the raw input history is used instead. | |
178 |
|
178 | |||
179 | Note that slices can be called with two notations: |
|
179 | Note that slices can be called with two notations: | |
180 |
|
180 | |||
181 | N:M -> standard python form, means including items N...(M-1). |
|
181 | N:M -> standard python form, means including items N...(M-1). | |
182 |
|
182 | |||
183 | N-M -> include items N..M (closed endpoint).""" |
|
183 | N-M -> include items N..M (closed endpoint).""" | |
184 |
|
184 | |||
185 | if raw: |
|
185 | if raw: | |
186 | hist = self.shell.input_hist_raw |
|
186 | hist = self.shell.input_hist_raw | |
187 | else: |
|
187 | else: | |
188 | hist = self.shell.input_hist |
|
188 | hist = self.shell.input_hist | |
189 |
|
189 | |||
190 | cmds = [] |
|
190 | cmds = [] | |
191 | for chunk in slices: |
|
191 | for chunk in slices: | |
192 | if ':' in chunk: |
|
192 | if ':' in chunk: | |
193 | ini,fin = map(int,chunk.split(':')) |
|
193 | ini,fin = map(int,chunk.split(':')) | |
194 | elif '-' in chunk: |
|
194 | elif '-' in chunk: | |
195 | ini,fin = map(int,chunk.split('-')) |
|
195 | ini,fin = map(int,chunk.split('-')) | |
196 | fin += 1 |
|
196 | fin += 1 | |
197 | else: |
|
197 | else: | |
198 | ini = int(chunk) |
|
198 | ini = int(chunk) | |
199 | fin = ini+1 |
|
199 | fin = ini+1 | |
200 | cmds.append(hist[ini:fin]) |
|
200 | cmds.append(hist[ini:fin]) | |
201 | return cmds |
|
201 | return cmds | |
202 |
|
202 | |||
203 | def _ofind(self, oname, namespaces=None): |
|
203 | def _ofind(self, oname, namespaces=None): | |
204 | """Find an object in the available namespaces. |
|
204 | """Find an object in the available namespaces. | |
205 |
|
205 | |||
206 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
206 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
207 |
|
207 | |||
208 | Has special code to detect magic functions. |
|
208 | Has special code to detect magic functions. | |
209 | """ |
|
209 | """ | |
210 |
|
210 | |||
211 | oname = oname.strip() |
|
211 | oname = oname.strip() | |
212 |
|
212 | |||
213 | alias_ns = None |
|
213 | alias_ns = None | |
214 | if namespaces is None: |
|
214 | if namespaces is None: | |
215 | # Namespaces to search in: |
|
215 | # Namespaces to search in: | |
216 | # Put them in a list. The order is important so that we |
|
216 | # Put them in a list. The order is important so that we | |
217 | # find things in the same order that Python finds them. |
|
217 | # find things in the same order that Python finds them. | |
218 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
218 | namespaces = [ ('Interactive', self.shell.user_ns), | |
219 | ('IPython internal', self.shell.internal_ns), |
|
219 | ('IPython internal', self.shell.internal_ns), | |
220 | ('Python builtin', __builtin__.__dict__), |
|
220 | ('Python builtin', __builtin__.__dict__), | |
221 | ('Alias', self.shell.alias_manager.alias_table), |
|
221 | ('Alias', self.shell.alias_manager.alias_table), | |
222 | ] |
|
222 | ] | |
223 | alias_ns = self.shell.alias_manager.alias_table |
|
223 | alias_ns = self.shell.alias_manager.alias_table | |
224 |
|
224 | |||
225 | # initialize results to 'null' |
|
225 | # initialize results to 'null' | |
226 | found = 0; obj = None; ospace = None; ds = None; |
|
226 | found = 0; obj = None; ospace = None; ds = None; | |
227 | ismagic = 0; isalias = 0; parent = None |
|
227 | ismagic = 0; isalias = 0; parent = None | |
228 |
|
228 | |||
229 | # Look for the given name by splitting it in parts. If the head is |
|
229 | # Look for the given name by splitting it in parts. If the head is | |
230 | # found, then we look for all the remaining parts as members, and only |
|
230 | # found, then we look for all the remaining parts as members, and only | |
231 | # declare success if we can find them all. |
|
231 | # declare success if we can find them all. | |
232 | oname_parts = oname.split('.') |
|
232 | oname_parts = oname.split('.') | |
233 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
233 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
234 | for nsname,ns in namespaces: |
|
234 | for nsname,ns in namespaces: | |
235 | try: |
|
235 | try: | |
236 | obj = ns[oname_head] |
|
236 | obj = ns[oname_head] | |
237 | except KeyError: |
|
237 | except KeyError: | |
238 | continue |
|
238 | continue | |
239 | else: |
|
239 | else: | |
240 | #print 'oname_rest:', oname_rest # dbg |
|
240 | #print 'oname_rest:', oname_rest # dbg | |
241 | for part in oname_rest: |
|
241 | for part in oname_rest: | |
242 | try: |
|
242 | try: | |
243 | parent = obj |
|
243 | parent = obj | |
244 | obj = getattr(obj,part) |
|
244 | obj = getattr(obj,part) | |
245 | except: |
|
245 | except: | |
246 | # Blanket except b/c some badly implemented objects |
|
246 | # Blanket except b/c some badly implemented objects | |
247 | # allow __getattr__ to raise exceptions other than |
|
247 | # allow __getattr__ to raise exceptions other than | |
248 | # AttributeError, which then crashes IPython. |
|
248 | # AttributeError, which then crashes IPython. | |
249 | break |
|
249 | break | |
250 | else: |
|
250 | else: | |
251 | # If we finish the for loop (no break), we got all members |
|
251 | # If we finish the for loop (no break), we got all members | |
252 | found = 1 |
|
252 | found = 1 | |
253 | ospace = nsname |
|
253 | ospace = nsname | |
254 | if ns == alias_ns: |
|
254 | if ns == alias_ns: | |
255 | isalias = 1 |
|
255 | isalias = 1 | |
256 | break # namespace loop |
|
256 | break # namespace loop | |
257 |
|
257 | |||
258 | # Try to see if it's magic |
|
258 | # Try to see if it's magic | |
259 | if not found: |
|
259 | if not found: | |
260 | if oname.startswith(ESC_MAGIC): |
|
260 | if oname.startswith(ESC_MAGIC): | |
261 | oname = oname[1:] |
|
261 | oname = oname[1:] | |
262 | obj = getattr(self,'magic_'+oname,None) |
|
262 | obj = getattr(self,'magic_'+oname,None) | |
263 | if obj is not None: |
|
263 | if obj is not None: | |
264 | found = 1 |
|
264 | found = 1 | |
265 | ospace = 'IPython internal' |
|
265 | ospace = 'IPython internal' | |
266 | ismagic = 1 |
|
266 | ismagic = 1 | |
267 |
|
267 | |||
268 | # Last try: special-case some literals like '', [], {}, etc: |
|
268 | # Last try: special-case some literals like '', [], {}, etc: | |
269 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
269 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
270 | obj = eval(oname_head) |
|
270 | obj = eval(oname_head) | |
271 | found = 1 |
|
271 | found = 1 | |
272 | ospace = 'Interactive' |
|
272 | ospace = 'Interactive' | |
273 |
|
273 | |||
274 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
274 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
275 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
275 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
276 |
|
276 | |||
277 | def arg_err(self,func): |
|
277 | def arg_err(self,func): | |
278 | """Print docstring if incorrect arguments were passed""" |
|
278 | """Print docstring if incorrect arguments were passed""" | |
279 | print 'Error in arguments:' |
|
279 | print 'Error in arguments:' | |
280 | print OInspect.getdoc(func) |
|
280 | print OInspect.getdoc(func) | |
281 |
|
281 | |||
282 | def format_latex(self,strng): |
|
282 | def format_latex(self,strng): | |
283 | """Format a string for latex inclusion.""" |
|
283 | """Format a string for latex inclusion.""" | |
284 |
|
284 | |||
285 | # Characters that need to be escaped for latex: |
|
285 | # Characters that need to be escaped for latex: | |
286 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
286 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
287 | # Magic command names as headers: |
|
287 | # Magic command names as headers: | |
288 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
288 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
289 | re.MULTILINE) |
|
289 | re.MULTILINE) | |
290 | # Magic commands |
|
290 | # Magic commands | |
291 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
291 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
292 | re.MULTILINE) |
|
292 | re.MULTILINE) | |
293 | # Paragraph continue |
|
293 | # Paragraph continue | |
294 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
294 | par_re = re.compile(r'\\$',re.MULTILINE) | |
295 |
|
295 | |||
296 | # The "\n" symbol |
|
296 | # The "\n" symbol | |
297 | newline_re = re.compile(r'\\n') |
|
297 | newline_re = re.compile(r'\\n') | |
298 |
|
298 | |||
299 | # Now build the string for output: |
|
299 | # Now build the string for output: | |
300 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
300 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
301 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
301 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
302 | strng) |
|
302 | strng) | |
303 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
303 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
304 | strng = par_re.sub(r'\\\\',strng) |
|
304 | strng = par_re.sub(r'\\\\',strng) | |
305 | strng = escape_re.sub(r'\\\1',strng) |
|
305 | strng = escape_re.sub(r'\\\1',strng) | |
306 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
306 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
307 | return strng |
|
307 | return strng | |
308 |
|
308 | |||
309 | def format_screen(self,strng): |
|
309 | def format_screen(self,strng): | |
310 | """Format a string for screen printing. |
|
310 | """Format a string for screen printing. | |
311 |
|
311 | |||
312 | This removes some latex-type format codes.""" |
|
312 | This removes some latex-type format codes.""" | |
313 | # Paragraph continue |
|
313 | # Paragraph continue | |
314 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
314 | par_re = re.compile(r'\\$',re.MULTILINE) | |
315 | strng = par_re.sub('',strng) |
|
315 | strng = par_re.sub('',strng) | |
316 | return strng |
|
316 | return strng | |
317 |
|
317 | |||
318 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
318 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
319 | """Parse options passed to an argument string. |
|
319 | """Parse options passed to an argument string. | |
320 |
|
320 | |||
321 | The interface is similar to that of getopt(), but it returns back a |
|
321 | The interface is similar to that of getopt(), but it returns back a | |
322 | Struct with the options as keys and the stripped argument string still |
|
322 | Struct with the options as keys and the stripped argument string still | |
323 | as a string. |
|
323 | as a string. | |
324 |
|
324 | |||
325 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
325 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
326 | This allows us to easily expand variables, glob files, quote |
|
326 | This allows us to easily expand variables, glob files, quote | |
327 | arguments, etc. |
|
327 | arguments, etc. | |
328 |
|
328 | |||
329 | Options: |
|
329 | Options: | |
330 | -mode: default 'string'. If given as 'list', the argument string is |
|
330 | -mode: default 'string'. If given as 'list', the argument string is | |
331 | returned as a list (split on whitespace) instead of a string. |
|
331 | returned as a list (split on whitespace) instead of a string. | |
332 |
|
332 | |||
333 | -list_all: put all option values in lists. Normally only options |
|
333 | -list_all: put all option values in lists. Normally only options | |
334 | appearing more than once are put in a list. |
|
334 | appearing more than once are put in a list. | |
335 |
|
335 | |||
336 | -posix (True): whether to split the input line in POSIX mode or not, |
|
336 | -posix (True): whether to split the input line in POSIX mode or not, | |
337 | as per the conventions outlined in the shlex module from the |
|
337 | as per the conventions outlined in the shlex module from the | |
338 | standard library.""" |
|
338 | standard library.""" | |
339 |
|
339 | |||
340 | # inject default options at the beginning of the input line |
|
340 | # inject default options at the beginning of the input line | |
341 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
341 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
342 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
342 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
343 |
|
343 | |||
344 | mode = kw.get('mode','string') |
|
344 | mode = kw.get('mode','string') | |
345 | if mode not in ['string','list']: |
|
345 | if mode not in ['string','list']: | |
346 | raise ValueError,'incorrect mode given: %s' % mode |
|
346 | raise ValueError,'incorrect mode given: %s' % mode | |
347 | # Get options |
|
347 | # Get options | |
348 | list_all = kw.get('list_all',0) |
|
348 | list_all = kw.get('list_all',0) | |
349 | posix = kw.get('posix',True) |
|
349 | posix = kw.get('posix',True) | |
350 |
|
350 | |||
351 | # Check if we have more than one argument to warrant extra processing: |
|
351 | # Check if we have more than one argument to warrant extra processing: | |
352 | odict = {} # Dictionary with options |
|
352 | odict = {} # Dictionary with options | |
353 | args = arg_str.split() |
|
353 | args = arg_str.split() | |
354 | if len(args) >= 1: |
|
354 | if len(args) >= 1: | |
355 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
355 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
356 | # need to look for options |
|
356 | # need to look for options | |
357 | argv = arg_split(arg_str,posix) |
|
357 | argv = arg_split(arg_str,posix) | |
358 | # Do regular option processing |
|
358 | # Do regular option processing | |
359 | try: |
|
359 | try: | |
360 | opts,args = getopt(argv,opt_str,*long_opts) |
|
360 | opts,args = getopt(argv,opt_str,*long_opts) | |
361 | except GetoptError,e: |
|
361 | except GetoptError,e: | |
362 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
362 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
363 | " ".join(long_opts))) |
|
363 | " ".join(long_opts))) | |
364 | for o,a in opts: |
|
364 | for o,a in opts: | |
365 | if o.startswith('--'): |
|
365 | if o.startswith('--'): | |
366 | o = o[2:] |
|
366 | o = o[2:] | |
367 | else: |
|
367 | else: | |
368 | o = o[1:] |
|
368 | o = o[1:] | |
369 | try: |
|
369 | try: | |
370 | odict[o].append(a) |
|
370 | odict[o].append(a) | |
371 | except AttributeError: |
|
371 | except AttributeError: | |
372 | odict[o] = [odict[o],a] |
|
372 | odict[o] = [odict[o],a] | |
373 | except KeyError: |
|
373 | except KeyError: | |
374 | if list_all: |
|
374 | if list_all: | |
375 | odict[o] = [a] |
|
375 | odict[o] = [a] | |
376 | else: |
|
376 | else: | |
377 | odict[o] = a |
|
377 | odict[o] = a | |
378 |
|
378 | |||
379 | # Prepare opts,args for return |
|
379 | # Prepare opts,args for return | |
380 | opts = Struct(odict) |
|
380 | opts = Struct(odict) | |
381 | if mode == 'string': |
|
381 | if mode == 'string': | |
382 | args = ' '.join(args) |
|
382 | args = ' '.join(args) | |
383 |
|
383 | |||
384 | return opts,args |
|
384 | return opts,args | |
385 |
|
385 | |||
386 | #...................................................................... |
|
386 | #...................................................................... | |
387 | # And now the actual magic functions |
|
387 | # And now the actual magic functions | |
388 |
|
388 | |||
389 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
389 | # Functions for IPython shell work (vars,funcs, config, etc) | |
390 | def magic_lsmagic(self, parameter_s = ''): |
|
390 | def magic_lsmagic(self, parameter_s = ''): | |
391 | """List currently available magic functions.""" |
|
391 | """List currently available magic functions.""" | |
392 | mesc = ESC_MAGIC |
|
392 | mesc = ESC_MAGIC | |
393 | print 'Available magic functions:\n'+mesc+\ |
|
393 | print 'Available magic functions:\n'+mesc+\ | |
394 | (' '+mesc).join(self.lsmagic()) |
|
394 | (' '+mesc).join(self.lsmagic()) | |
395 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
395 | print '\n' + Magic.auto_status[self.shell.automagic] | |
396 | return None |
|
396 | return None | |
397 |
|
397 | |||
398 | def magic_magic(self, parameter_s = ''): |
|
398 | def magic_magic(self, parameter_s = ''): | |
399 | """Print information about the magic function system. |
|
399 | """Print information about the magic function system. | |
400 |
|
400 | |||
401 | Supported formats: -latex, -brief, -rest |
|
401 | Supported formats: -latex, -brief, -rest | |
402 | """ |
|
402 | """ | |
403 |
|
403 | |||
404 | mode = '' |
|
404 | mode = '' | |
405 | try: |
|
405 | try: | |
406 | if parameter_s.split()[0] == '-latex': |
|
406 | if parameter_s.split()[0] == '-latex': | |
407 | mode = 'latex' |
|
407 | mode = 'latex' | |
408 | if parameter_s.split()[0] == '-brief': |
|
408 | if parameter_s.split()[0] == '-brief': | |
409 | mode = 'brief' |
|
409 | mode = 'brief' | |
410 | if parameter_s.split()[0] == '-rest': |
|
410 | if parameter_s.split()[0] == '-rest': | |
411 | mode = 'rest' |
|
411 | mode = 'rest' | |
412 | rest_docs = [] |
|
412 | rest_docs = [] | |
413 | except: |
|
413 | except: | |
414 | pass |
|
414 | pass | |
415 |
|
415 | |||
416 | magic_docs = [] |
|
416 | magic_docs = [] | |
417 | for fname in self.lsmagic(): |
|
417 | for fname in self.lsmagic(): | |
418 | mname = 'magic_' + fname |
|
418 | mname = 'magic_' + fname | |
419 | for space in (Magic,self,self.__class__): |
|
419 | for space in (Magic,self,self.__class__): | |
420 | try: |
|
420 | try: | |
421 | fn = space.__dict__[mname] |
|
421 | fn = space.__dict__[mname] | |
422 | except KeyError: |
|
422 | except KeyError: | |
423 | pass |
|
423 | pass | |
424 | else: |
|
424 | else: | |
425 | break |
|
425 | break | |
426 | if mode == 'brief': |
|
426 | if mode == 'brief': | |
427 | # only first line |
|
427 | # only first line | |
428 | if fn.__doc__: |
|
428 | if fn.__doc__: | |
429 | fndoc = fn.__doc__.split('\n',1)[0] |
|
429 | fndoc = fn.__doc__.split('\n',1)[0] | |
430 | else: |
|
430 | else: | |
431 | fndoc = 'No documentation' |
|
431 | fndoc = 'No documentation' | |
432 | else: |
|
432 | else: | |
433 | if fn.__doc__: |
|
433 | if fn.__doc__: | |
434 | fndoc = fn.__doc__.rstrip() |
|
434 | fndoc = fn.__doc__.rstrip() | |
435 | else: |
|
435 | else: | |
436 | fndoc = 'No documentation' |
|
436 | fndoc = 'No documentation' | |
437 |
|
437 | |||
438 |
|
438 | |||
439 | if mode == 'rest': |
|
439 | if mode == 'rest': | |
440 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
440 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
441 | fname,fndoc)) |
|
441 | fname,fndoc)) | |
442 |
|
442 | |||
443 | else: |
|
443 | else: | |
444 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
444 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
445 | fname,fndoc)) |
|
445 | fname,fndoc)) | |
446 |
|
446 | |||
447 | magic_docs = ''.join(magic_docs) |
|
447 | magic_docs = ''.join(magic_docs) | |
448 |
|
448 | |||
449 | if mode == 'rest': |
|
449 | if mode == 'rest': | |
450 | return "".join(rest_docs) |
|
450 | return "".join(rest_docs) | |
451 |
|
451 | |||
452 | if mode == 'latex': |
|
452 | if mode == 'latex': | |
453 | print self.format_latex(magic_docs) |
|
453 | print self.format_latex(magic_docs) | |
454 | return |
|
454 | return | |
455 | else: |
|
455 | else: | |
456 | magic_docs = self.format_screen(magic_docs) |
|
456 | magic_docs = self.format_screen(magic_docs) | |
457 | if mode == 'brief': |
|
457 | if mode == 'brief': | |
458 | return magic_docs |
|
458 | return magic_docs | |
459 |
|
459 | |||
460 | outmsg = """ |
|
460 | outmsg = """ | |
461 | IPython's 'magic' functions |
|
461 | IPython's 'magic' functions | |
462 | =========================== |
|
462 | =========================== | |
463 |
|
463 | |||
464 | The magic function system provides a series of functions which allow you to |
|
464 | The magic function system provides a series of functions which allow you to | |
465 | control the behavior of IPython itself, plus a lot of system-type |
|
465 | control the behavior of IPython itself, plus a lot of system-type | |
466 | features. All these functions are prefixed with a % character, but parameters |
|
466 | features. All these functions are prefixed with a % character, but parameters | |
467 | are given without parentheses or quotes. |
|
467 | are given without parentheses or quotes. | |
468 |
|
468 | |||
469 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
469 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
470 | %automagic function), you don't need to type in the % explicitly. By default, |
|
470 | %automagic function), you don't need to type in the % explicitly. By default, | |
471 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
471 | IPython ships with automagic on, so you should only rarely need the % escape. | |
472 |
|
472 | |||
473 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
473 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
474 | to 'mydir', if it exists. |
|
474 | to 'mydir', if it exists. | |
475 |
|
475 | |||
476 | You can define your own magic functions to extend the system. See the supplied |
|
476 | You can define your own magic functions to extend the system. See the supplied | |
477 | ipythonrc and example-magic.py files for details (in your ipython |
|
477 | ipythonrc and example-magic.py files for details (in your ipython | |
478 | configuration directory, typically $HOME/.ipython/). |
|
478 | configuration directory, typically $HOME/.ipython/). | |
479 |
|
479 | |||
480 | You can also define your own aliased names for magic functions. In your |
|
480 | You can also define your own aliased names for magic functions. In your | |
481 | ipythonrc file, placing a line like: |
|
481 | ipythonrc file, placing a line like: | |
482 |
|
482 | |||
483 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
483 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
484 |
|
484 | |||
485 | will define %pf as a new name for %profile. |
|
485 | will define %pf as a new name for %profile. | |
486 |
|
486 | |||
487 | You can also call magics in code using the magic() function, which IPython |
|
487 | You can also call magics in code using the magic() function, which IPython | |
488 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
488 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
489 |
|
489 | |||
490 | For a list of the available magic functions, use %lsmagic. For a description |
|
490 | For a list of the available magic functions, use %lsmagic. For a description | |
491 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
491 | of any of them, type %magic_name?, e.g. '%cd?'. | |
492 |
|
492 | |||
493 | Currently the magic system has the following functions:\n""" |
|
493 | Currently the magic system has the following functions:\n""" | |
494 |
|
494 | |||
495 | mesc = ESC_MAGIC |
|
495 | mesc = ESC_MAGIC | |
496 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
496 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
497 | "\n\n%s%s\n\n%s" % (outmsg, |
|
497 | "\n\n%s%s\n\n%s" % (outmsg, | |
498 | magic_docs,mesc,mesc, |
|
498 | magic_docs,mesc,mesc, | |
499 | (' '+mesc).join(self.lsmagic()), |
|
499 | (' '+mesc).join(self.lsmagic()), | |
500 | Magic.auto_status[self.shell.automagic] ) ) |
|
500 | Magic.auto_status[self.shell.automagic] ) ) | |
501 |
|
501 | |||
502 | page(outmsg,screen_lines=self.shell.usable_screen_length) |
|
502 | page(outmsg,screen_lines=self.shell.usable_screen_length) | |
503 |
|
503 | |||
504 |
|
504 | |||
505 | def magic_autoindent(self, parameter_s = ''): |
|
505 | def magic_autoindent(self, parameter_s = ''): | |
506 | """Toggle autoindent on/off (if available).""" |
|
506 | """Toggle autoindent on/off (if available).""" | |
507 |
|
507 | |||
508 | self.shell.set_autoindent() |
|
508 | self.shell.set_autoindent() | |
509 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
509 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
510 |
|
510 | |||
511 |
|
511 | |||
512 | def magic_automagic(self, parameter_s = ''): |
|
512 | def magic_automagic(self, parameter_s = ''): | |
513 | """Make magic functions callable without having to type the initial %. |
|
513 | """Make magic functions callable without having to type the initial %. | |
514 |
|
514 | |||
515 | Without argumentsl toggles on/off (when off, you must call it as |
|
515 | Without argumentsl toggles on/off (when off, you must call it as | |
516 | %automagic, of course). With arguments it sets the value, and you can |
|
516 | %automagic, of course). With arguments it sets the value, and you can | |
517 | use any of (case insensitive): |
|
517 | use any of (case insensitive): | |
518 |
|
518 | |||
519 | - on,1,True: to activate |
|
519 | - on,1,True: to activate | |
520 |
|
520 | |||
521 | - off,0,False: to deactivate. |
|
521 | - off,0,False: to deactivate. | |
522 |
|
522 | |||
523 | Note that magic functions have lowest priority, so if there's a |
|
523 | Note that magic functions have lowest priority, so if there's a | |
524 | variable whose name collides with that of a magic fn, automagic won't |
|
524 | variable whose name collides with that of a magic fn, automagic won't | |
525 | work for that function (you get the variable instead). However, if you |
|
525 | work for that function (you get the variable instead). However, if you | |
526 | delete the variable (del var), the previously shadowed magic function |
|
526 | delete the variable (del var), the previously shadowed magic function | |
527 | becomes visible to automagic again.""" |
|
527 | becomes visible to automagic again.""" | |
528 |
|
528 | |||
529 | arg = parameter_s.lower() |
|
529 | arg = parameter_s.lower() | |
530 | if parameter_s in ('on','1','true'): |
|
530 | if parameter_s in ('on','1','true'): | |
531 | self.shell.automagic = True |
|
531 | self.shell.automagic = True | |
532 | elif parameter_s in ('off','0','false'): |
|
532 | elif parameter_s in ('off','0','false'): | |
533 | self.shell.automagic = False |
|
533 | self.shell.automagic = False | |
534 | else: |
|
534 | else: | |
535 | self.shell.automagic = not self.shell.automagic |
|
535 | self.shell.automagic = not self.shell.automagic | |
536 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
536 | print '\n' + Magic.auto_status[self.shell.automagic] | |
537 |
|
537 | |||
538 | @testdec.skip_doctest |
|
538 | @testdec.skip_doctest | |
539 | def magic_autocall(self, parameter_s = ''): |
|
539 | def magic_autocall(self, parameter_s = ''): | |
540 | """Make functions callable without having to type parentheses. |
|
540 | """Make functions callable without having to type parentheses. | |
541 |
|
541 | |||
542 | Usage: |
|
542 | Usage: | |
543 |
|
543 | |||
544 | %autocall [mode] |
|
544 | %autocall [mode] | |
545 |
|
545 | |||
546 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
546 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
547 | value is toggled on and off (remembering the previous state). |
|
547 | value is toggled on and off (remembering the previous state). | |
548 |
|
548 | |||
549 | In more detail, these values mean: |
|
549 | In more detail, these values mean: | |
550 |
|
550 | |||
551 | 0 -> fully disabled |
|
551 | 0 -> fully disabled | |
552 |
|
552 | |||
553 | 1 -> active, but do not apply if there are no arguments on the line. |
|
553 | 1 -> active, but do not apply if there are no arguments on the line. | |
554 |
|
554 | |||
555 | In this mode, you get: |
|
555 | In this mode, you get: | |
556 |
|
556 | |||
557 | In [1]: callable |
|
557 | In [1]: callable | |
558 | Out[1]: <built-in function callable> |
|
558 | Out[1]: <built-in function callable> | |
559 |
|
559 | |||
560 | In [2]: callable 'hello' |
|
560 | In [2]: callable 'hello' | |
561 | ------> callable('hello') |
|
561 | ------> callable('hello') | |
562 | Out[2]: False |
|
562 | Out[2]: False | |
563 |
|
563 | |||
564 | 2 -> Active always. Even if no arguments are present, the callable |
|
564 | 2 -> Active always. Even if no arguments are present, the callable | |
565 | object is called: |
|
565 | object is called: | |
566 |
|
566 | |||
567 | In [2]: float |
|
567 | In [2]: float | |
568 | ------> float() |
|
568 | ------> float() | |
569 | Out[2]: 0.0 |
|
569 | Out[2]: 0.0 | |
570 |
|
570 | |||
571 | Note that even with autocall off, you can still use '/' at the start of |
|
571 | Note that even with autocall off, you can still use '/' at the start of | |
572 | a line to treat the first argument on the command line as a function |
|
572 | a line to treat the first argument on the command line as a function | |
573 | and add parentheses to it: |
|
573 | and add parentheses to it: | |
574 |
|
574 | |||
575 | In [8]: /str 43 |
|
575 | In [8]: /str 43 | |
576 | ------> str(43) |
|
576 | ------> str(43) | |
577 | Out[8]: '43' |
|
577 | Out[8]: '43' | |
578 |
|
578 | |||
579 | # all-random (note for auto-testing) |
|
579 | # all-random (note for auto-testing) | |
580 | """ |
|
580 | """ | |
581 |
|
581 | |||
582 | if parameter_s: |
|
582 | if parameter_s: | |
583 | arg = int(parameter_s) |
|
583 | arg = int(parameter_s) | |
584 | else: |
|
584 | else: | |
585 | arg = 'toggle' |
|
585 | arg = 'toggle' | |
586 |
|
586 | |||
587 | if not arg in (0,1,2,'toggle'): |
|
587 | if not arg in (0,1,2,'toggle'): | |
588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
589 | return |
|
589 | return | |
590 |
|
590 | |||
591 | if arg in (0,1,2): |
|
591 | if arg in (0,1,2): | |
592 | self.shell.autocall = arg |
|
592 | self.shell.autocall = arg | |
593 | else: # toggle |
|
593 | else: # toggle | |
594 | if self.shell.autocall: |
|
594 | if self.shell.autocall: | |
595 | self._magic_state.autocall_save = self.shell.autocall |
|
595 | self._magic_state.autocall_save = self.shell.autocall | |
596 | self.shell.autocall = 0 |
|
596 | self.shell.autocall = 0 | |
597 | else: |
|
597 | else: | |
598 | try: |
|
598 | try: | |
599 | self.shell.autocall = self._magic_state.autocall_save |
|
599 | self.shell.autocall = self._magic_state.autocall_save | |
600 | except AttributeError: |
|
600 | except AttributeError: | |
601 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
601 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
602 |
|
602 | |||
603 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
603 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
604 |
|
604 | |||
605 | def magic_system_verbose(self, parameter_s = ''): |
|
605 | def magic_system_verbose(self, parameter_s = ''): | |
606 | """Set verbose printing of system calls. |
|
606 | """Set verbose printing of system calls. | |
607 |
|
607 | |||
608 | If called without an argument, act as a toggle""" |
|
608 | If called without an argument, act as a toggle""" | |
609 |
|
609 | |||
610 | if parameter_s: |
|
610 | if parameter_s: | |
611 | val = bool(eval(parameter_s)) |
|
611 | val = bool(eval(parameter_s)) | |
612 | else: |
|
612 | else: | |
613 | val = None |
|
613 | val = None | |
614 |
|
614 | |||
615 | if self.shell.system_verbose: |
|
615 | if self.shell.system_verbose: | |
616 | self.shell.system_verbose = False |
|
616 | self.shell.system_verbose = False | |
617 | else: |
|
617 | else: | |
618 | self.shell.system_verbose = True |
|
618 | self.shell.system_verbose = True | |
619 | print "System verbose printing is:",\ |
|
619 | print "System verbose printing is:",\ | |
620 | ['OFF','ON'][self.shell.system_verbose] |
|
620 | ['OFF','ON'][self.shell.system_verbose] | |
621 |
|
621 | |||
622 |
|
622 | |||
623 | def magic_page(self, parameter_s=''): |
|
623 | def magic_page(self, parameter_s=''): | |
624 | """Pretty print the object and display it through a pager. |
|
624 | """Pretty print the object and display it through a pager. | |
625 |
|
625 | |||
626 | %page [options] OBJECT |
|
626 | %page [options] OBJECT | |
627 |
|
627 | |||
628 | If no object is given, use _ (last output). |
|
628 | If no object is given, use _ (last output). | |
629 |
|
629 | |||
630 | Options: |
|
630 | Options: | |
631 |
|
631 | |||
632 | -r: page str(object), don't pretty-print it.""" |
|
632 | -r: page str(object), don't pretty-print it.""" | |
633 |
|
633 | |||
634 | # After a function contributed by Olivier Aubert, slightly modified. |
|
634 | # After a function contributed by Olivier Aubert, slightly modified. | |
635 |
|
635 | |||
636 | # Process options/args |
|
636 | # Process options/args | |
637 | opts,args = self.parse_options(parameter_s,'r') |
|
637 | opts,args = self.parse_options(parameter_s,'r') | |
638 | raw = 'r' in opts |
|
638 | raw = 'r' in opts | |
639 |
|
639 | |||
640 | oname = args and args or '_' |
|
640 | oname = args and args or '_' | |
641 | info = self._ofind(oname) |
|
641 | info = self._ofind(oname) | |
642 | if info['found']: |
|
642 | if info['found']: | |
643 | txt = (raw and str or pformat)( info['obj'] ) |
|
643 | txt = (raw and str or pformat)( info['obj'] ) | |
644 | page(txt) |
|
644 | page(txt) | |
645 | else: |
|
645 | else: | |
646 | print 'Object `%s` not found' % oname |
|
646 | print 'Object `%s` not found' % oname | |
647 |
|
647 | |||
648 | def magic_profile(self, parameter_s=''): |
|
648 | def magic_profile(self, parameter_s=''): | |
649 | """Print your currently active IPyhton profile.""" |
|
649 | """Print your currently active IPyhton profile.""" | |
650 | if self.shell.profile: |
|
650 | if self.shell.profile: | |
651 | printpl('Current IPython profile: $self.shell.profile.') |
|
651 | printpl('Current IPython profile: $self.shell.profile.') | |
652 | else: |
|
652 | else: | |
653 | print 'No profile active.' |
|
653 | print 'No profile active.' | |
654 |
|
654 | |||
655 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
655 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
656 | """Provide detailed information about an object. |
|
656 | """Provide detailed information about an object. | |
657 |
|
657 | |||
658 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
658 | '%pinfo object' is just a synonym for object? or ?object.""" | |
659 |
|
659 | |||
660 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
660 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
661 |
|
661 | |||
662 |
|
662 | |||
663 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
663 | # detail_level: 0 -> obj? , 1 -> obj?? | |
664 | detail_level = 0 |
|
664 | detail_level = 0 | |
665 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
665 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
666 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
666 | # happen if the user types 'pinfo foo?' at the cmd line. | |
667 | pinfo,qmark1,oname,qmark2 = \ |
|
667 | pinfo,qmark1,oname,qmark2 = \ | |
668 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
668 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
669 | if pinfo or qmark1 or qmark2: |
|
669 | if pinfo or qmark1 or qmark2: | |
670 | detail_level = 1 |
|
670 | detail_level = 1 | |
671 | if "*" in oname: |
|
671 | if "*" in oname: | |
672 | self.magic_psearch(oname) |
|
672 | self.magic_psearch(oname) | |
673 | else: |
|
673 | else: | |
674 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
674 | self._inspect('pinfo', oname, detail_level=detail_level, | |
675 | namespaces=namespaces) |
|
675 | namespaces=namespaces) | |
676 |
|
676 | |||
677 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
677 | def magic_pdef(self, parameter_s='', namespaces=None): | |
678 | """Print the definition header for any callable object. |
|
678 | """Print the definition header for any callable object. | |
679 |
|
679 | |||
680 | If the object is a class, print the constructor information.""" |
|
680 | If the object is a class, print the constructor information.""" | |
681 | self._inspect('pdef',parameter_s, namespaces) |
|
681 | self._inspect('pdef',parameter_s, namespaces) | |
682 |
|
682 | |||
683 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
683 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
684 | """Print the docstring for an object. |
|
684 | """Print the docstring for an object. | |
685 |
|
685 | |||
686 | If the given object is a class, it will print both the class and the |
|
686 | If the given object is a class, it will print both the class and the | |
687 | constructor docstrings.""" |
|
687 | constructor docstrings.""" | |
688 | self._inspect('pdoc',parameter_s, namespaces) |
|
688 | self._inspect('pdoc',parameter_s, namespaces) | |
689 |
|
689 | |||
690 | def magic_psource(self, parameter_s='', namespaces=None): |
|
690 | def magic_psource(self, parameter_s='', namespaces=None): | |
691 | """Print (or run through pager) the source code for an object.""" |
|
691 | """Print (or run through pager) the source code for an object.""" | |
692 | self._inspect('psource',parameter_s, namespaces) |
|
692 | self._inspect('psource',parameter_s, namespaces) | |
693 |
|
693 | |||
694 | def magic_pfile(self, parameter_s=''): |
|
694 | def magic_pfile(self, parameter_s=''): | |
695 | """Print (or run through pager) the file where an object is defined. |
|
695 | """Print (or run through pager) the file where an object is defined. | |
696 |
|
696 | |||
697 | The file opens at the line where the object definition begins. IPython |
|
697 | The file opens at the line where the object definition begins. IPython | |
698 | will honor the environment variable PAGER if set, and otherwise will |
|
698 | will honor the environment variable PAGER if set, and otherwise will | |
699 | do its best to print the file in a convenient form. |
|
699 | do its best to print the file in a convenient form. | |
700 |
|
700 | |||
701 | If the given argument is not an object currently defined, IPython will |
|
701 | If the given argument is not an object currently defined, IPython will | |
702 | try to interpret it as a filename (automatically adding a .py extension |
|
702 | try to interpret it as a filename (automatically adding a .py extension | |
703 | if needed). You can thus use %pfile as a syntax highlighting code |
|
703 | if needed). You can thus use %pfile as a syntax highlighting code | |
704 | viewer.""" |
|
704 | viewer.""" | |
705 |
|
705 | |||
706 | # first interpret argument as an object name |
|
706 | # first interpret argument as an object name | |
707 | out = self._inspect('pfile',parameter_s) |
|
707 | out = self._inspect('pfile',parameter_s) | |
708 | # if not, try the input as a filename |
|
708 | # if not, try the input as a filename | |
709 | if out == 'not found': |
|
709 | if out == 'not found': | |
710 | try: |
|
710 | try: | |
711 | filename = get_py_filename(parameter_s) |
|
711 | filename = get_py_filename(parameter_s) | |
712 | except IOError,msg: |
|
712 | except IOError,msg: | |
713 | print msg |
|
713 | print msg | |
714 | return |
|
714 | return | |
715 | page(self.shell.inspector.format(file(filename).read())) |
|
715 | page(self.shell.inspector.format(file(filename).read())) | |
716 |
|
716 | |||
717 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
717 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
718 | """Generic interface to the inspector system. |
|
718 | """Generic interface to the inspector system. | |
719 |
|
719 | |||
720 | This function is meant to be called by pdef, pdoc & friends.""" |
|
720 | This function is meant to be called by pdef, pdoc & friends.""" | |
721 |
|
721 | |||
722 | #oname = oname.strip() |
|
722 | #oname = oname.strip() | |
723 | #print '1- oname: <%r>' % oname # dbg |
|
723 | #print '1- oname: <%r>' % oname # dbg | |
724 | try: |
|
724 | try: | |
725 | oname = oname.strip().encode('ascii') |
|
725 | oname = oname.strip().encode('ascii') | |
726 | #print '2- oname: <%r>' % oname # dbg |
|
726 | #print '2- oname: <%r>' % oname # dbg | |
727 | except UnicodeEncodeError: |
|
727 | except UnicodeEncodeError: | |
728 | print 'Python identifiers can only contain ascii characters.' |
|
728 | print 'Python identifiers can only contain ascii characters.' | |
729 | return 'not found' |
|
729 | return 'not found' | |
730 |
|
730 | |||
731 | info = Struct(self._ofind(oname, namespaces)) |
|
731 | info = Struct(self._ofind(oname, namespaces)) | |
732 |
|
732 | |||
733 | if info.found: |
|
733 | if info.found: | |
734 | try: |
|
734 | try: | |
735 | IPython.utils.generics.inspect_object(info.obj) |
|
735 | IPython.utils.generics.inspect_object(info.obj) | |
736 | return |
|
736 | return | |
737 | except TryNext: |
|
737 | except TryNext: | |
738 | pass |
|
738 | pass | |
739 | # Get the docstring of the class property if it exists. |
|
739 | # Get the docstring of the class property if it exists. | |
740 | path = oname.split('.') |
|
740 | path = oname.split('.') | |
741 | root = '.'.join(path[:-1]) |
|
741 | root = '.'.join(path[:-1]) | |
742 | if info.parent is not None: |
|
742 | if info.parent is not None: | |
743 | try: |
|
743 | try: | |
744 | target = getattr(info.parent, '__class__') |
|
744 | target = getattr(info.parent, '__class__') | |
745 | # The object belongs to a class instance. |
|
745 | # The object belongs to a class instance. | |
746 | try: |
|
746 | try: | |
747 | target = getattr(target, path[-1]) |
|
747 | target = getattr(target, path[-1]) | |
748 | # The class defines the object. |
|
748 | # The class defines the object. | |
749 | if isinstance(target, property): |
|
749 | if isinstance(target, property): | |
750 | oname = root + '.__class__.' + path[-1] |
|
750 | oname = root + '.__class__.' + path[-1] | |
751 | info = Struct(self._ofind(oname)) |
|
751 | info = Struct(self._ofind(oname)) | |
752 | except AttributeError: pass |
|
752 | except AttributeError: pass | |
753 | except AttributeError: pass |
|
753 | except AttributeError: pass | |
754 |
|
754 | |||
755 | pmethod = getattr(self.shell.inspector,meth) |
|
755 | pmethod = getattr(self.shell.inspector,meth) | |
756 | formatter = info.ismagic and self.format_screen or None |
|
756 | formatter = info.ismagic and self.format_screen or None | |
757 | if meth == 'pdoc': |
|
757 | if meth == 'pdoc': | |
758 | pmethod(info.obj,oname,formatter) |
|
758 | pmethod(info.obj,oname,formatter) | |
759 | elif meth == 'pinfo': |
|
759 | elif meth == 'pinfo': | |
760 | pmethod(info.obj,oname,formatter,info,**kw) |
|
760 | pmethod(info.obj,oname,formatter,info,**kw) | |
761 | else: |
|
761 | else: | |
762 | pmethod(info.obj,oname) |
|
762 | pmethod(info.obj,oname) | |
763 | else: |
|
763 | else: | |
764 | print 'Object `%s` not found.' % oname |
|
764 | print 'Object `%s` not found.' % oname | |
765 | return 'not found' # so callers can take other action |
|
765 | return 'not found' # so callers can take other action | |
766 |
|
766 | |||
767 | def magic_psearch(self, parameter_s=''): |
|
767 | def magic_psearch(self, parameter_s=''): | |
768 | """Search for object in namespaces by wildcard. |
|
768 | """Search for object in namespaces by wildcard. | |
769 |
|
769 | |||
770 | %psearch [options] PATTERN [OBJECT TYPE] |
|
770 | %psearch [options] PATTERN [OBJECT TYPE] | |
771 |
|
771 | |||
772 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
772 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
773 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
773 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
774 | rest of the command line must be unchanged (options come first), so |
|
774 | rest of the command line must be unchanged (options come first), so | |
775 | for example the following forms are equivalent |
|
775 | for example the following forms are equivalent | |
776 |
|
776 | |||
777 | %psearch -i a* function |
|
777 | %psearch -i a* function | |
778 | -i a* function? |
|
778 | -i a* function? | |
779 | ?-i a* function |
|
779 | ?-i a* function | |
780 |
|
780 | |||
781 | Arguments: |
|
781 | Arguments: | |
782 |
|
782 | |||
783 | PATTERN |
|
783 | PATTERN | |
784 |
|
784 | |||
785 | where PATTERN is a string containing * as a wildcard similar to its |
|
785 | where PATTERN is a string containing * as a wildcard similar to its | |
786 | use in a shell. The pattern is matched in all namespaces on the |
|
786 | use in a shell. The pattern is matched in all namespaces on the | |
787 | search path. By default objects starting with a single _ are not |
|
787 | search path. By default objects starting with a single _ are not | |
788 | matched, many IPython generated objects have a single |
|
788 | matched, many IPython generated objects have a single | |
789 | underscore. The default is case insensitive matching. Matching is |
|
789 | underscore. The default is case insensitive matching. Matching is | |
790 | also done on the attributes of objects and not only on the objects |
|
790 | also done on the attributes of objects and not only on the objects | |
791 | in a module. |
|
791 | in a module. | |
792 |
|
792 | |||
793 | [OBJECT TYPE] |
|
793 | [OBJECT TYPE] | |
794 |
|
794 | |||
795 | Is the name of a python type from the types module. The name is |
|
795 | Is the name of a python type from the types module. The name is | |
796 | given in lowercase without the ending type, ex. StringType is |
|
796 | given in lowercase without the ending type, ex. StringType is | |
797 | written string. By adding a type here only objects matching the |
|
797 | written string. By adding a type here only objects matching the | |
798 | given type are matched. Using all here makes the pattern match all |
|
798 | given type are matched. Using all here makes the pattern match all | |
799 | types (this is the default). |
|
799 | types (this is the default). | |
800 |
|
800 | |||
801 | Options: |
|
801 | Options: | |
802 |
|
802 | |||
803 | -a: makes the pattern match even objects whose names start with a |
|
803 | -a: makes the pattern match even objects whose names start with a | |
804 | single underscore. These names are normally ommitted from the |
|
804 | single underscore. These names are normally ommitted from the | |
805 | search. |
|
805 | search. | |
806 |
|
806 | |||
807 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
807 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
808 | these options is given, the default is read from your ipythonrc |
|
808 | these options is given, the default is read from your ipythonrc | |
809 | file. The option name which sets this value is |
|
809 | file. The option name which sets this value is | |
810 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
810 | 'wildcards_case_sensitive'. If this option is not specified in your | |
811 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
811 | ipythonrc file, IPython's internal default is to do a case sensitive | |
812 | search. |
|
812 | search. | |
813 |
|
813 | |||
814 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
814 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
815 | specifiy can be searched in any of the following namespaces: |
|
815 | specifiy can be searched in any of the following namespaces: | |
816 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
816 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
817 | 'builtin' and 'user' are the search defaults. Note that you should |
|
817 | 'builtin' and 'user' are the search defaults. Note that you should | |
818 | not use quotes when specifying namespaces. |
|
818 | not use quotes when specifying namespaces. | |
819 |
|
819 | |||
820 | 'Builtin' contains the python module builtin, 'user' contains all |
|
820 | 'Builtin' contains the python module builtin, 'user' contains all | |
821 | user data, 'alias' only contain the shell aliases and no python |
|
821 | user data, 'alias' only contain the shell aliases and no python | |
822 | objects, 'internal' contains objects used by IPython. The |
|
822 | objects, 'internal' contains objects used by IPython. The | |
823 | 'user_global' namespace is only used by embedded IPython instances, |
|
823 | 'user_global' namespace is only used by embedded IPython instances, | |
824 | and it contains module-level globals. You can add namespaces to the |
|
824 | and it contains module-level globals. You can add namespaces to the | |
825 | search with -s or exclude them with -e (these options can be given |
|
825 | search with -s or exclude them with -e (these options can be given | |
826 | more than once). |
|
826 | more than once). | |
827 |
|
827 | |||
828 | Examples: |
|
828 | Examples: | |
829 |
|
829 | |||
830 | %psearch a* -> objects beginning with an a |
|
830 | %psearch a* -> objects beginning with an a | |
831 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
831 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
832 | %psearch a* function -> all functions beginning with an a |
|
832 | %psearch a* function -> all functions beginning with an a | |
833 | %psearch re.e* -> objects beginning with an e in module re |
|
833 | %psearch re.e* -> objects beginning with an e in module re | |
834 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
834 | %psearch r*.e* -> objects that start with e in modules starting in r | |
835 | %psearch r*.* string -> all strings in modules beginning with r |
|
835 | %psearch r*.* string -> all strings in modules beginning with r | |
836 |
|
836 | |||
837 | Case sensitve search: |
|
837 | Case sensitve search: | |
838 |
|
838 | |||
839 | %psearch -c a* list all object beginning with lower case a |
|
839 | %psearch -c a* list all object beginning with lower case a | |
840 |
|
840 | |||
841 | Show objects beginning with a single _: |
|
841 | Show objects beginning with a single _: | |
842 |
|
842 | |||
843 | %psearch -a _* list objects beginning with a single underscore""" |
|
843 | %psearch -a _* list objects beginning with a single underscore""" | |
844 | try: |
|
844 | try: | |
845 | parameter_s = parameter_s.encode('ascii') |
|
845 | parameter_s = parameter_s.encode('ascii') | |
846 | except UnicodeEncodeError: |
|
846 | except UnicodeEncodeError: | |
847 | print 'Python identifiers can only contain ascii characters.' |
|
847 | print 'Python identifiers can only contain ascii characters.' | |
848 | return |
|
848 | return | |
849 |
|
849 | |||
850 | # default namespaces to be searched |
|
850 | # default namespaces to be searched | |
851 | def_search = ['user','builtin'] |
|
851 | def_search = ['user','builtin'] | |
852 |
|
852 | |||
853 | # Process options/args |
|
853 | # Process options/args | |
854 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
854 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
855 | opt = opts.get |
|
855 | opt = opts.get | |
856 | shell = self.shell |
|
856 | shell = self.shell | |
857 | psearch = shell.inspector.psearch |
|
857 | psearch = shell.inspector.psearch | |
858 |
|
858 | |||
859 | # select case options |
|
859 | # select case options | |
860 | if opts.has_key('i'): |
|
860 | if opts.has_key('i'): | |
861 | ignore_case = True |
|
861 | ignore_case = True | |
862 | elif opts.has_key('c'): |
|
862 | elif opts.has_key('c'): | |
863 | ignore_case = False |
|
863 | ignore_case = False | |
864 | else: |
|
864 | else: | |
865 | ignore_case = not shell.wildcards_case_sensitive |
|
865 | ignore_case = not shell.wildcards_case_sensitive | |
866 |
|
866 | |||
867 | # Build list of namespaces to search from user options |
|
867 | # Build list of namespaces to search from user options | |
868 | def_search.extend(opt('s',[])) |
|
868 | def_search.extend(opt('s',[])) | |
869 | ns_exclude = ns_exclude=opt('e',[]) |
|
869 | ns_exclude = ns_exclude=opt('e',[]) | |
870 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
870 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
871 |
|
871 | |||
872 | # Call the actual search |
|
872 | # Call the actual search | |
873 | try: |
|
873 | try: | |
874 | psearch(args,shell.ns_table,ns_search, |
|
874 | psearch(args,shell.ns_table,ns_search, | |
875 | show_all=opt('a'),ignore_case=ignore_case) |
|
875 | show_all=opt('a'),ignore_case=ignore_case) | |
876 | except: |
|
876 | except: | |
877 | shell.showtraceback() |
|
877 | shell.showtraceback() | |
878 |
|
878 | |||
879 | def magic_who_ls(self, parameter_s=''): |
|
879 | def magic_who_ls(self, parameter_s=''): | |
880 | """Return a sorted list of all interactive variables. |
|
880 | """Return a sorted list of all interactive variables. | |
881 |
|
881 | |||
882 | If arguments are given, only variables of types matching these |
|
882 | If arguments are given, only variables of types matching these | |
883 | arguments are returned.""" |
|
883 | arguments are returned.""" | |
884 |
|
884 | |||
885 | user_ns = self.shell.user_ns |
|
885 | user_ns = self.shell.user_ns | |
886 | internal_ns = self.shell.internal_ns |
|
886 | internal_ns = self.shell.internal_ns | |
887 | user_config_ns = self.shell.user_config_ns |
|
887 | user_config_ns = self.shell.user_config_ns | |
888 | out = [ i for i in user_ns |
|
888 | out = [ i for i in user_ns | |
889 | if not i.startswith('_') \ |
|
889 | if not i.startswith('_') \ | |
890 | and not (i in internal_ns or i in user_config_ns) ] |
|
890 | and not (i in internal_ns or i in user_config_ns) ] | |
891 |
|
891 | |||
892 | typelist = parameter_s.split() |
|
892 | typelist = parameter_s.split() | |
893 | if typelist: |
|
893 | if typelist: | |
894 | typeset = set(typelist) |
|
894 | typeset = set(typelist) | |
895 | out = [i for i in out if type(i).__name__ in typeset] |
|
895 | out = [i for i in out if type(i).__name__ in typeset] | |
896 |
|
896 | |||
897 | out.sort() |
|
897 | out.sort() | |
898 | return out |
|
898 | return out | |
899 |
|
899 | |||
900 | def magic_who(self, parameter_s=''): |
|
900 | def magic_who(self, parameter_s=''): | |
901 | """Print all interactive variables, with some minimal formatting. |
|
901 | """Print all interactive variables, with some minimal formatting. | |
902 |
|
902 | |||
903 | If any arguments are given, only variables whose type matches one of |
|
903 | If any arguments are given, only variables whose type matches one of | |
904 | these are printed. For example: |
|
904 | these are printed. For example: | |
905 |
|
905 | |||
906 | %who function str |
|
906 | %who function str | |
907 |
|
907 | |||
908 | will only list functions and strings, excluding all other types of |
|
908 | will only list functions and strings, excluding all other types of | |
909 | variables. To find the proper type names, simply use type(var) at a |
|
909 | variables. To find the proper type names, simply use type(var) at a | |
910 | command line to see how python prints type names. For example: |
|
910 | command line to see how python prints type names. For example: | |
911 |
|
911 | |||
912 | In [1]: type('hello')\\ |
|
912 | In [1]: type('hello')\\ | |
913 | Out[1]: <type 'str'> |
|
913 | Out[1]: <type 'str'> | |
914 |
|
914 | |||
915 | indicates that the type name for strings is 'str'. |
|
915 | indicates that the type name for strings is 'str'. | |
916 |
|
916 | |||
917 | %who always excludes executed names loaded through your configuration |
|
917 | %who always excludes executed names loaded through your configuration | |
918 | file and things which are internal to IPython. |
|
918 | file and things which are internal to IPython. | |
919 |
|
919 | |||
920 | This is deliberate, as typically you may load many modules and the |
|
920 | This is deliberate, as typically you may load many modules and the | |
921 | purpose of %who is to show you only what you've manually defined.""" |
|
921 | purpose of %who is to show you only what you've manually defined.""" | |
922 |
|
922 | |||
923 | varlist = self.magic_who_ls(parameter_s) |
|
923 | varlist = self.magic_who_ls(parameter_s) | |
924 | if not varlist: |
|
924 | if not varlist: | |
925 | if parameter_s: |
|
925 | if parameter_s: | |
926 | print 'No variables match your requested type.' |
|
926 | print 'No variables match your requested type.' | |
927 | else: |
|
927 | else: | |
928 | print 'Interactive namespace is empty.' |
|
928 | print 'Interactive namespace is empty.' | |
929 | return |
|
929 | return | |
930 |
|
930 | |||
931 | # if we have variables, move on... |
|
931 | # if we have variables, move on... | |
932 | count = 0 |
|
932 | count = 0 | |
933 | for i in varlist: |
|
933 | for i in varlist: | |
934 | print i+'\t', |
|
934 | print i+'\t', | |
935 | count += 1 |
|
935 | count += 1 | |
936 | if count > 8: |
|
936 | if count > 8: | |
937 | count = 0 |
|
937 | count = 0 | |
938 |
|
938 | |||
939 |
|
939 | |||
940 |
|
940 | |||
941 | def magic_whos(self, parameter_s=''): |
|
941 | def magic_whos(self, parameter_s=''): | |
942 | """Like %who, but gives some extra information about each variable. |
|
942 | """Like %who, but gives some extra information about each variable. | |
943 |
|
943 | |||
944 | The same type filtering of %who can be applied here. |
|
944 | The same type filtering of %who can be applied here. | |
945 |
|
945 | |||
946 | For all variables, the type is printed. Additionally it prints: |
|
946 | For all variables, the type is printed. Additionally it prints: | |
947 |
|
947 | |||
948 | - For {},[],(): their length. |
|
948 | - For {},[],(): their length. | |
949 |
|
949 | |||
950 | - For numpy and Numeric arrays, a summary with shape, number of |
|
950 | - For numpy and Numeric arrays, a summary with shape, number of | |
951 | elements, typecode and size in memory. |
|
951 | elements, typecode and size in memory. | |
952 |
|
952 | |||
953 | - Everything else: a string representation, snipping their middle if |
|
953 | - Everything else: a string representation, snipping their middle if | |
954 | too long.""" |
|
954 | too long.""" | |
955 |
|
955 | |||
956 | varnames = self.magic_who_ls(parameter_s) |
|
956 | varnames = self.magic_who_ls(parameter_s) | |
957 | if not varnames: |
|
957 | if not varnames: | |
958 | if parameter_s: |
|
958 | if parameter_s: | |
959 | print 'No variables match your requested type.' |
|
959 | print 'No variables match your requested type.' | |
960 | else: |
|
960 | else: | |
961 | print 'Interactive namespace is empty.' |
|
961 | print 'Interactive namespace is empty.' | |
962 | return |
|
962 | return | |
963 |
|
963 | |||
964 | # if we have variables, move on... |
|
964 | # if we have variables, move on... | |
965 |
|
965 | |||
966 | # for these types, show len() instead of data: |
|
966 | # for these types, show len() instead of data: | |
967 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
967 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
968 |
|
968 | |||
969 | # for numpy/Numeric arrays, display summary info |
|
969 | # for numpy/Numeric arrays, display summary info | |
970 | try: |
|
970 | try: | |
971 | import numpy |
|
971 | import numpy | |
972 | except ImportError: |
|
972 | except ImportError: | |
973 | ndarray_type = None |
|
973 | ndarray_type = None | |
974 | else: |
|
974 | else: | |
975 | ndarray_type = numpy.ndarray.__name__ |
|
975 | ndarray_type = numpy.ndarray.__name__ | |
976 | try: |
|
976 | try: | |
977 | import Numeric |
|
977 | import Numeric | |
978 | except ImportError: |
|
978 | except ImportError: | |
979 | array_type = None |
|
979 | array_type = None | |
980 | else: |
|
980 | else: | |
981 | array_type = Numeric.ArrayType.__name__ |
|
981 | array_type = Numeric.ArrayType.__name__ | |
982 |
|
982 | |||
983 | # Find all variable names and types so we can figure out column sizes |
|
983 | # Find all variable names and types so we can figure out column sizes | |
984 | def get_vars(i): |
|
984 | def get_vars(i): | |
985 | return self.shell.user_ns[i] |
|
985 | return self.shell.user_ns[i] | |
986 |
|
986 | |||
987 | # some types are well known and can be shorter |
|
987 | # some types are well known and can be shorter | |
988 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
988 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
989 | def type_name(v): |
|
989 | def type_name(v): | |
990 | tn = type(v).__name__ |
|
990 | tn = type(v).__name__ | |
991 | return abbrevs.get(tn,tn) |
|
991 | return abbrevs.get(tn,tn) | |
992 |
|
992 | |||
993 | varlist = map(get_vars,varnames) |
|
993 | varlist = map(get_vars,varnames) | |
994 |
|
994 | |||
995 | typelist = [] |
|
995 | typelist = [] | |
996 | for vv in varlist: |
|
996 | for vv in varlist: | |
997 | tt = type_name(vv) |
|
997 | tt = type_name(vv) | |
998 |
|
998 | |||
999 | if tt=='instance': |
|
999 | if tt=='instance': | |
1000 | typelist.append( abbrevs.get(str(vv.__class__), |
|
1000 | typelist.append( abbrevs.get(str(vv.__class__), | |
1001 | str(vv.__class__))) |
|
1001 | str(vv.__class__))) | |
1002 | else: |
|
1002 | else: | |
1003 | typelist.append(tt) |
|
1003 | typelist.append(tt) | |
1004 |
|
1004 | |||
1005 | # column labels and # of spaces as separator |
|
1005 | # column labels and # of spaces as separator | |
1006 | varlabel = 'Variable' |
|
1006 | varlabel = 'Variable' | |
1007 | typelabel = 'Type' |
|
1007 | typelabel = 'Type' | |
1008 | datalabel = 'Data/Info' |
|
1008 | datalabel = 'Data/Info' | |
1009 | colsep = 3 |
|
1009 | colsep = 3 | |
1010 | # variable format strings |
|
1010 | # variable format strings | |
1011 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1011 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
1012 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1012 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
1013 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1013 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1014 | # find the size of the columns to format the output nicely |
|
1014 | # find the size of the columns to format the output nicely | |
1015 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1015 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1016 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1016 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1017 | # table header |
|
1017 | # table header | |
1018 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1018 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1019 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1019 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1020 | # and the table itself |
|
1020 | # and the table itself | |
1021 | kb = 1024 |
|
1021 | kb = 1024 | |
1022 | Mb = 1048576 # kb**2 |
|
1022 | Mb = 1048576 # kb**2 | |
1023 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1023 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1024 | print itpl(vformat), |
|
1024 | print itpl(vformat), | |
1025 | if vtype in seq_types: |
|
1025 | if vtype in seq_types: | |
1026 | print len(var) |
|
1026 | print len(var) | |
1027 | elif vtype in [array_type,ndarray_type]: |
|
1027 | elif vtype in [array_type,ndarray_type]: | |
1028 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1028 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1029 | if vtype==ndarray_type: |
|
1029 | if vtype==ndarray_type: | |
1030 | # numpy |
|
1030 | # numpy | |
1031 | vsize = var.size |
|
1031 | vsize = var.size | |
1032 | vbytes = vsize*var.itemsize |
|
1032 | vbytes = vsize*var.itemsize | |
1033 | vdtype = var.dtype |
|
1033 | vdtype = var.dtype | |
1034 | else: |
|
1034 | else: | |
1035 | # Numeric |
|
1035 | # Numeric | |
1036 | vsize = Numeric.size(var) |
|
1036 | vsize = Numeric.size(var) | |
1037 | vbytes = vsize*var.itemsize() |
|
1037 | vbytes = vsize*var.itemsize() | |
1038 | vdtype = var.typecode() |
|
1038 | vdtype = var.typecode() | |
1039 |
|
1039 | |||
1040 | if vbytes < 100000: |
|
1040 | if vbytes < 100000: | |
1041 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1041 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1042 | else: |
|
1042 | else: | |
1043 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1043 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1044 | if vbytes < Mb: |
|
1044 | if vbytes < Mb: | |
1045 | print '(%s kb)' % (vbytes/kb,) |
|
1045 | print '(%s kb)' % (vbytes/kb,) | |
1046 | else: |
|
1046 | else: | |
1047 | print '(%s Mb)' % (vbytes/Mb,) |
|
1047 | print '(%s Mb)' % (vbytes/Mb,) | |
1048 | else: |
|
1048 | else: | |
1049 | try: |
|
1049 | try: | |
1050 | vstr = str(var) |
|
1050 | vstr = str(var) | |
1051 | except UnicodeEncodeError: |
|
1051 | except UnicodeEncodeError: | |
1052 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1052 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
1053 | 'backslashreplace') |
|
1053 | 'backslashreplace') | |
1054 | vstr = vstr.replace('\n','\\n') |
|
1054 | vstr = vstr.replace('\n','\\n') | |
1055 | if len(vstr) < 50: |
|
1055 | if len(vstr) < 50: | |
1056 | print vstr |
|
1056 | print vstr | |
1057 | else: |
|
1057 | else: | |
1058 | printpl(vfmt_short) |
|
1058 | printpl(vfmt_short) | |
1059 |
|
1059 | |||
1060 | def magic_reset(self, parameter_s=''): |
|
1060 | def magic_reset(self, parameter_s=''): | |
1061 | """Resets the namespace by removing all names defined by the user. |
|
1061 | """Resets the namespace by removing all names defined by the user. | |
1062 |
|
1062 | |||
1063 | Input/Output history are left around in case you need them. |
|
1063 | Input/Output history are left around in case you need them. | |
1064 |
|
1064 | |||
1065 | Parameters |
|
1065 | Parameters | |
1066 | ---------- |
|
1066 | ---------- | |
1067 | -y : force reset without asking for confirmation. |
|
1067 | -y : force reset without asking for confirmation. | |
1068 |
|
1068 | |||
1069 | Examples |
|
1069 | Examples | |
1070 | -------- |
|
1070 | -------- | |
1071 | In [6]: a = 1 |
|
1071 | In [6]: a = 1 | |
1072 |
|
1072 | |||
1073 | In [7]: a |
|
1073 | In [7]: a | |
1074 | Out[7]: 1 |
|
1074 | Out[7]: 1 | |
1075 |
|
1075 | |||
1076 | In [8]: 'a' in _ip.user_ns |
|
1076 | In [8]: 'a' in _ip.user_ns | |
1077 | Out[8]: True |
|
1077 | Out[8]: True | |
1078 |
|
1078 | |||
1079 | In [9]: %reset -f |
|
1079 | In [9]: %reset -f | |
1080 |
|
1080 | |||
1081 | In [10]: 'a' in _ip.user_ns |
|
1081 | In [10]: 'a' in _ip.user_ns | |
1082 | Out[10]: False |
|
1082 | Out[10]: False | |
1083 | """ |
|
1083 | """ | |
1084 |
|
1084 | |||
1085 | if parameter_s == '-f': |
|
1085 | if parameter_s == '-f': | |
1086 | ans = True |
|
1086 | ans = True | |
1087 | else: |
|
1087 | else: | |
1088 | ans = self.shell.ask_yes_no( |
|
1088 | ans = self.shell.ask_yes_no( | |
1089 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1089 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1090 | if not ans: |
|
1090 | if not ans: | |
1091 | print 'Nothing done.' |
|
1091 | print 'Nothing done.' | |
1092 | return |
|
1092 | return | |
1093 | user_ns = self.shell.user_ns |
|
1093 | user_ns = self.shell.user_ns | |
1094 | for i in self.magic_who_ls(): |
|
1094 | for i in self.magic_who_ls(): | |
1095 | del(user_ns[i]) |
|
1095 | del(user_ns[i]) | |
1096 |
|
1096 | |||
1097 | # Also flush the private list of module references kept for script |
|
1097 | # Also flush the private list of module references kept for script | |
1098 | # execution protection |
|
1098 | # execution protection | |
1099 | self.shell.clear_main_mod_cache() |
|
1099 | self.shell.clear_main_mod_cache() | |
1100 |
|
1100 | |||
1101 | def magic_logstart(self,parameter_s=''): |
|
1101 | def magic_logstart(self,parameter_s=''): | |
1102 | """Start logging anywhere in a session. |
|
1102 | """Start logging anywhere in a session. | |
1103 |
|
1103 | |||
1104 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1104 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1105 |
|
1105 | |||
1106 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1106 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1107 | current directory, in 'rotate' mode (see below). |
|
1107 | current directory, in 'rotate' mode (see below). | |
1108 |
|
1108 | |||
1109 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1109 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1110 | history up to that point and then continues logging. |
|
1110 | history up to that point and then continues logging. | |
1111 |
|
1111 | |||
1112 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1112 | %logstart takes a second optional parameter: logging mode. This can be one | |
1113 | of (note that the modes are given unquoted):\\ |
|
1113 | of (note that the modes are given unquoted):\\ | |
1114 | append: well, that says it.\\ |
|
1114 | append: well, that says it.\\ | |
1115 | backup: rename (if exists) to name~ and start name.\\ |
|
1115 | backup: rename (if exists) to name~ and start name.\\ | |
1116 | global: single logfile in your home dir, appended to.\\ |
|
1116 | global: single logfile in your home dir, appended to.\\ | |
1117 | over : overwrite existing log.\\ |
|
1117 | over : overwrite existing log.\\ | |
1118 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1118 | rotate: create rotating logs name.1~, name.2~, etc. | |
1119 |
|
1119 | |||
1120 | Options: |
|
1120 | Options: | |
1121 |
|
1121 | |||
1122 | -o: log also IPython's output. In this mode, all commands which |
|
1122 | -o: log also IPython's output. In this mode, all commands which | |
1123 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1123 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1124 | their corresponding input line. The output lines are always |
|
1124 | their corresponding input line. The output lines are always | |
1125 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1125 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1126 | Python code. |
|
1126 | Python code. | |
1127 |
|
1127 | |||
1128 | Since this marker is always the same, filtering only the output from |
|
1128 | Since this marker is always the same, filtering only the output from | |
1129 | a log is very easy, using for example a simple awk call: |
|
1129 | a log is very easy, using for example a simple awk call: | |
1130 |
|
1130 | |||
1131 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1131 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1132 |
|
1132 | |||
1133 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1133 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1134 | input, so that user lines are logged in their final form, converted |
|
1134 | input, so that user lines are logged in their final form, converted | |
1135 | into valid Python. For example, %Exit is logged as |
|
1135 | into valid Python. For example, %Exit is logged as | |
1136 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1136 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1137 | exactly as typed, with no transformations applied. |
|
1137 | exactly as typed, with no transformations applied. | |
1138 |
|
1138 | |||
1139 | -t: put timestamps before each input line logged (these are put in |
|
1139 | -t: put timestamps before each input line logged (these are put in | |
1140 | comments).""" |
|
1140 | comments).""" | |
1141 |
|
1141 | |||
1142 | opts,par = self.parse_options(parameter_s,'ort') |
|
1142 | opts,par = self.parse_options(parameter_s,'ort') | |
1143 | log_output = 'o' in opts |
|
1143 | log_output = 'o' in opts | |
1144 | log_raw_input = 'r' in opts |
|
1144 | log_raw_input = 'r' in opts | |
1145 | timestamp = 't' in opts |
|
1145 | timestamp = 't' in opts | |
1146 |
|
1146 | |||
1147 | logger = self.shell.logger |
|
1147 | logger = self.shell.logger | |
1148 |
|
1148 | |||
1149 | # if no args are given, the defaults set in the logger constructor by |
|
1149 | # if no args are given, the defaults set in the logger constructor by | |
1150 | # ipytohn remain valid |
|
1150 | # ipytohn remain valid | |
1151 | if par: |
|
1151 | if par: | |
1152 | try: |
|
1152 | try: | |
1153 | logfname,logmode = par.split() |
|
1153 | logfname,logmode = par.split() | |
1154 | except: |
|
1154 | except: | |
1155 | logfname = par |
|
1155 | logfname = par | |
1156 | logmode = 'backup' |
|
1156 | logmode = 'backup' | |
1157 | else: |
|
1157 | else: | |
1158 | logfname = logger.logfname |
|
1158 | logfname = logger.logfname | |
1159 | logmode = logger.logmode |
|
1159 | logmode = logger.logmode | |
1160 | # put logfname into rc struct as if it had been called on the command |
|
1160 | # put logfname into rc struct as if it had been called on the command | |
1161 | # line, so it ends up saved in the log header Save it in case we need |
|
1161 | # line, so it ends up saved in the log header Save it in case we need | |
1162 | # to restore it... |
|
1162 | # to restore it... | |
1163 | old_logfile = self.shell.logfile |
|
1163 | old_logfile = self.shell.logfile | |
1164 | if logfname: |
|
1164 | if logfname: | |
1165 | logfname = os.path.expanduser(logfname) |
|
1165 | logfname = os.path.expanduser(logfname) | |
1166 | self.shell.logfile = logfname |
|
1166 | self.shell.logfile = logfname | |
1167 |
|
1167 | |||
1168 | loghead = '# IPython log file\n\n' |
|
1168 | loghead = '# IPython log file\n\n' | |
1169 | try: |
|
1169 | try: | |
1170 | started = logger.logstart(logfname,loghead,logmode, |
|
1170 | started = logger.logstart(logfname,loghead,logmode, | |
1171 | log_output,timestamp,log_raw_input) |
|
1171 | log_output,timestamp,log_raw_input) | |
1172 | except: |
|
1172 | except: | |
1173 | rc.opts.logfile = old_logfile |
|
1173 | rc.opts.logfile = old_logfile | |
1174 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1174 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1175 | else: |
|
1175 | else: | |
1176 | # log input history up to this point, optionally interleaving |
|
1176 | # log input history up to this point, optionally interleaving | |
1177 | # output if requested |
|
1177 | # output if requested | |
1178 |
|
1178 | |||
1179 | if timestamp: |
|
1179 | if timestamp: | |
1180 | # disable timestamping for the previous history, since we've |
|
1180 | # disable timestamping for the previous history, since we've | |
1181 | # lost those already (no time machine here). |
|
1181 | # lost those already (no time machine here). | |
1182 | logger.timestamp = False |
|
1182 | logger.timestamp = False | |
1183 |
|
1183 | |||
1184 | if log_raw_input: |
|
1184 | if log_raw_input: | |
1185 | input_hist = self.shell.input_hist_raw |
|
1185 | input_hist = self.shell.input_hist_raw | |
1186 | else: |
|
1186 | else: | |
1187 | input_hist = self.shell.input_hist |
|
1187 | input_hist = self.shell.input_hist | |
1188 |
|
1188 | |||
1189 | if log_output: |
|
1189 | if log_output: | |
1190 | log_write = logger.log_write |
|
1190 | log_write = logger.log_write | |
1191 | output_hist = self.shell.output_hist |
|
1191 | output_hist = self.shell.output_hist | |
1192 | for n in range(1,len(input_hist)-1): |
|
1192 | for n in range(1,len(input_hist)-1): | |
1193 | log_write(input_hist[n].rstrip()) |
|
1193 | log_write(input_hist[n].rstrip()) | |
1194 | if n in output_hist: |
|
1194 | if n in output_hist: | |
1195 | log_write(repr(output_hist[n]),'output') |
|
1195 | log_write(repr(output_hist[n]),'output') | |
1196 | else: |
|
1196 | else: | |
1197 | logger.log_write(input_hist[1:]) |
|
1197 | logger.log_write(input_hist[1:]) | |
1198 | if timestamp: |
|
1198 | if timestamp: | |
1199 | # re-enable timestamping |
|
1199 | # re-enable timestamping | |
1200 | logger.timestamp = True |
|
1200 | logger.timestamp = True | |
1201 |
|
1201 | |||
1202 | print ('Activating auto-logging. ' |
|
1202 | print ('Activating auto-logging. ' | |
1203 | 'Current session state plus future input saved.') |
|
1203 | 'Current session state plus future input saved.') | |
1204 | logger.logstate() |
|
1204 | logger.logstate() | |
1205 |
|
1205 | |||
1206 | def magic_logstop(self,parameter_s=''): |
|
1206 | def magic_logstop(self,parameter_s=''): | |
1207 | """Fully stop logging and close log file. |
|
1207 | """Fully stop logging and close log file. | |
1208 |
|
1208 | |||
1209 | In order to start logging again, a new %logstart call needs to be made, |
|
1209 | In order to start logging again, a new %logstart call needs to be made, | |
1210 | possibly (though not necessarily) with a new filename, mode and other |
|
1210 | possibly (though not necessarily) with a new filename, mode and other | |
1211 | options.""" |
|
1211 | options.""" | |
1212 | self.logger.logstop() |
|
1212 | self.logger.logstop() | |
1213 |
|
1213 | |||
1214 | def magic_logoff(self,parameter_s=''): |
|
1214 | def magic_logoff(self,parameter_s=''): | |
1215 | """Temporarily stop logging. |
|
1215 | """Temporarily stop logging. | |
1216 |
|
1216 | |||
1217 | You must have previously started logging.""" |
|
1217 | You must have previously started logging.""" | |
1218 | self.shell.logger.switch_log(0) |
|
1218 | self.shell.logger.switch_log(0) | |
1219 |
|
1219 | |||
1220 | def magic_logon(self,parameter_s=''): |
|
1220 | def magic_logon(self,parameter_s=''): | |
1221 | """Restart logging. |
|
1221 | """Restart logging. | |
1222 |
|
1222 | |||
1223 | This function is for restarting logging which you've temporarily |
|
1223 | This function is for restarting logging which you've temporarily | |
1224 | stopped with %logoff. For starting logging for the first time, you |
|
1224 | stopped with %logoff. For starting logging for the first time, you | |
1225 | must use the %logstart function, which allows you to specify an |
|
1225 | must use the %logstart function, which allows you to specify an | |
1226 | optional log filename.""" |
|
1226 | optional log filename.""" | |
1227 |
|
1227 | |||
1228 | self.shell.logger.switch_log(1) |
|
1228 | self.shell.logger.switch_log(1) | |
1229 |
|
1229 | |||
1230 | def magic_logstate(self,parameter_s=''): |
|
1230 | def magic_logstate(self,parameter_s=''): | |
1231 | """Print the status of the logging system.""" |
|
1231 | """Print the status of the logging system.""" | |
1232 |
|
1232 | |||
1233 | self.shell.logger.logstate() |
|
1233 | self.shell.logger.logstate() | |
1234 |
|
1234 | |||
1235 | def magic_pdb(self, parameter_s=''): |
|
1235 | def magic_pdb(self, parameter_s=''): | |
1236 | """Control the automatic calling of the pdb interactive debugger. |
|
1236 | """Control the automatic calling of the pdb interactive debugger. | |
1237 |
|
1237 | |||
1238 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1238 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1239 | argument it works as a toggle. |
|
1239 | argument it works as a toggle. | |
1240 |
|
1240 | |||
1241 | When an exception is triggered, IPython can optionally call the |
|
1241 | When an exception is triggered, IPython can optionally call the | |
1242 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1242 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1243 | this feature on and off. |
|
1243 | this feature on and off. | |
1244 |
|
1244 | |||
1245 | The initial state of this feature is set in your ipythonrc |
|
1245 | The initial state of this feature is set in your ipythonrc | |
1246 | configuration file (the variable is called 'pdb'). |
|
1246 | configuration file (the variable is called 'pdb'). | |
1247 |
|
1247 | |||
1248 | If you want to just activate the debugger AFTER an exception has fired, |
|
1248 | If you want to just activate the debugger AFTER an exception has fired, | |
1249 | without having to type '%pdb on' and rerunning your code, you can use |
|
1249 | without having to type '%pdb on' and rerunning your code, you can use | |
1250 | the %debug magic.""" |
|
1250 | the %debug magic.""" | |
1251 |
|
1251 | |||
1252 | par = parameter_s.strip().lower() |
|
1252 | par = parameter_s.strip().lower() | |
1253 |
|
1253 | |||
1254 | if par: |
|
1254 | if par: | |
1255 | try: |
|
1255 | try: | |
1256 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1256 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1257 | except KeyError: |
|
1257 | except KeyError: | |
1258 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1258 | print ('Incorrect argument. Use on/1, off/0, ' | |
1259 | 'or nothing for a toggle.') |
|
1259 | 'or nothing for a toggle.') | |
1260 | return |
|
1260 | return | |
1261 | else: |
|
1261 | else: | |
1262 | # toggle |
|
1262 | # toggle | |
1263 | new_pdb = not self.shell.call_pdb |
|
1263 | new_pdb = not self.shell.call_pdb | |
1264 |
|
1264 | |||
1265 | # set on the shell |
|
1265 | # set on the shell | |
1266 | self.shell.call_pdb = new_pdb |
|
1266 | self.shell.call_pdb = new_pdb | |
1267 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1267 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1268 |
|
1268 | |||
1269 | def magic_debug(self, parameter_s=''): |
|
1269 | def magic_debug(self, parameter_s=''): | |
1270 | """Activate the interactive debugger in post-mortem mode. |
|
1270 | """Activate the interactive debugger in post-mortem mode. | |
1271 |
|
1271 | |||
1272 | If an exception has just occurred, this lets you inspect its stack |
|
1272 | If an exception has just occurred, this lets you inspect its stack | |
1273 | frames interactively. Note that this will always work only on the last |
|
1273 | frames interactively. Note that this will always work only on the last | |
1274 | traceback that occurred, so you must call this quickly after an |
|
1274 | traceback that occurred, so you must call this quickly after an | |
1275 | exception that you wish to inspect has fired, because if another one |
|
1275 | exception that you wish to inspect has fired, because if another one | |
1276 | occurs, it clobbers the previous one. |
|
1276 | occurs, it clobbers the previous one. | |
1277 |
|
1277 | |||
1278 | If you want IPython to automatically do this on every exception, see |
|
1278 | If you want IPython to automatically do this on every exception, see | |
1279 | the %pdb magic for more details. |
|
1279 | the %pdb magic for more details. | |
1280 | """ |
|
1280 | """ | |
1281 | self.shell.debugger(force=True) |
|
1281 | self.shell.debugger(force=True) | |
1282 |
|
1282 | |||
1283 | @testdec.skip_doctest |
|
1283 | @testdec.skip_doctest | |
1284 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1284 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1285 | opts=None,arg_lst=None,prog_ns=None): |
|
1285 | opts=None,arg_lst=None,prog_ns=None): | |
1286 |
|
1286 | |||
1287 | """Run a statement through the python code profiler. |
|
1287 | """Run a statement through the python code profiler. | |
1288 |
|
1288 | |||
1289 | Usage: |
|
1289 | Usage: | |
1290 | %prun [options] statement |
|
1290 | %prun [options] statement | |
1291 |
|
1291 | |||
1292 | The given statement (which doesn't require quote marks) is run via the |
|
1292 | The given statement (which doesn't require quote marks) is run via the | |
1293 | python profiler in a manner similar to the profile.run() function. |
|
1293 | python profiler in a manner similar to the profile.run() function. | |
1294 | Namespaces are internally managed to work correctly; profile.run |
|
1294 | Namespaces are internally managed to work correctly; profile.run | |
1295 | cannot be used in IPython because it makes certain assumptions about |
|
1295 | cannot be used in IPython because it makes certain assumptions about | |
1296 | namespaces which do not hold under IPython. |
|
1296 | namespaces which do not hold under IPython. | |
1297 |
|
1297 | |||
1298 | Options: |
|
1298 | Options: | |
1299 |
|
1299 | |||
1300 | -l <limit>: you can place restrictions on what or how much of the |
|
1300 | -l <limit>: you can place restrictions on what or how much of the | |
1301 | profile gets printed. The limit value can be: |
|
1301 | profile gets printed. The limit value can be: | |
1302 |
|
1302 | |||
1303 | * A string: only information for function names containing this string |
|
1303 | * A string: only information for function names containing this string | |
1304 | is printed. |
|
1304 | is printed. | |
1305 |
|
1305 | |||
1306 | * An integer: only these many lines are printed. |
|
1306 | * An integer: only these many lines are printed. | |
1307 |
|
1307 | |||
1308 | * A float (between 0 and 1): this fraction of the report is printed |
|
1308 | * A float (between 0 and 1): this fraction of the report is printed | |
1309 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1309 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1310 |
|
1310 | |||
1311 | You can combine several limits with repeated use of the option. For |
|
1311 | You can combine several limits with repeated use of the option. For | |
1312 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1312 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1313 | information about class constructors. |
|
1313 | information about class constructors. | |
1314 |
|
1314 | |||
1315 | -r: return the pstats.Stats object generated by the profiling. This |
|
1315 | -r: return the pstats.Stats object generated by the profiling. This | |
1316 | object has all the information about the profile in it, and you can |
|
1316 | object has all the information about the profile in it, and you can | |
1317 | later use it for further analysis or in other functions. |
|
1317 | later use it for further analysis or in other functions. | |
1318 |
|
1318 | |||
1319 | -s <key>: sort profile by given key. You can provide more than one key |
|
1319 | -s <key>: sort profile by given key. You can provide more than one key | |
1320 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1320 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1321 | default sorting key is 'time'. |
|
1321 | default sorting key is 'time'. | |
1322 |
|
1322 | |||
1323 | The following is copied verbatim from the profile documentation |
|
1323 | The following is copied verbatim from the profile documentation | |
1324 | referenced below: |
|
1324 | referenced below: | |
1325 |
|
1325 | |||
1326 | When more than one key is provided, additional keys are used as |
|
1326 | When more than one key is provided, additional keys are used as | |
1327 | secondary criteria when the there is equality in all keys selected |
|
1327 | secondary criteria when the there is equality in all keys selected | |
1328 | before them. |
|
1328 | before them. | |
1329 |
|
1329 | |||
1330 | Abbreviations can be used for any key names, as long as the |
|
1330 | Abbreviations can be used for any key names, as long as the | |
1331 | abbreviation is unambiguous. The following are the keys currently |
|
1331 | abbreviation is unambiguous. The following are the keys currently | |
1332 | defined: |
|
1332 | defined: | |
1333 |
|
1333 | |||
1334 | Valid Arg Meaning |
|
1334 | Valid Arg Meaning | |
1335 | "calls" call count |
|
1335 | "calls" call count | |
1336 | "cumulative" cumulative time |
|
1336 | "cumulative" cumulative time | |
1337 | "file" file name |
|
1337 | "file" file name | |
1338 | "module" file name |
|
1338 | "module" file name | |
1339 | "pcalls" primitive call count |
|
1339 | "pcalls" primitive call count | |
1340 | "line" line number |
|
1340 | "line" line number | |
1341 | "name" function name |
|
1341 | "name" function name | |
1342 | "nfl" name/file/line |
|
1342 | "nfl" name/file/line | |
1343 | "stdname" standard name |
|
1343 | "stdname" standard name | |
1344 | "time" internal time |
|
1344 | "time" internal time | |
1345 |
|
1345 | |||
1346 | Note that all sorts on statistics are in descending order (placing |
|
1346 | Note that all sorts on statistics are in descending order (placing | |
1347 | most time consuming items first), where as name, file, and line number |
|
1347 | most time consuming items first), where as name, file, and line number | |
1348 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1348 | searches are in ascending order (i.e., alphabetical). The subtle | |
1349 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1349 | distinction between "nfl" and "stdname" is that the standard name is a | |
1350 | sort of the name as printed, which means that the embedded line |
|
1350 | sort of the name as printed, which means that the embedded line | |
1351 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1351 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1352 | would (if the file names were the same) appear in the string order |
|
1352 | would (if the file names were the same) appear in the string order | |
1353 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1353 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1354 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1354 | line numbers. In fact, sort_stats("nfl") is the same as | |
1355 | sort_stats("name", "file", "line"). |
|
1355 | sort_stats("name", "file", "line"). | |
1356 |
|
1356 | |||
1357 | -T <filename>: save profile results as shown on screen to a text |
|
1357 | -T <filename>: save profile results as shown on screen to a text | |
1358 | file. The profile is still shown on screen. |
|
1358 | file. The profile is still shown on screen. | |
1359 |
|
1359 | |||
1360 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1360 | -D <filename>: save (via dump_stats) profile statistics to given | |
1361 | filename. This data is in a format understod by the pstats module, and |
|
1361 | filename. This data is in a format understod by the pstats module, and | |
1362 | is generated by a call to the dump_stats() method of profile |
|
1362 | is generated by a call to the dump_stats() method of profile | |
1363 | objects. The profile is still shown on screen. |
|
1363 | objects. The profile is still shown on screen. | |
1364 |
|
1364 | |||
1365 | If you want to run complete programs under the profiler's control, use |
|
1365 | If you want to run complete programs under the profiler's control, use | |
1366 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1366 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1367 | contains profiler specific options as described here. |
|
1367 | contains profiler specific options as described here. | |
1368 |
|
1368 | |||
1369 | You can read the complete documentation for the profile module with:: |
|
1369 | You can read the complete documentation for the profile module with:: | |
1370 |
|
1370 | |||
1371 | In [1]: import profile; profile.help() |
|
1371 | In [1]: import profile; profile.help() | |
1372 | """ |
|
1372 | """ | |
1373 |
|
1373 | |||
1374 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1374 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1375 | # protect user quote marks |
|
1375 | # protect user quote marks | |
1376 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1376 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1377 |
|
1377 | |||
1378 | if user_mode: # regular user call |
|
1378 | if user_mode: # regular user call | |
1379 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1379 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1380 | list_all=1) |
|
1380 | list_all=1) | |
1381 | namespace = self.shell.user_ns |
|
1381 | namespace = self.shell.user_ns | |
1382 | else: # called to run a program by %run -p |
|
1382 | else: # called to run a program by %run -p | |
1383 | try: |
|
1383 | try: | |
1384 | filename = get_py_filename(arg_lst[0]) |
|
1384 | filename = get_py_filename(arg_lst[0]) | |
1385 | except IOError,msg: |
|
1385 | except IOError,msg: | |
1386 | error(msg) |
|
1386 | error(msg) | |
1387 | return |
|
1387 | return | |
1388 |
|
1388 | |||
1389 | arg_str = 'execfile(filename,prog_ns)' |
|
1389 | arg_str = 'execfile(filename,prog_ns)' | |
1390 | namespace = locals() |
|
1390 | namespace = locals() | |
1391 |
|
1391 | |||
1392 | opts.merge(opts_def) |
|
1392 | opts.merge(opts_def) | |
1393 |
|
1393 | |||
1394 | prof = profile.Profile() |
|
1394 | prof = profile.Profile() | |
1395 | try: |
|
1395 | try: | |
1396 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1396 | prof = prof.runctx(arg_str,namespace,namespace) | |
1397 | sys_exit = '' |
|
1397 | sys_exit = '' | |
1398 | except SystemExit: |
|
1398 | except SystemExit: | |
1399 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1399 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1400 |
|
1400 | |||
1401 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1401 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1402 |
|
1402 | |||
1403 | lims = opts.l |
|
1403 | lims = opts.l | |
1404 | if lims: |
|
1404 | if lims: | |
1405 | lims = [] # rebuild lims with ints/floats/strings |
|
1405 | lims = [] # rebuild lims with ints/floats/strings | |
1406 | for lim in opts.l: |
|
1406 | for lim in opts.l: | |
1407 | try: |
|
1407 | try: | |
1408 | lims.append(int(lim)) |
|
1408 | lims.append(int(lim)) | |
1409 | except ValueError: |
|
1409 | except ValueError: | |
1410 | try: |
|
1410 | try: | |
1411 | lims.append(float(lim)) |
|
1411 | lims.append(float(lim)) | |
1412 | except ValueError: |
|
1412 | except ValueError: | |
1413 | lims.append(lim) |
|
1413 | lims.append(lim) | |
1414 |
|
1414 | |||
1415 | # Trap output. |
|
1415 | # Trap output. | |
1416 | stdout_trap = StringIO() |
|
1416 | stdout_trap = StringIO() | |
1417 |
|
1417 | |||
1418 | if hasattr(stats,'stream'): |
|
1418 | if hasattr(stats,'stream'): | |
1419 | # In newer versions of python, the stats object has a 'stream' |
|
1419 | # In newer versions of python, the stats object has a 'stream' | |
1420 | # attribute to write into. |
|
1420 | # attribute to write into. | |
1421 | stats.stream = stdout_trap |
|
1421 | stats.stream = stdout_trap | |
1422 | stats.print_stats(*lims) |
|
1422 | stats.print_stats(*lims) | |
1423 | else: |
|
1423 | else: | |
1424 | # For older versions, we manually redirect stdout during printing |
|
1424 | # For older versions, we manually redirect stdout during printing | |
1425 | sys_stdout = sys.stdout |
|
1425 | sys_stdout = sys.stdout | |
1426 | try: |
|
1426 | try: | |
1427 | sys.stdout = stdout_trap |
|
1427 | sys.stdout = stdout_trap | |
1428 | stats.print_stats(*lims) |
|
1428 | stats.print_stats(*lims) | |
1429 | finally: |
|
1429 | finally: | |
1430 | sys.stdout = sys_stdout |
|
1430 | sys.stdout = sys_stdout | |
1431 |
|
1431 | |||
1432 | output = stdout_trap.getvalue() |
|
1432 | output = stdout_trap.getvalue() | |
1433 | output = output.rstrip() |
|
1433 | output = output.rstrip() | |
1434 |
|
1434 | |||
1435 | page(output,screen_lines=self.shell.usable_screen_length) |
|
1435 | page(output,screen_lines=self.shell.usable_screen_length) | |
1436 | print sys_exit, |
|
1436 | print sys_exit, | |
1437 |
|
1437 | |||
1438 | dump_file = opts.D[0] |
|
1438 | dump_file = opts.D[0] | |
1439 | text_file = opts.T[0] |
|
1439 | text_file = opts.T[0] | |
1440 | if dump_file: |
|
1440 | if dump_file: | |
1441 | prof.dump_stats(dump_file) |
|
1441 | prof.dump_stats(dump_file) | |
1442 | print '\n*** Profile stats marshalled to file',\ |
|
1442 | print '\n*** Profile stats marshalled to file',\ | |
1443 | `dump_file`+'.',sys_exit |
|
1443 | `dump_file`+'.',sys_exit | |
1444 | if text_file: |
|
1444 | if text_file: | |
1445 | pfile = file(text_file,'w') |
|
1445 | pfile = file(text_file,'w') | |
1446 | pfile.write(output) |
|
1446 | pfile.write(output) | |
1447 | pfile.close() |
|
1447 | pfile.close() | |
1448 | print '\n*** Profile printout saved to text file',\ |
|
1448 | print '\n*** Profile printout saved to text file',\ | |
1449 | `text_file`+'.',sys_exit |
|
1449 | `text_file`+'.',sys_exit | |
1450 |
|
1450 | |||
1451 | if opts.has_key('r'): |
|
1451 | if opts.has_key('r'): | |
1452 | return stats |
|
1452 | return stats | |
1453 | else: |
|
1453 | else: | |
1454 | return None |
|
1454 | return None | |
1455 |
|
1455 | |||
1456 | @testdec.skip_doctest |
|
1456 | @testdec.skip_doctest | |
1457 | def magic_run(self, parameter_s ='',runner=None, |
|
1457 | def magic_run(self, parameter_s ='',runner=None, | |
1458 | file_finder=get_py_filename): |
|
1458 | file_finder=get_py_filename): | |
1459 | """Run the named file inside IPython as a program. |
|
1459 | """Run the named file inside IPython as a program. | |
1460 |
|
1460 | |||
1461 | Usage:\\ |
|
1461 | Usage:\\ | |
1462 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1462 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1463 |
|
1463 | |||
1464 | Parameters after the filename are passed as command-line arguments to |
|
1464 | Parameters after the filename are passed as command-line arguments to | |
1465 | the program (put in sys.argv). Then, control returns to IPython's |
|
1465 | the program (put in sys.argv). Then, control returns to IPython's | |
1466 | prompt. |
|
1466 | prompt. | |
1467 |
|
1467 | |||
1468 | This is similar to running at a system prompt:\\ |
|
1468 | This is similar to running at a system prompt:\\ | |
1469 | $ python file args\\ |
|
1469 | $ python file args\\ | |
1470 | but with the advantage of giving you IPython's tracebacks, and of |
|
1470 | but with the advantage of giving you IPython's tracebacks, and of | |
1471 | loading all variables into your interactive namespace for further use |
|
1471 | loading all variables into your interactive namespace for further use | |
1472 | (unless -p is used, see below). |
|
1472 | (unless -p is used, see below). | |
1473 |
|
1473 | |||
1474 | The file is executed in a namespace initially consisting only of |
|
1474 | The file is executed in a namespace initially consisting only of | |
1475 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1475 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1476 | sees its environment as if it were being run as a stand-alone program |
|
1476 | sees its environment as if it were being run as a stand-alone program | |
1477 | (except for sharing global objects such as previously imported |
|
1477 | (except for sharing global objects such as previously imported | |
1478 | modules). But after execution, the IPython interactive namespace gets |
|
1478 | modules). But after execution, the IPython interactive namespace gets | |
1479 | updated with all variables defined in the program (except for __name__ |
|
1479 | updated with all variables defined in the program (except for __name__ | |
1480 | and sys.argv). This allows for very convenient loading of code for |
|
1480 | and sys.argv). This allows for very convenient loading of code for | |
1481 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1481 | interactive work, while giving each program a 'clean sheet' to run in. | |
1482 |
|
1482 | |||
1483 | Options: |
|
1483 | Options: | |
1484 |
|
1484 | |||
1485 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1485 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1486 | without extension (as python does under import). This allows running |
|
1486 | without extension (as python does under import). This allows running | |
1487 | scripts and reloading the definitions in them without calling code |
|
1487 | scripts and reloading the definitions in them without calling code | |
1488 | protected by an ' if __name__ == "__main__" ' clause. |
|
1488 | protected by an ' if __name__ == "__main__" ' clause. | |
1489 |
|
1489 | |||
1490 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1490 | -i: run the file in IPython's namespace instead of an empty one. This | |
1491 | is useful if you are experimenting with code written in a text editor |
|
1491 | is useful if you are experimenting with code written in a text editor | |
1492 | which depends on variables defined interactively. |
|
1492 | which depends on variables defined interactively. | |
1493 |
|
1493 | |||
1494 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1494 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1495 | being run. This is particularly useful if IPython is being used to |
|
1495 | being run. This is particularly useful if IPython is being used to | |
1496 | run unittests, which always exit with a sys.exit() call. In such |
|
1496 | run unittests, which always exit with a sys.exit() call. In such | |
1497 | cases you are interested in the output of the test results, not in |
|
1497 | cases you are interested in the output of the test results, not in | |
1498 | seeing a traceback of the unittest module. |
|
1498 | seeing a traceback of the unittest module. | |
1499 |
|
1499 | |||
1500 | -t: print timing information at the end of the run. IPython will give |
|
1500 | -t: print timing information at the end of the run. IPython will give | |
1501 | you an estimated CPU time consumption for your script, which under |
|
1501 | you an estimated CPU time consumption for your script, which under | |
1502 | Unix uses the resource module to avoid the wraparound problems of |
|
1502 | Unix uses the resource module to avoid the wraparound problems of | |
1503 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1503 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1504 | is also given (for Windows platforms this is reported as 0.0). |
|
1504 | is also given (for Windows platforms this is reported as 0.0). | |
1505 |
|
1505 | |||
1506 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1506 | If -t is given, an additional -N<N> option can be given, where <N> | |
1507 | must be an integer indicating how many times you want the script to |
|
1507 | must be an integer indicating how many times you want the script to | |
1508 | run. The final timing report will include total and per run results. |
|
1508 | run. The final timing report will include total and per run results. | |
1509 |
|
1509 | |||
1510 | For example (testing the script uniq_stable.py): |
|
1510 | For example (testing the script uniq_stable.py): | |
1511 |
|
1511 | |||
1512 | In [1]: run -t uniq_stable |
|
1512 | In [1]: run -t uniq_stable | |
1513 |
|
1513 | |||
1514 | IPython CPU timings (estimated):\\ |
|
1514 | IPython CPU timings (estimated):\\ | |
1515 | User : 0.19597 s.\\ |
|
1515 | User : 0.19597 s.\\ | |
1516 | System: 0.0 s.\\ |
|
1516 | System: 0.0 s.\\ | |
1517 |
|
1517 | |||
1518 | In [2]: run -t -N5 uniq_stable |
|
1518 | In [2]: run -t -N5 uniq_stable | |
1519 |
|
1519 | |||
1520 | IPython CPU timings (estimated):\\ |
|
1520 | IPython CPU timings (estimated):\\ | |
1521 | Total runs performed: 5\\ |
|
1521 | Total runs performed: 5\\ | |
1522 | Times : Total Per run\\ |
|
1522 | Times : Total Per run\\ | |
1523 | User : 0.910862 s, 0.1821724 s.\\ |
|
1523 | User : 0.910862 s, 0.1821724 s.\\ | |
1524 | System: 0.0 s, 0.0 s. |
|
1524 | System: 0.0 s, 0.0 s. | |
1525 |
|
1525 | |||
1526 | -d: run your program under the control of pdb, the Python debugger. |
|
1526 | -d: run your program under the control of pdb, the Python debugger. | |
1527 | This allows you to execute your program step by step, watch variables, |
|
1527 | This allows you to execute your program step by step, watch variables, | |
1528 | etc. Internally, what IPython does is similar to calling: |
|
1528 | etc. Internally, what IPython does is similar to calling: | |
1529 |
|
1529 | |||
1530 | pdb.run('execfile("YOURFILENAME")') |
|
1530 | pdb.run('execfile("YOURFILENAME")') | |
1531 |
|
1531 | |||
1532 | with a breakpoint set on line 1 of your file. You can change the line |
|
1532 | with a breakpoint set on line 1 of your file. You can change the line | |
1533 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1533 | number for this automatic breakpoint to be <N> by using the -bN option | |
1534 | (where N must be an integer). For example: |
|
1534 | (where N must be an integer). For example: | |
1535 |
|
1535 | |||
1536 | %run -d -b40 myscript |
|
1536 | %run -d -b40 myscript | |
1537 |
|
1537 | |||
1538 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1538 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1539 | the first breakpoint must be set on a line which actually does |
|
1539 | the first breakpoint must be set on a line which actually does | |
1540 | something (not a comment or docstring) for it to stop execution. |
|
1540 | something (not a comment or docstring) for it to stop execution. | |
1541 |
|
1541 | |||
1542 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1542 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1543 | first enter 'c' (without qoutes) to start execution up to the first |
|
1543 | first enter 'c' (without qoutes) to start execution up to the first | |
1544 | breakpoint. |
|
1544 | breakpoint. | |
1545 |
|
1545 | |||
1546 | Entering 'help' gives information about the use of the debugger. You |
|
1546 | Entering 'help' gives information about the use of the debugger. You | |
1547 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1547 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1548 | at a prompt. |
|
1548 | at a prompt. | |
1549 |
|
1549 | |||
1550 | -p: run program under the control of the Python profiler module (which |
|
1550 | -p: run program under the control of the Python profiler module (which | |
1551 | prints a detailed report of execution times, function calls, etc). |
|
1551 | prints a detailed report of execution times, function calls, etc). | |
1552 |
|
1552 | |||
1553 | You can pass other options after -p which affect the behavior of the |
|
1553 | You can pass other options after -p which affect the behavior of the | |
1554 | profiler itself. See the docs for %prun for details. |
|
1554 | profiler itself. See the docs for %prun for details. | |
1555 |
|
1555 | |||
1556 | In this mode, the program's variables do NOT propagate back to the |
|
1556 | In this mode, the program's variables do NOT propagate back to the | |
1557 | IPython interactive namespace (because they remain in the namespace |
|
1557 | IPython interactive namespace (because they remain in the namespace | |
1558 | where the profiler executes them). |
|
1558 | where the profiler executes them). | |
1559 |
|
1559 | |||
1560 | Internally this triggers a call to %prun, see its documentation for |
|
1560 | Internally this triggers a call to %prun, see its documentation for | |
1561 | details on the options available specifically for profiling. |
|
1561 | details on the options available specifically for profiling. | |
1562 |
|
1562 | |||
1563 | There is one special usage for which the text above doesn't apply: |
|
1563 | There is one special usage for which the text above doesn't apply: | |
1564 | if the filename ends with .ipy, the file is run as ipython script, |
|
1564 | if the filename ends with .ipy, the file is run as ipython script, | |
1565 | just as if the commands were written on IPython prompt. |
|
1565 | just as if the commands were written on IPython prompt. | |
1566 | """ |
|
1566 | """ | |
1567 |
|
1567 | |||
1568 | # get arguments and set sys.argv for program to be run. |
|
1568 | # get arguments and set sys.argv for program to be run. | |
1569 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1569 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1570 | mode='list',list_all=1) |
|
1570 | mode='list',list_all=1) | |
1571 |
|
1571 | |||
1572 | try: |
|
1572 | try: | |
1573 | filename = file_finder(arg_lst[0]) |
|
1573 | filename = file_finder(arg_lst[0]) | |
1574 | except IndexError: |
|
1574 | except IndexError: | |
1575 | warn('you must provide at least a filename.') |
|
1575 | warn('you must provide at least a filename.') | |
1576 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1576 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1577 | return |
|
1577 | return | |
1578 | except IOError,msg: |
|
1578 | except IOError,msg: | |
1579 | error(msg) |
|
1579 | error(msg) | |
1580 | return |
|
1580 | return | |
1581 |
|
1581 | |||
1582 | if filename.lower().endswith('.ipy'): |
|
1582 | if filename.lower().endswith('.ipy'): | |
1583 | self.shell.safe_execfile_ipy(filename) |
|
1583 | self.shell.safe_execfile_ipy(filename) | |
1584 | return |
|
1584 | return | |
1585 |
|
1585 | |||
1586 | # Control the response to exit() calls made by the script being run |
|
1586 | # Control the response to exit() calls made by the script being run | |
1587 | exit_ignore = opts.has_key('e') |
|
1587 | exit_ignore = opts.has_key('e') | |
1588 |
|
1588 | |||
1589 | # Make sure that the running script gets a proper sys.argv as if it |
|
1589 | # Make sure that the running script gets a proper sys.argv as if it | |
1590 | # were run from a system shell. |
|
1590 | # were run from a system shell. | |
1591 | save_argv = sys.argv # save it for later restoring |
|
1591 | save_argv = sys.argv # save it for later restoring | |
1592 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1592 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1593 |
|
1593 | |||
1594 | if opts.has_key('i'): |
|
1594 | if opts.has_key('i'): | |
1595 | # Run in user's interactive namespace |
|
1595 | # Run in user's interactive namespace | |
1596 | prog_ns = self.shell.user_ns |
|
1596 | prog_ns = self.shell.user_ns | |
1597 | __name__save = self.shell.user_ns['__name__'] |
|
1597 | __name__save = self.shell.user_ns['__name__'] | |
1598 | prog_ns['__name__'] = '__main__' |
|
1598 | prog_ns['__name__'] = '__main__' | |
1599 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1599 | main_mod = self.shell.new_main_mod(prog_ns) | |
1600 | else: |
|
1600 | else: | |
1601 | # Run in a fresh, empty namespace |
|
1601 | # Run in a fresh, empty namespace | |
1602 | if opts.has_key('n'): |
|
1602 | if opts.has_key('n'): | |
1603 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1603 | name = os.path.splitext(os.path.basename(filename))[0] | |
1604 | else: |
|
1604 | else: | |
1605 | name = '__main__' |
|
1605 | name = '__main__' | |
1606 |
|
1606 | |||
1607 | main_mod = self.shell.new_main_mod() |
|
1607 | main_mod = self.shell.new_main_mod() | |
1608 | prog_ns = main_mod.__dict__ |
|
1608 | prog_ns = main_mod.__dict__ | |
1609 | prog_ns['__name__'] = name |
|
1609 | prog_ns['__name__'] = name | |
1610 |
|
1610 | |||
1611 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1611 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1612 | # set the __file__ global in the script's namespace |
|
1612 | # set the __file__ global in the script's namespace | |
1613 | prog_ns['__file__'] = filename |
|
1613 | prog_ns['__file__'] = filename | |
1614 |
|
1614 | |||
1615 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1615 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1616 | # that, if we overwrite __main__, we replace it at the end |
|
1616 | # that, if we overwrite __main__, we replace it at the end | |
1617 | main_mod_name = prog_ns['__name__'] |
|
1617 | main_mod_name = prog_ns['__name__'] | |
1618 |
|
1618 | |||
1619 | if main_mod_name == '__main__': |
|
1619 | if main_mod_name == '__main__': | |
1620 | restore_main = sys.modules['__main__'] |
|
1620 | restore_main = sys.modules['__main__'] | |
1621 | else: |
|
1621 | else: | |
1622 | restore_main = False |
|
1622 | restore_main = False | |
1623 |
|
1623 | |||
1624 | # This needs to be undone at the end to prevent holding references to |
|
1624 | # This needs to be undone at the end to prevent holding references to | |
1625 | # every single object ever created. |
|
1625 | # every single object ever created. | |
1626 | sys.modules[main_mod_name] = main_mod |
|
1626 | sys.modules[main_mod_name] = main_mod | |
1627 |
|
1627 | |||
1628 | stats = None |
|
1628 | stats = None | |
1629 | try: |
|
1629 | try: | |
1630 | self.shell.savehist() |
|
1630 | self.shell.savehist() | |
1631 |
|
1631 | |||
1632 | if opts.has_key('p'): |
|
1632 | if opts.has_key('p'): | |
1633 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1633 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1634 | else: |
|
1634 | else: | |
1635 | if opts.has_key('d'): |
|
1635 | if opts.has_key('d'): | |
1636 | deb = debugger.Pdb(self.shell.colors) |
|
1636 | deb = debugger.Pdb(self.shell.colors) | |
1637 | # reset Breakpoint state, which is moronically kept |
|
1637 | # reset Breakpoint state, which is moronically kept | |
1638 | # in a class |
|
1638 | # in a class | |
1639 | bdb.Breakpoint.next = 1 |
|
1639 | bdb.Breakpoint.next = 1 | |
1640 | bdb.Breakpoint.bplist = {} |
|
1640 | bdb.Breakpoint.bplist = {} | |
1641 | bdb.Breakpoint.bpbynumber = [None] |
|
1641 | bdb.Breakpoint.bpbynumber = [None] | |
1642 | # Set an initial breakpoint to stop execution |
|
1642 | # Set an initial breakpoint to stop execution | |
1643 | maxtries = 10 |
|
1643 | maxtries = 10 | |
1644 | bp = int(opts.get('b',[1])[0]) |
|
1644 | bp = int(opts.get('b',[1])[0]) | |
1645 | checkline = deb.checkline(filename,bp) |
|
1645 | checkline = deb.checkline(filename,bp) | |
1646 | if not checkline: |
|
1646 | if not checkline: | |
1647 | for bp in range(bp+1,bp+maxtries+1): |
|
1647 | for bp in range(bp+1,bp+maxtries+1): | |
1648 | if deb.checkline(filename,bp): |
|
1648 | if deb.checkline(filename,bp): | |
1649 | break |
|
1649 | break | |
1650 | else: |
|
1650 | else: | |
1651 | msg = ("\nI failed to find a valid line to set " |
|
1651 | msg = ("\nI failed to find a valid line to set " | |
1652 | "a breakpoint\n" |
|
1652 | "a breakpoint\n" | |
1653 | "after trying up to line: %s.\n" |
|
1653 | "after trying up to line: %s.\n" | |
1654 | "Please set a valid breakpoint manually " |
|
1654 | "Please set a valid breakpoint manually " | |
1655 | "with the -b option." % bp) |
|
1655 | "with the -b option." % bp) | |
1656 | error(msg) |
|
1656 | error(msg) | |
1657 | return |
|
1657 | return | |
1658 | # if we find a good linenumber, set the breakpoint |
|
1658 | # if we find a good linenumber, set the breakpoint | |
1659 | deb.do_break('%s:%s' % (filename,bp)) |
|
1659 | deb.do_break('%s:%s' % (filename,bp)) | |
1660 | # Start file run |
|
1660 | # Start file run | |
1661 | print "NOTE: Enter 'c' at the", |
|
1661 | print "NOTE: Enter 'c' at the", | |
1662 | print "%s prompt to start your script." % deb.prompt |
|
1662 | print "%s prompt to start your script." % deb.prompt | |
1663 | try: |
|
1663 | try: | |
1664 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1664 | deb.run('execfile("%s")' % filename,prog_ns) | |
1665 |
|
1665 | |||
1666 | except: |
|
1666 | except: | |
1667 | etype, value, tb = sys.exc_info() |
|
1667 | etype, value, tb = sys.exc_info() | |
1668 | # Skip three frames in the traceback: the %run one, |
|
1668 | # Skip three frames in the traceback: the %run one, | |
1669 | # one inside bdb.py, and the command-line typed by the |
|
1669 | # one inside bdb.py, and the command-line typed by the | |
1670 | # user (run by exec in pdb itself). |
|
1670 | # user (run by exec in pdb itself). | |
1671 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1671 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1672 | else: |
|
1672 | else: | |
1673 | if runner is None: |
|
1673 | if runner is None: | |
1674 | runner = self.shell.safe_execfile |
|
1674 | runner = self.shell.safe_execfile | |
1675 | if opts.has_key('t'): |
|
1675 | if opts.has_key('t'): | |
1676 | # timed execution |
|
1676 | # timed execution | |
1677 | try: |
|
1677 | try: | |
1678 | nruns = int(opts['N'][0]) |
|
1678 | nruns = int(opts['N'][0]) | |
1679 | if nruns < 1: |
|
1679 | if nruns < 1: | |
1680 | error('Number of runs must be >=1') |
|
1680 | error('Number of runs must be >=1') | |
1681 | return |
|
1681 | return | |
1682 | except (KeyError): |
|
1682 | except (KeyError): | |
1683 | nruns = 1 |
|
1683 | nruns = 1 | |
1684 | if nruns == 1: |
|
1684 | if nruns == 1: | |
1685 | t0 = clock2() |
|
1685 | t0 = clock2() | |
1686 | runner(filename,prog_ns,prog_ns, |
|
1686 | runner(filename,prog_ns,prog_ns, | |
1687 | exit_ignore=exit_ignore) |
|
1687 | exit_ignore=exit_ignore) | |
1688 | t1 = clock2() |
|
1688 | t1 = clock2() | |
1689 | t_usr = t1[0]-t0[0] |
|
1689 | t_usr = t1[0]-t0[0] | |
1690 | t_sys = t1[1]-t0[1] |
|
1690 | t_sys = t1[1]-t0[1] | |
1691 | print "\nIPython CPU timings (estimated):" |
|
1691 | print "\nIPython CPU timings (estimated):" | |
1692 | print " User : %10s s." % t_usr |
|
1692 | print " User : %10s s." % t_usr | |
1693 | print " System: %10s s." % t_sys |
|
1693 | print " System: %10s s." % t_sys | |
1694 | else: |
|
1694 | else: | |
1695 | runs = range(nruns) |
|
1695 | runs = range(nruns) | |
1696 | t0 = clock2() |
|
1696 | t0 = clock2() | |
1697 | for nr in runs: |
|
1697 | for nr in runs: | |
1698 | runner(filename,prog_ns,prog_ns, |
|
1698 | runner(filename,prog_ns,prog_ns, | |
1699 | exit_ignore=exit_ignore) |
|
1699 | exit_ignore=exit_ignore) | |
1700 | t1 = clock2() |
|
1700 | t1 = clock2() | |
1701 | t_usr = t1[0]-t0[0] |
|
1701 | t_usr = t1[0]-t0[0] | |
1702 | t_sys = t1[1]-t0[1] |
|
1702 | t_sys = t1[1]-t0[1] | |
1703 | print "\nIPython CPU timings (estimated):" |
|
1703 | print "\nIPython CPU timings (estimated):" | |
1704 | print "Total runs performed:",nruns |
|
1704 | print "Total runs performed:",nruns | |
1705 | print " Times : %10s %10s" % ('Total','Per run') |
|
1705 | print " Times : %10s %10s" % ('Total','Per run') | |
1706 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1706 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1707 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1707 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1708 |
|
1708 | |||
1709 | else: |
|
1709 | else: | |
1710 | # regular execution |
|
1710 | # regular execution | |
1711 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1711 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1712 |
|
1712 | |||
1713 | if opts.has_key('i'): |
|
1713 | if opts.has_key('i'): | |
1714 | self.shell.user_ns['__name__'] = __name__save |
|
1714 | self.shell.user_ns['__name__'] = __name__save | |
1715 | else: |
|
1715 | else: | |
1716 | # The shell MUST hold a reference to prog_ns so after %run |
|
1716 | # The shell MUST hold a reference to prog_ns so after %run | |
1717 | # exits, the python deletion mechanism doesn't zero it out |
|
1717 | # exits, the python deletion mechanism doesn't zero it out | |
1718 | # (leaving dangling references). |
|
1718 | # (leaving dangling references). | |
1719 | self.shell.cache_main_mod(prog_ns,filename) |
|
1719 | self.shell.cache_main_mod(prog_ns,filename) | |
1720 | # update IPython interactive namespace |
|
1720 | # update IPython interactive namespace | |
1721 |
|
1721 | |||
1722 | # Some forms of read errors on the file may mean the |
|
1722 | # Some forms of read errors on the file may mean the | |
1723 | # __name__ key was never set; using pop we don't have to |
|
1723 | # __name__ key was never set; using pop we don't have to | |
1724 | # worry about a possible KeyError. |
|
1724 | # worry about a possible KeyError. | |
1725 | prog_ns.pop('__name__', None) |
|
1725 | prog_ns.pop('__name__', None) | |
1726 |
|
1726 | |||
1727 | self.shell.user_ns.update(prog_ns) |
|
1727 | self.shell.user_ns.update(prog_ns) | |
1728 | finally: |
|
1728 | finally: | |
1729 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1729 | # It's a bit of a mystery why, but __builtins__ can change from | |
1730 | # being a module to becoming a dict missing some key data after |
|
1730 | # being a module to becoming a dict missing some key data after | |
1731 | # %run. As best I can see, this is NOT something IPython is doing |
|
1731 | # %run. As best I can see, this is NOT something IPython is doing | |
1732 | # at all, and similar problems have been reported before: |
|
1732 | # at all, and similar problems have been reported before: | |
1733 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1733 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1734 | # Since this seems to be done by the interpreter itself, the best |
|
1734 | # Since this seems to be done by the interpreter itself, the best | |
1735 | # we can do is to at least restore __builtins__ for the user on |
|
1735 | # we can do is to at least restore __builtins__ for the user on | |
1736 | # exit. |
|
1736 | # exit. | |
1737 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1737 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1738 |
|
1738 | |||
1739 | # Ensure key global structures are restored |
|
1739 | # Ensure key global structures are restored | |
1740 | sys.argv = save_argv |
|
1740 | sys.argv = save_argv | |
1741 | if restore_main: |
|
1741 | if restore_main: | |
1742 | sys.modules['__main__'] = restore_main |
|
1742 | sys.modules['__main__'] = restore_main | |
1743 | else: |
|
1743 | else: | |
1744 | # Remove from sys.modules the reference to main_mod we'd |
|
1744 | # Remove from sys.modules the reference to main_mod we'd | |
1745 | # added. Otherwise it will trap references to objects |
|
1745 | # added. Otherwise it will trap references to objects | |
1746 | # contained therein. |
|
1746 | # contained therein. | |
1747 | del sys.modules[main_mod_name] |
|
1747 | del sys.modules[main_mod_name] | |
1748 |
|
1748 | |||
1749 | self.shell.reloadhist() |
|
1749 | self.shell.reloadhist() | |
1750 |
|
1750 | |||
1751 | return stats |
|
1751 | return stats | |
1752 |
|
1752 | |||
1753 | @testdec.skip_doctest |
|
1753 | @testdec.skip_doctest | |
1754 | def magic_timeit(self, parameter_s =''): |
|
1754 | def magic_timeit(self, parameter_s =''): | |
1755 | """Time execution of a Python statement or expression |
|
1755 | """Time execution of a Python statement or expression | |
1756 |
|
1756 | |||
1757 | Usage:\\ |
|
1757 | Usage:\\ | |
1758 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1758 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1759 |
|
1759 | |||
1760 | Time execution of a Python statement or expression using the timeit |
|
1760 | Time execution of a Python statement or expression using the timeit | |
1761 | module. |
|
1761 | module. | |
1762 |
|
1762 | |||
1763 | Options: |
|
1763 | Options: | |
1764 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1764 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1765 | is not given, a fitting value is chosen. |
|
1765 | is not given, a fitting value is chosen. | |
1766 |
|
1766 | |||
1767 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1767 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1768 | Default: 3 |
|
1768 | Default: 3 | |
1769 |
|
1769 | |||
1770 | -t: use time.time to measure the time, which is the default on Unix. |
|
1770 | -t: use time.time to measure the time, which is the default on Unix. | |
1771 | This function measures wall time. |
|
1771 | This function measures wall time. | |
1772 |
|
1772 | |||
1773 | -c: use time.clock to measure the time, which is the default on |
|
1773 | -c: use time.clock to measure the time, which is the default on | |
1774 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1774 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1775 | instead and returns the CPU user time. |
|
1775 | instead and returns the CPU user time. | |
1776 |
|
1776 | |||
1777 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1777 | -p<P>: use a precision of <P> digits to display the timing result. | |
1778 | Default: 3 |
|
1778 | Default: 3 | |
1779 |
|
1779 | |||
1780 |
|
1780 | |||
1781 | Examples: |
|
1781 | Examples: | |
1782 |
|
1782 | |||
1783 | In [1]: %timeit pass |
|
1783 | In [1]: %timeit pass | |
1784 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1784 | 10000000 loops, best of 3: 53.3 ns per loop | |
1785 |
|
1785 | |||
1786 | In [2]: u = None |
|
1786 | In [2]: u = None | |
1787 |
|
1787 | |||
1788 | In [3]: %timeit u is None |
|
1788 | In [3]: %timeit u is None | |
1789 | 10000000 loops, best of 3: 184 ns per loop |
|
1789 | 10000000 loops, best of 3: 184 ns per loop | |
1790 |
|
1790 | |||
1791 | In [4]: %timeit -r 4 u == None |
|
1791 | In [4]: %timeit -r 4 u == None | |
1792 | 1000000 loops, best of 4: 242 ns per loop |
|
1792 | 1000000 loops, best of 4: 242 ns per loop | |
1793 |
|
1793 | |||
1794 | In [5]: import time |
|
1794 | In [5]: import time | |
1795 |
|
1795 | |||
1796 | In [6]: %timeit -n1 time.sleep(2) |
|
1796 | In [6]: %timeit -n1 time.sleep(2) | |
1797 | 1 loops, best of 3: 2 s per loop |
|
1797 | 1 loops, best of 3: 2 s per loop | |
1798 |
|
1798 | |||
1799 |
|
1799 | |||
1800 | The times reported by %timeit will be slightly higher than those |
|
1800 | The times reported by %timeit will be slightly higher than those | |
1801 | reported by the timeit.py script when variables are accessed. This is |
|
1801 | reported by the timeit.py script when variables are accessed. This is | |
1802 | due to the fact that %timeit executes the statement in the namespace |
|
1802 | due to the fact that %timeit executes the statement in the namespace | |
1803 | of the shell, compared with timeit.py, which uses a single setup |
|
1803 | of the shell, compared with timeit.py, which uses a single setup | |
1804 | statement to import function or create variables. Generally, the bias |
|
1804 | statement to import function or create variables. Generally, the bias | |
1805 | does not matter as long as results from timeit.py are not mixed with |
|
1805 | does not matter as long as results from timeit.py are not mixed with | |
1806 | those from %timeit.""" |
|
1806 | those from %timeit.""" | |
1807 |
|
1807 | |||
1808 | import timeit |
|
1808 | import timeit | |
1809 | import math |
|
1809 | import math | |
1810 |
|
1810 | |||
1811 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1811 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1812 | # certain terminals. Until we figure out a robust way of |
|
1812 | # certain terminals. Until we figure out a robust way of | |
1813 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1813 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1814 | # microseconds. I am really NOT happy about disabling the proper |
|
1814 | # microseconds. I am really NOT happy about disabling the proper | |
1815 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1815 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1816 | # right solution for this is, I'm all ears... |
|
1816 | # right solution for this is, I'm all ears... | |
1817 | # |
|
1817 | # | |
1818 | # Note: using |
|
1818 | # Note: using | |
1819 | # |
|
1819 | # | |
1820 | # s = u'\xb5' |
|
1820 | # s = u'\xb5' | |
1821 | # s.encode(sys.getdefaultencoding()) |
|
1821 | # s.encode(sys.getdefaultencoding()) | |
1822 | # |
|
1822 | # | |
1823 | # is not sufficient, as I've seen terminals where that fails but |
|
1823 | # is not sufficient, as I've seen terminals where that fails but | |
1824 | # print s |
|
1824 | # print s | |
1825 | # |
|
1825 | # | |
1826 | # succeeds |
|
1826 | # succeeds | |
1827 | # |
|
1827 | # | |
1828 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1828 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1829 |
|
1829 | |||
1830 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1830 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1831 | units = [u"s", u"ms",u'us',"ns"] |
|
1831 | units = [u"s", u"ms",u'us',"ns"] | |
1832 |
|
1832 | |||
1833 | scaling = [1, 1e3, 1e6, 1e9] |
|
1833 | scaling = [1, 1e3, 1e6, 1e9] | |
1834 |
|
1834 | |||
1835 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1835 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1836 | posix=False) |
|
1836 | posix=False) | |
1837 | if stmt == "": |
|
1837 | if stmt == "": | |
1838 | return |
|
1838 | return | |
1839 | timefunc = timeit.default_timer |
|
1839 | timefunc = timeit.default_timer | |
1840 | number = int(getattr(opts, "n", 0)) |
|
1840 | number = int(getattr(opts, "n", 0)) | |
1841 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1841 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1842 | precision = int(getattr(opts, "p", 3)) |
|
1842 | precision = int(getattr(opts, "p", 3)) | |
1843 | if hasattr(opts, "t"): |
|
1843 | if hasattr(opts, "t"): | |
1844 | timefunc = time.time |
|
1844 | timefunc = time.time | |
1845 | if hasattr(opts, "c"): |
|
1845 | if hasattr(opts, "c"): | |
1846 | timefunc = clock |
|
1846 | timefunc = clock | |
1847 |
|
1847 | |||
1848 | timer = timeit.Timer(timer=timefunc) |
|
1848 | timer = timeit.Timer(timer=timefunc) | |
1849 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1849 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1850 | # but is there a better way to achieve that the code stmt has access |
|
1850 | # but is there a better way to achieve that the code stmt has access | |
1851 | # to the shell namespace? |
|
1851 | # to the shell namespace? | |
1852 |
|
1852 | |||
1853 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1853 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1854 | 'setup': "pass"} |
|
1854 | 'setup': "pass"} | |
1855 | # Track compilation time so it can be reported if too long |
|
1855 | # Track compilation time so it can be reported if too long | |
1856 | # Minimum time above which compilation time will be reported |
|
1856 | # Minimum time above which compilation time will be reported | |
1857 | tc_min = 0.1 |
|
1857 | tc_min = 0.1 | |
1858 |
|
1858 | |||
1859 | t0 = clock() |
|
1859 | t0 = clock() | |
1860 | code = compile(src, "<magic-timeit>", "exec") |
|
1860 | code = compile(src, "<magic-timeit>", "exec") | |
1861 | tc = clock()-t0 |
|
1861 | tc = clock()-t0 | |
1862 |
|
1862 | |||
1863 | ns = {} |
|
1863 | ns = {} | |
1864 | exec code in self.shell.user_ns, ns |
|
1864 | exec code in self.shell.user_ns, ns | |
1865 | timer.inner = ns["inner"] |
|
1865 | timer.inner = ns["inner"] | |
1866 |
|
1866 | |||
1867 | if number == 0: |
|
1867 | if number == 0: | |
1868 | # determine number so that 0.2 <= total time < 2.0 |
|
1868 | # determine number so that 0.2 <= total time < 2.0 | |
1869 | number = 1 |
|
1869 | number = 1 | |
1870 | for i in range(1, 10): |
|
1870 | for i in range(1, 10): | |
1871 | if timer.timeit(number) >= 0.2: |
|
1871 | if timer.timeit(number) >= 0.2: | |
1872 | break |
|
1872 | break | |
1873 | number *= 10 |
|
1873 | number *= 10 | |
1874 |
|
1874 | |||
1875 | best = min(timer.repeat(repeat, number)) / number |
|
1875 | best = min(timer.repeat(repeat, number)) / number | |
1876 |
|
1876 | |||
1877 | if best > 0.0: |
|
1877 | if best > 0.0: | |
1878 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1878 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1879 | else: |
|
1879 | else: | |
1880 | order = 3 |
|
1880 | order = 3 | |
1881 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1881 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1882 | precision, |
|
1882 | precision, | |
1883 | best * scaling[order], |
|
1883 | best * scaling[order], | |
1884 | units[order]) |
|
1884 | units[order]) | |
1885 | if tc > tc_min: |
|
1885 | if tc > tc_min: | |
1886 | print "Compiler time: %.2f s" % tc |
|
1886 | print "Compiler time: %.2f s" % tc | |
1887 |
|
1887 | |||
1888 | @testdec.skip_doctest |
|
1888 | @testdec.skip_doctest | |
1889 | def magic_time(self,parameter_s = ''): |
|
1889 | def magic_time(self,parameter_s = ''): | |
1890 | """Time execution of a Python statement or expression. |
|
1890 | """Time execution of a Python statement or expression. | |
1891 |
|
1891 | |||
1892 | The CPU and wall clock times are printed, and the value of the |
|
1892 | The CPU and wall clock times are printed, and the value of the | |
1893 | expression (if any) is returned. Note that under Win32, system time |
|
1893 | expression (if any) is returned. Note that under Win32, system time | |
1894 | is always reported as 0, since it can not be measured. |
|
1894 | is always reported as 0, since it can not be measured. | |
1895 |
|
1895 | |||
1896 | This function provides very basic timing functionality. In Python |
|
1896 | This function provides very basic timing functionality. In Python | |
1897 | 2.3, the timeit module offers more control and sophistication, so this |
|
1897 | 2.3, the timeit module offers more control and sophistication, so this | |
1898 | could be rewritten to use it (patches welcome). |
|
1898 | could be rewritten to use it (patches welcome). | |
1899 |
|
1899 | |||
1900 | Some examples: |
|
1900 | Some examples: | |
1901 |
|
1901 | |||
1902 | In [1]: time 2**128 |
|
1902 | In [1]: time 2**128 | |
1903 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1903 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1904 | Wall time: 0.00 |
|
1904 | Wall time: 0.00 | |
1905 | Out[1]: 340282366920938463463374607431768211456L |
|
1905 | Out[1]: 340282366920938463463374607431768211456L | |
1906 |
|
1906 | |||
1907 | In [2]: n = 1000000 |
|
1907 | In [2]: n = 1000000 | |
1908 |
|
1908 | |||
1909 | In [3]: time sum(range(n)) |
|
1909 | In [3]: time sum(range(n)) | |
1910 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1910 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1911 | Wall time: 1.37 |
|
1911 | Wall time: 1.37 | |
1912 | Out[3]: 499999500000L |
|
1912 | Out[3]: 499999500000L | |
1913 |
|
1913 | |||
1914 | In [4]: time print 'hello world' |
|
1914 | In [4]: time print 'hello world' | |
1915 | hello world |
|
1915 | hello world | |
1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1917 | Wall time: 0.00 |
|
1917 | Wall time: 0.00 | |
1918 |
|
1918 | |||
1919 | Note that the time needed by Python to compile the given expression |
|
1919 | Note that the time needed by Python to compile the given expression | |
1920 | will be reported if it is more than 0.1s. In this example, the |
|
1920 | will be reported if it is more than 0.1s. In this example, the | |
1921 | actual exponentiation is done by Python at compilation time, so while |
|
1921 | actual exponentiation is done by Python at compilation time, so while | |
1922 | the expression can take a noticeable amount of time to compute, that |
|
1922 | the expression can take a noticeable amount of time to compute, that | |
1923 | time is purely due to the compilation: |
|
1923 | time is purely due to the compilation: | |
1924 |
|
1924 | |||
1925 | In [5]: time 3**9999; |
|
1925 | In [5]: time 3**9999; | |
1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1927 | Wall time: 0.00 s |
|
1927 | Wall time: 0.00 s | |
1928 |
|
1928 | |||
1929 | In [6]: time 3**999999; |
|
1929 | In [6]: time 3**999999; | |
1930 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1930 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1931 | Wall time: 0.00 s |
|
1931 | Wall time: 0.00 s | |
1932 | Compiler : 0.78 s |
|
1932 | Compiler : 0.78 s | |
1933 | """ |
|
1933 | """ | |
1934 |
|
1934 | |||
1935 | # fail immediately if the given expression can't be compiled |
|
1935 | # fail immediately if the given expression can't be compiled | |
1936 |
|
1936 | |||
1937 | expr = self.shell.prefilter(parameter_s,False) |
|
1937 | expr = self.shell.prefilter(parameter_s,False) | |
1938 |
|
1938 | |||
1939 | # Minimum time above which compilation time will be reported |
|
1939 | # Minimum time above which compilation time will be reported | |
1940 | tc_min = 0.1 |
|
1940 | tc_min = 0.1 | |
1941 |
|
1941 | |||
1942 | try: |
|
1942 | try: | |
1943 | mode = 'eval' |
|
1943 | mode = 'eval' | |
1944 | t0 = clock() |
|
1944 | t0 = clock() | |
1945 | code = compile(expr,'<timed eval>',mode) |
|
1945 | code = compile(expr,'<timed eval>',mode) | |
1946 | tc = clock()-t0 |
|
1946 | tc = clock()-t0 | |
1947 | except SyntaxError: |
|
1947 | except SyntaxError: | |
1948 | mode = 'exec' |
|
1948 | mode = 'exec' | |
1949 | t0 = clock() |
|
1949 | t0 = clock() | |
1950 | code = compile(expr,'<timed exec>',mode) |
|
1950 | code = compile(expr,'<timed exec>',mode) | |
1951 | tc = clock()-t0 |
|
1951 | tc = clock()-t0 | |
1952 | # skew measurement as little as possible |
|
1952 | # skew measurement as little as possible | |
1953 | glob = self.shell.user_ns |
|
1953 | glob = self.shell.user_ns | |
1954 | clk = clock2 |
|
1954 | clk = clock2 | |
1955 | wtime = time.time |
|
1955 | wtime = time.time | |
1956 | # time execution |
|
1956 | # time execution | |
1957 | wall_st = wtime() |
|
1957 | wall_st = wtime() | |
1958 | if mode=='eval': |
|
1958 | if mode=='eval': | |
1959 | st = clk() |
|
1959 | st = clk() | |
1960 | out = eval(code,glob) |
|
1960 | out = eval(code,glob) | |
1961 | end = clk() |
|
1961 | end = clk() | |
1962 | else: |
|
1962 | else: | |
1963 | st = clk() |
|
1963 | st = clk() | |
1964 | exec code in glob |
|
1964 | exec code in glob | |
1965 | end = clk() |
|
1965 | end = clk() | |
1966 | out = None |
|
1966 | out = None | |
1967 | wall_end = wtime() |
|
1967 | wall_end = wtime() | |
1968 | # Compute actual times and report |
|
1968 | # Compute actual times and report | |
1969 | wall_time = wall_end-wall_st |
|
1969 | wall_time = wall_end-wall_st | |
1970 | cpu_user = end[0]-st[0] |
|
1970 | cpu_user = end[0]-st[0] | |
1971 | cpu_sys = end[1]-st[1] |
|
1971 | cpu_sys = end[1]-st[1] | |
1972 | cpu_tot = cpu_user+cpu_sys |
|
1972 | cpu_tot = cpu_user+cpu_sys | |
1973 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1973 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1974 | (cpu_user,cpu_sys,cpu_tot) |
|
1974 | (cpu_user,cpu_sys,cpu_tot) | |
1975 | print "Wall time: %.2f s" % wall_time |
|
1975 | print "Wall time: %.2f s" % wall_time | |
1976 | if tc > tc_min: |
|
1976 | if tc > tc_min: | |
1977 | print "Compiler : %.2f s" % tc |
|
1977 | print "Compiler : %.2f s" % tc | |
1978 | return out |
|
1978 | return out | |
1979 |
|
1979 | |||
1980 | @testdec.skip_doctest |
|
1980 | @testdec.skip_doctest | |
1981 | def magic_macro(self,parameter_s = ''): |
|
1981 | def magic_macro(self,parameter_s = ''): | |
1982 | """Define a set of input lines as a macro for future re-execution. |
|
1982 | """Define a set of input lines as a macro for future re-execution. | |
1983 |
|
1983 | |||
1984 | Usage:\\ |
|
1984 | Usage:\\ | |
1985 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1985 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1986 |
|
1986 | |||
1987 | Options: |
|
1987 | Options: | |
1988 |
|
1988 | |||
1989 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1989 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1990 | so that magics are loaded in their transformed version to valid |
|
1990 | so that magics are loaded in their transformed version to valid | |
1991 | Python. If this option is given, the raw input as typed as the |
|
1991 | Python. If this option is given, the raw input as typed as the | |
1992 | command line is used instead. |
|
1992 | command line is used instead. | |
1993 |
|
1993 | |||
1994 | This will define a global variable called `name` which is a string |
|
1994 | This will define a global variable called `name` which is a string | |
1995 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1995 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1996 | above) from your input history into a single string. This variable |
|
1996 | above) from your input history into a single string. This variable | |
1997 | acts like an automatic function which re-executes those lines as if |
|
1997 | acts like an automatic function which re-executes those lines as if | |
1998 | you had typed them. You just type 'name' at the prompt and the code |
|
1998 | you had typed them. You just type 'name' at the prompt and the code | |
1999 | executes. |
|
1999 | executes. | |
2000 |
|
2000 | |||
2001 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
2001 | The notation for indicating number ranges is: n1-n2 means 'use line | |
2002 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
2002 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
2003 | using the lines numbered 5,6 and 7. |
|
2003 | using the lines numbered 5,6 and 7. | |
2004 |
|
2004 | |||
2005 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2005 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2006 | notation, where N:M means numbers N through M-1. |
|
2006 | notation, where N:M means numbers N through M-1. | |
2007 |
|
2007 | |||
2008 | For example, if your history contains (%hist prints it): |
|
2008 | For example, if your history contains (%hist prints it): | |
2009 |
|
2009 | |||
2010 | 44: x=1 |
|
2010 | 44: x=1 | |
2011 | 45: y=3 |
|
2011 | 45: y=3 | |
2012 | 46: z=x+y |
|
2012 | 46: z=x+y | |
2013 | 47: print x |
|
2013 | 47: print x | |
2014 | 48: a=5 |
|
2014 | 48: a=5 | |
2015 | 49: print 'x',x,'y',y |
|
2015 | 49: print 'x',x,'y',y | |
2016 |
|
2016 | |||
2017 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2017 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2018 | called my_macro with: |
|
2018 | called my_macro with: | |
2019 |
|
2019 | |||
2020 | In [55]: %macro my_macro 44-47 49 |
|
2020 | In [55]: %macro my_macro 44-47 49 | |
2021 |
|
2021 | |||
2022 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2022 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2023 | in one pass. |
|
2023 | in one pass. | |
2024 |
|
2024 | |||
2025 | You don't need to give the line-numbers in order, and any given line |
|
2025 | You don't need to give the line-numbers in order, and any given line | |
2026 | number can appear multiple times. You can assemble macros with any |
|
2026 | number can appear multiple times. You can assemble macros with any | |
2027 | lines from your input history in any order. |
|
2027 | lines from your input history in any order. | |
2028 |
|
2028 | |||
2029 | The macro is a simple object which holds its value in an attribute, |
|
2029 | The macro is a simple object which holds its value in an attribute, | |
2030 | but IPython's display system checks for macros and executes them as |
|
2030 | but IPython's display system checks for macros and executes them as | |
2031 | code instead of printing them when you type their name. |
|
2031 | code instead of printing them when you type their name. | |
2032 |
|
2032 | |||
2033 | You can view a macro's contents by explicitly printing it with: |
|
2033 | You can view a macro's contents by explicitly printing it with: | |
2034 |
|
2034 | |||
2035 | 'print macro_name'. |
|
2035 | 'print macro_name'. | |
2036 |
|
2036 | |||
2037 | For one-off cases which DON'T contain magic function calls in them you |
|
2037 | For one-off cases which DON'T contain magic function calls in them you | |
2038 | can obtain similar results by explicitly executing slices from your |
|
2038 | can obtain similar results by explicitly executing slices from your | |
2039 | input history with: |
|
2039 | input history with: | |
2040 |
|
2040 | |||
2041 | In [60]: exec In[44:48]+In[49]""" |
|
2041 | In [60]: exec In[44:48]+In[49]""" | |
2042 |
|
2042 | |||
2043 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2043 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2044 | if not args: |
|
2044 | if not args: | |
2045 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2045 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2046 | macs.sort() |
|
2046 | macs.sort() | |
2047 | return macs |
|
2047 | return macs | |
2048 | if len(args) == 1: |
|
2048 | if len(args) == 1: | |
2049 | raise UsageError( |
|
2049 | raise UsageError( | |
2050 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2050 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2051 | name,ranges = args[0], args[1:] |
|
2051 | name,ranges = args[0], args[1:] | |
2052 |
|
2052 | |||
2053 | #print 'rng',ranges # dbg |
|
2053 | #print 'rng',ranges # dbg | |
2054 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2054 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2055 | macro = Macro(lines) |
|
2055 | macro = Macro(lines) | |
2056 | self.shell.define_macro(name, macro) |
|
2056 | self.shell.define_macro(name, macro) | |
2057 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2057 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2058 | print 'Macro contents:' |
|
2058 | print 'Macro contents:' | |
2059 | print macro, |
|
2059 | print macro, | |
2060 |
|
2060 | |||
2061 | def magic_save(self,parameter_s = ''): |
|
2061 | def magic_save(self,parameter_s = ''): | |
2062 | """Save a set of lines to a given filename. |
|
2062 | """Save a set of lines to a given filename. | |
2063 |
|
2063 | |||
2064 | Usage:\\ |
|
2064 | Usage:\\ | |
2065 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2065 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2066 |
|
2066 | |||
2067 | Options: |
|
2067 | Options: | |
2068 |
|
2068 | |||
2069 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2069 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2070 | so that magics are loaded in their transformed version to valid |
|
2070 | so that magics are loaded in their transformed version to valid | |
2071 | Python. If this option is given, the raw input as typed as the |
|
2071 | Python. If this option is given, the raw input as typed as the | |
2072 | command line is used instead. |
|
2072 | command line is used instead. | |
2073 |
|
2073 | |||
2074 | This function uses the same syntax as %macro for line extraction, but |
|
2074 | This function uses the same syntax as %macro for line extraction, but | |
2075 | instead of creating a macro it saves the resulting string to the |
|
2075 | instead of creating a macro it saves the resulting string to the | |
2076 | filename you specify. |
|
2076 | filename you specify. | |
2077 |
|
2077 | |||
2078 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2078 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2079 | it asks for confirmation before overwriting existing files.""" |
|
2079 | it asks for confirmation before overwriting existing files.""" | |
2080 |
|
2080 | |||
2081 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2081 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2082 | fname,ranges = args[0], args[1:] |
|
2082 | fname,ranges = args[0], args[1:] | |
2083 | if not fname.endswith('.py'): |
|
2083 | if not fname.endswith('.py'): | |
2084 | fname += '.py' |
|
2084 | fname += '.py' | |
2085 | if os.path.isfile(fname): |
|
2085 | if os.path.isfile(fname): | |
2086 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2086 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2087 | if ans.lower() not in ['y','yes']: |
|
2087 | if ans.lower() not in ['y','yes']: | |
2088 | print 'Operation cancelled.' |
|
2088 | print 'Operation cancelled.' | |
2089 | return |
|
2089 | return | |
2090 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2090 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2091 | f = file(fname,'w') |
|
2091 | f = file(fname,'w') | |
2092 | f.write(cmds) |
|
2092 | f.write(cmds) | |
2093 | f.close() |
|
2093 | f.close() | |
2094 | print 'The following commands were written to file `%s`:' % fname |
|
2094 | print 'The following commands were written to file `%s`:' % fname | |
2095 | print cmds |
|
2095 | print cmds | |
2096 |
|
2096 | |||
2097 | def _edit_macro(self,mname,macro): |
|
2097 | def _edit_macro(self,mname,macro): | |
2098 | """open an editor with the macro data in a file""" |
|
2098 | """open an editor with the macro data in a file""" | |
2099 | filename = self.shell.mktempfile(macro.value) |
|
2099 | filename = self.shell.mktempfile(macro.value) | |
2100 | self.shell.hooks.editor(filename) |
|
2100 | self.shell.hooks.editor(filename) | |
2101 |
|
2101 | |||
2102 | # and make a new macro object, to replace the old one |
|
2102 | # and make a new macro object, to replace the old one | |
2103 | mfile = open(filename) |
|
2103 | mfile = open(filename) | |
2104 | mvalue = mfile.read() |
|
2104 | mvalue = mfile.read() | |
2105 | mfile.close() |
|
2105 | mfile.close() | |
2106 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2106 | self.shell.user_ns[mname] = Macro(mvalue) | |
2107 |
|
2107 | |||
2108 | def magic_ed(self,parameter_s=''): |
|
2108 | def magic_ed(self,parameter_s=''): | |
2109 | """Alias to %edit.""" |
|
2109 | """Alias to %edit.""" | |
2110 | return self.magic_edit(parameter_s) |
|
2110 | return self.magic_edit(parameter_s) | |
2111 |
|
2111 | |||
2112 | @testdec.skip_doctest |
|
2112 | @testdec.skip_doctest | |
2113 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2113 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2114 | """Bring up an editor and execute the resulting code. |
|
2114 | """Bring up an editor and execute the resulting code. | |
2115 |
|
2115 | |||
2116 | Usage: |
|
2116 | Usage: | |
2117 | %edit [options] [args] |
|
2117 | %edit [options] [args] | |
2118 |
|
2118 | |||
2119 | %edit runs IPython's editor hook. The default version of this hook is |
|
2119 | %edit runs IPython's editor hook. The default version of this hook is | |
2120 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2120 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2121 | environment variable $EDITOR. If this isn't found, it will default to |
|
2121 | environment variable $EDITOR. If this isn't found, it will default to | |
2122 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2122 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2123 | docstring for how to change the editor hook. |
|
2123 | docstring for how to change the editor hook. | |
2124 |
|
2124 | |||
2125 | You can also set the value of this editor via the command line option |
|
2125 | You can also set the value of this editor via the command line option | |
2126 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2126 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2127 | specifically for IPython an editor different from your typical default |
|
2127 | specifically for IPython an editor different from your typical default | |
2128 | (and for Windows users who typically don't set environment variables). |
|
2128 | (and for Windows users who typically don't set environment variables). | |
2129 |
|
2129 | |||
2130 | This command allows you to conveniently edit multi-line code right in |
|
2130 | This command allows you to conveniently edit multi-line code right in | |
2131 | your IPython session. |
|
2131 | your IPython session. | |
2132 |
|
2132 | |||
2133 | If called without arguments, %edit opens up an empty editor with a |
|
2133 | If called without arguments, %edit opens up an empty editor with a | |
2134 | temporary file and will execute the contents of this file when you |
|
2134 | temporary file and will execute the contents of this file when you | |
2135 | close it (don't forget to save it!). |
|
2135 | close it (don't forget to save it!). | |
2136 |
|
2136 | |||
2137 |
|
2137 | |||
2138 | Options: |
|
2138 | Options: | |
2139 |
|
2139 | |||
2140 | -n <number>: open the editor at a specified line number. By default, |
|
2140 | -n <number>: open the editor at a specified line number. By default, | |
2141 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2141 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2142 | you can configure this by providing your own modified hook if your |
|
2142 | you can configure this by providing your own modified hook if your | |
2143 | favorite editor supports line-number specifications with a different |
|
2143 | favorite editor supports line-number specifications with a different | |
2144 | syntax. |
|
2144 | syntax. | |
2145 |
|
2145 | |||
2146 | -p: this will call the editor with the same data as the previous time |
|
2146 | -p: this will call the editor with the same data as the previous time | |
2147 | it was used, regardless of how long ago (in your current session) it |
|
2147 | it was used, regardless of how long ago (in your current session) it | |
2148 | was. |
|
2148 | was. | |
2149 |
|
2149 | |||
2150 | -r: use 'raw' input. This option only applies to input taken from the |
|
2150 | -r: use 'raw' input. This option only applies to input taken from the | |
2151 | user's history. By default, the 'processed' history is used, so that |
|
2151 | user's history. By default, the 'processed' history is used, so that | |
2152 | magics are loaded in their transformed version to valid Python. If |
|
2152 | magics are loaded in their transformed version to valid Python. If | |
2153 | this option is given, the raw input as typed as the command line is |
|
2153 | this option is given, the raw input as typed as the command line is | |
2154 | used instead. When you exit the editor, it will be executed by |
|
2154 | used instead. When you exit the editor, it will be executed by | |
2155 | IPython's own processor. |
|
2155 | IPython's own processor. | |
2156 |
|
2156 | |||
2157 | -x: do not execute the edited code immediately upon exit. This is |
|
2157 | -x: do not execute the edited code immediately upon exit. This is | |
2158 | mainly useful if you are editing programs which need to be called with |
|
2158 | mainly useful if you are editing programs which need to be called with | |
2159 | command line arguments, which you can then do using %run. |
|
2159 | command line arguments, which you can then do using %run. | |
2160 |
|
2160 | |||
2161 |
|
2161 | |||
2162 | Arguments: |
|
2162 | Arguments: | |
2163 |
|
2163 | |||
2164 | If arguments are given, the following possibilites exist: |
|
2164 | If arguments are given, the following possibilites exist: | |
2165 |
|
2165 | |||
2166 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2166 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2167 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2167 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2168 | loaded into the editor. The syntax is the same of the %macro command. |
|
2168 | loaded into the editor. The syntax is the same of the %macro command. | |
2169 |
|
2169 | |||
2170 | - If the argument doesn't start with a number, it is evaluated as a |
|
2170 | - If the argument doesn't start with a number, it is evaluated as a | |
2171 | variable and its contents loaded into the editor. You can thus edit |
|
2171 | variable and its contents loaded into the editor. You can thus edit | |
2172 | any string which contains python code (including the result of |
|
2172 | any string which contains python code (including the result of | |
2173 | previous edits). |
|
2173 | previous edits). | |
2174 |
|
2174 | |||
2175 | - If the argument is the name of an object (other than a string), |
|
2175 | - If the argument is the name of an object (other than a string), | |
2176 | IPython will try to locate the file where it was defined and open the |
|
2176 | IPython will try to locate the file where it was defined and open the | |
2177 | editor at the point where it is defined. You can use `%edit function` |
|
2177 | editor at the point where it is defined. You can use `%edit function` | |
2178 | to load an editor exactly at the point where 'function' is defined, |
|
2178 | to load an editor exactly at the point where 'function' is defined, | |
2179 | edit it and have the file be executed automatically. |
|
2179 | edit it and have the file be executed automatically. | |
2180 |
|
2180 | |||
2181 | If the object is a macro (see %macro for details), this opens up your |
|
2181 | If the object is a macro (see %macro for details), this opens up your | |
2182 | specified editor with a temporary file containing the macro's data. |
|
2182 | specified editor with a temporary file containing the macro's data. | |
2183 | Upon exit, the macro is reloaded with the contents of the file. |
|
2183 | Upon exit, the macro is reloaded with the contents of the file. | |
2184 |
|
2184 | |||
2185 | Note: opening at an exact line is only supported under Unix, and some |
|
2185 | Note: opening at an exact line is only supported under Unix, and some | |
2186 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2186 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2187 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2187 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2188 | (X)Emacs, vi, jed, pico and joe all do. |
|
2188 | (X)Emacs, vi, jed, pico and joe all do. | |
2189 |
|
2189 | |||
2190 | - If the argument is not found as a variable, IPython will look for a |
|
2190 | - If the argument is not found as a variable, IPython will look for a | |
2191 | file with that name (adding .py if necessary) and load it into the |
|
2191 | file with that name (adding .py if necessary) and load it into the | |
2192 | editor. It will execute its contents with execfile() when you exit, |
|
2192 | editor. It will execute its contents with execfile() when you exit, | |
2193 | loading any code in the file into your interactive namespace. |
|
2193 | loading any code in the file into your interactive namespace. | |
2194 |
|
2194 | |||
2195 | After executing your code, %edit will return as output the code you |
|
2195 | After executing your code, %edit will return as output the code you | |
2196 | typed in the editor (except when it was an existing file). This way |
|
2196 | typed in the editor (except when it was an existing file). This way | |
2197 | you can reload the code in further invocations of %edit as a variable, |
|
2197 | you can reload the code in further invocations of %edit as a variable, | |
2198 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2198 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2199 | the output. |
|
2199 | the output. | |
2200 |
|
2200 | |||
2201 | Note that %edit is also available through the alias %ed. |
|
2201 | Note that %edit is also available through the alias %ed. | |
2202 |
|
2202 | |||
2203 | This is an example of creating a simple function inside the editor and |
|
2203 | This is an example of creating a simple function inside the editor and | |
2204 | then modifying it. First, start up the editor: |
|
2204 | then modifying it. First, start up the editor: | |
2205 |
|
2205 | |||
2206 | In [1]: ed |
|
2206 | In [1]: ed | |
2207 | Editing... done. Executing edited code... |
|
2207 | Editing... done. Executing edited code... | |
2208 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2208 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2209 |
|
2209 | |||
2210 | We can then call the function foo(): |
|
2210 | We can then call the function foo(): | |
2211 |
|
2211 | |||
2212 | In [2]: foo() |
|
2212 | In [2]: foo() | |
2213 | foo() was defined in an editing session |
|
2213 | foo() was defined in an editing session | |
2214 |
|
2214 | |||
2215 | Now we edit foo. IPython automatically loads the editor with the |
|
2215 | Now we edit foo. IPython automatically loads the editor with the | |
2216 | (temporary) file where foo() was previously defined: |
|
2216 | (temporary) file where foo() was previously defined: | |
2217 |
|
2217 | |||
2218 | In [3]: ed foo |
|
2218 | In [3]: ed foo | |
2219 | Editing... done. Executing edited code... |
|
2219 | Editing... done. Executing edited code... | |
2220 |
|
2220 | |||
2221 | And if we call foo() again we get the modified version: |
|
2221 | And if we call foo() again we get the modified version: | |
2222 |
|
2222 | |||
2223 | In [4]: foo() |
|
2223 | In [4]: foo() | |
2224 | foo() has now been changed! |
|
2224 | foo() has now been changed! | |
2225 |
|
2225 | |||
2226 | Here is an example of how to edit a code snippet successive |
|
2226 | Here is an example of how to edit a code snippet successive | |
2227 | times. First we call the editor: |
|
2227 | times. First we call the editor: | |
2228 |
|
2228 | |||
2229 | In [5]: ed |
|
2229 | In [5]: ed | |
2230 | Editing... done. Executing edited code... |
|
2230 | Editing... done. Executing edited code... | |
2231 | hello |
|
2231 | hello | |
2232 | Out[5]: "print 'hello'n" |
|
2232 | Out[5]: "print 'hello'n" | |
2233 |
|
2233 | |||
2234 | Now we call it again with the previous output (stored in _): |
|
2234 | Now we call it again with the previous output (stored in _): | |
2235 |
|
2235 | |||
2236 | In [6]: ed _ |
|
2236 | In [6]: ed _ | |
2237 | Editing... done. Executing edited code... |
|
2237 | Editing... done. Executing edited code... | |
2238 | hello world |
|
2238 | hello world | |
2239 | Out[6]: "print 'hello world'n" |
|
2239 | Out[6]: "print 'hello world'n" | |
2240 |
|
2240 | |||
2241 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2241 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2242 |
|
2242 | |||
2243 | In [7]: ed _8 |
|
2243 | In [7]: ed _8 | |
2244 | Editing... done. Executing edited code... |
|
2244 | Editing... done. Executing edited code... | |
2245 | hello again |
|
2245 | hello again | |
2246 | Out[7]: "print 'hello again'n" |
|
2246 | Out[7]: "print 'hello again'n" | |
2247 |
|
2247 | |||
2248 |
|
2248 | |||
2249 | Changing the default editor hook: |
|
2249 | Changing the default editor hook: | |
2250 |
|
2250 | |||
2251 | If you wish to write your own editor hook, you can put it in a |
|
2251 | If you wish to write your own editor hook, you can put it in a | |
2252 | configuration file which you load at startup time. The default hook |
|
2252 | configuration file which you load at startup time. The default hook | |
2253 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2253 | is defined in the IPython.core.hooks module, and you can use that as a | |
2254 | starting example for further modifications. That file also has |
|
2254 | starting example for further modifications. That file also has | |
2255 | general instructions on how to set a new hook for use once you've |
|
2255 | general instructions on how to set a new hook for use once you've | |
2256 | defined it.""" |
|
2256 | defined it.""" | |
2257 |
|
2257 | |||
2258 | # FIXME: This function has become a convoluted mess. It needs a |
|
2258 | # FIXME: This function has become a convoluted mess. It needs a | |
2259 | # ground-up rewrite with clean, simple logic. |
|
2259 | # ground-up rewrite with clean, simple logic. | |
2260 |
|
2260 | |||
2261 | def make_filename(arg): |
|
2261 | def make_filename(arg): | |
2262 | "Make a filename from the given args" |
|
2262 | "Make a filename from the given args" | |
2263 | try: |
|
2263 | try: | |
2264 | filename = get_py_filename(arg) |
|
2264 | filename = get_py_filename(arg) | |
2265 | except IOError: |
|
2265 | except IOError: | |
2266 | if args.endswith('.py'): |
|
2266 | if args.endswith('.py'): | |
2267 | filename = arg |
|
2267 | filename = arg | |
2268 | else: |
|
2268 | else: | |
2269 | filename = None |
|
2269 | filename = None | |
2270 | return filename |
|
2270 | return filename | |
2271 |
|
2271 | |||
2272 | # custom exceptions |
|
2272 | # custom exceptions | |
2273 | class DataIsObject(Exception): pass |
|
2273 | class DataIsObject(Exception): pass | |
2274 |
|
2274 | |||
2275 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2275 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2276 | # Set a few locals from the options for convenience: |
|
2276 | # Set a few locals from the options for convenience: | |
2277 | opts_p = opts.has_key('p') |
|
2277 | opts_p = opts.has_key('p') | |
2278 | opts_r = opts.has_key('r') |
|
2278 | opts_r = opts.has_key('r') | |
2279 |
|
2279 | |||
2280 | # Default line number value |
|
2280 | # Default line number value | |
2281 | lineno = opts.get('n',None) |
|
2281 | lineno = opts.get('n',None) | |
2282 |
|
2282 | |||
2283 | if opts_p: |
|
2283 | if opts_p: | |
2284 | args = '_%s' % last_call[0] |
|
2284 | args = '_%s' % last_call[0] | |
2285 | if not self.shell.user_ns.has_key(args): |
|
2285 | if not self.shell.user_ns.has_key(args): | |
2286 | args = last_call[1] |
|
2286 | args = last_call[1] | |
2287 |
|
2287 | |||
2288 | # use last_call to remember the state of the previous call, but don't |
|
2288 | # use last_call to remember the state of the previous call, but don't | |
2289 | # let it be clobbered by successive '-p' calls. |
|
2289 | # let it be clobbered by successive '-p' calls. | |
2290 | try: |
|
2290 | try: | |
2291 | last_call[0] = self.shell.outputcache.prompt_count |
|
2291 | last_call[0] = self.shell.outputcache.prompt_count | |
2292 | if not opts_p: |
|
2292 | if not opts_p: | |
2293 | last_call[1] = parameter_s |
|
2293 | last_call[1] = parameter_s | |
2294 | except: |
|
2294 | except: | |
2295 | pass |
|
2295 | pass | |
2296 |
|
2296 | |||
2297 | # by default this is done with temp files, except when the given |
|
2297 | # by default this is done with temp files, except when the given | |
2298 | # arg is a filename |
|
2298 | # arg is a filename | |
2299 | use_temp = 1 |
|
2299 | use_temp = 1 | |
2300 |
|
2300 | |||
2301 | if re.match(r'\d',args): |
|
2301 | if re.match(r'\d',args): | |
2302 | # Mode where user specifies ranges of lines, like in %macro. |
|
2302 | # Mode where user specifies ranges of lines, like in %macro. | |
2303 | # This means that you can't edit files whose names begin with |
|
2303 | # This means that you can't edit files whose names begin with | |
2304 | # numbers this way. Tough. |
|
2304 | # numbers this way. Tough. | |
2305 | ranges = args.split() |
|
2305 | ranges = args.split() | |
2306 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2306 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2307 | elif args.endswith('.py'): |
|
2307 | elif args.endswith('.py'): | |
2308 | filename = make_filename(args) |
|
2308 | filename = make_filename(args) | |
2309 | data = '' |
|
2309 | data = '' | |
2310 | use_temp = 0 |
|
2310 | use_temp = 0 | |
2311 | elif args: |
|
2311 | elif args: | |
2312 | try: |
|
2312 | try: | |
2313 | # Load the parameter given as a variable. If not a string, |
|
2313 | # Load the parameter given as a variable. If not a string, | |
2314 | # process it as an object instead (below) |
|
2314 | # process it as an object instead (below) | |
2315 |
|
2315 | |||
2316 | #print '*** args',args,'type',type(args) # dbg |
|
2316 | #print '*** args',args,'type',type(args) # dbg | |
2317 | data = eval(args,self.shell.user_ns) |
|
2317 | data = eval(args,self.shell.user_ns) | |
2318 | if not type(data) in StringTypes: |
|
2318 | if not type(data) in StringTypes: | |
2319 | raise DataIsObject |
|
2319 | raise DataIsObject | |
2320 |
|
2320 | |||
2321 | except (NameError,SyntaxError): |
|
2321 | except (NameError,SyntaxError): | |
2322 | # given argument is not a variable, try as a filename |
|
2322 | # given argument is not a variable, try as a filename | |
2323 | filename = make_filename(args) |
|
2323 | filename = make_filename(args) | |
2324 | if filename is None: |
|
2324 | if filename is None: | |
2325 | warn("Argument given (%s) can't be found as a variable " |
|
2325 | warn("Argument given (%s) can't be found as a variable " | |
2326 | "or as a filename." % args) |
|
2326 | "or as a filename." % args) | |
2327 | return |
|
2327 | return | |
2328 |
|
2328 | |||
2329 | data = '' |
|
2329 | data = '' | |
2330 | use_temp = 0 |
|
2330 | use_temp = 0 | |
2331 | except DataIsObject: |
|
2331 | except DataIsObject: | |
2332 |
|
2332 | |||
2333 | # macros have a special edit function |
|
2333 | # macros have a special edit function | |
2334 | if isinstance(data,Macro): |
|
2334 | if isinstance(data,Macro): | |
2335 | self._edit_macro(args,data) |
|
2335 | self._edit_macro(args,data) | |
2336 | return |
|
2336 | return | |
2337 |
|
2337 | |||
2338 | # For objects, try to edit the file where they are defined |
|
2338 | # For objects, try to edit the file where they are defined | |
2339 | try: |
|
2339 | try: | |
2340 | filename = inspect.getabsfile(data) |
|
2340 | filename = inspect.getabsfile(data) | |
2341 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2341 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2342 | # class created by %edit? Try to find source |
|
2342 | # class created by %edit? Try to find source | |
2343 | # by looking for method definitions instead, the |
|
2343 | # by looking for method definitions instead, the | |
2344 | # __module__ in those classes is FakeModule. |
|
2344 | # __module__ in those classes is FakeModule. | |
2345 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2345 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2346 | for attr in attrs: |
|
2346 | for attr in attrs: | |
2347 | if not inspect.ismethod(attr): |
|
2347 | if not inspect.ismethod(attr): | |
2348 | continue |
|
2348 | continue | |
2349 | filename = inspect.getabsfile(attr) |
|
2349 | filename = inspect.getabsfile(attr) | |
2350 | if filename and 'fakemodule' not in filename.lower(): |
|
2350 | if filename and 'fakemodule' not in filename.lower(): | |
2351 | # change the attribute to be the edit target instead |
|
2351 | # change the attribute to be the edit target instead | |
2352 | data = attr |
|
2352 | data = attr | |
2353 | break |
|
2353 | break | |
2354 |
|
2354 | |||
2355 | datafile = 1 |
|
2355 | datafile = 1 | |
2356 | except TypeError: |
|
2356 | except TypeError: | |
2357 | filename = make_filename(args) |
|
2357 | filename = make_filename(args) | |
2358 | datafile = 1 |
|
2358 | datafile = 1 | |
2359 | warn('Could not find file where `%s` is defined.\n' |
|
2359 | warn('Could not find file where `%s` is defined.\n' | |
2360 | 'Opening a file named `%s`' % (args,filename)) |
|
2360 | 'Opening a file named `%s`' % (args,filename)) | |
2361 | # Now, make sure we can actually read the source (if it was in |
|
2361 | # Now, make sure we can actually read the source (if it was in | |
2362 | # a temp file it's gone by now). |
|
2362 | # a temp file it's gone by now). | |
2363 | if datafile: |
|
2363 | if datafile: | |
2364 | try: |
|
2364 | try: | |
2365 | if lineno is None: |
|
2365 | if lineno is None: | |
2366 | lineno = inspect.getsourcelines(data)[1] |
|
2366 | lineno = inspect.getsourcelines(data)[1] | |
2367 | except IOError: |
|
2367 | except IOError: | |
2368 | filename = make_filename(args) |
|
2368 | filename = make_filename(args) | |
2369 | if filename is None: |
|
2369 | if filename is None: | |
2370 | warn('The file `%s` where `%s` was defined cannot ' |
|
2370 | warn('The file `%s` where `%s` was defined cannot ' | |
2371 | 'be read.' % (filename,data)) |
|
2371 | 'be read.' % (filename,data)) | |
2372 | return |
|
2372 | return | |
2373 | use_temp = 0 |
|
2373 | use_temp = 0 | |
2374 | else: |
|
2374 | else: | |
2375 | data = '' |
|
2375 | data = '' | |
2376 |
|
2376 | |||
2377 | if use_temp: |
|
2377 | if use_temp: | |
2378 | filename = self.shell.mktempfile(data) |
|
2378 | filename = self.shell.mktempfile(data) | |
2379 | print 'IPython will make a temporary file named:',filename |
|
2379 | print 'IPython will make a temporary file named:',filename | |
2380 |
|
2380 | |||
2381 | # do actual editing here |
|
2381 | # do actual editing here | |
2382 | print 'Editing...', |
|
2382 | print 'Editing...', | |
2383 | sys.stdout.flush() |
|
2383 | sys.stdout.flush() | |
2384 | try: |
|
2384 | try: | |
2385 | self.shell.hooks.editor(filename,lineno) |
|
2385 | self.shell.hooks.editor(filename,lineno) | |
2386 | except TryNext: |
|
2386 | except TryNext: | |
2387 | warn('Could not open editor') |
|
2387 | warn('Could not open editor') | |
2388 | return |
|
2388 | return | |
2389 |
|
2389 | |||
2390 | # XXX TODO: should this be generalized for all string vars? |
|
2390 | # XXX TODO: should this be generalized for all string vars? | |
2391 | # For now, this is special-cased to blocks created by cpaste |
|
2391 | # For now, this is special-cased to blocks created by cpaste | |
2392 | if args.strip() == 'pasted_block': |
|
2392 | if args.strip() == 'pasted_block': | |
2393 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2393 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2394 |
|
2394 | |||
2395 | if opts.has_key('x'): # -x prevents actual execution |
|
2395 | if opts.has_key('x'): # -x prevents actual execution | |
2396 |
|
2396 | |||
2397 | else: |
|
2397 | else: | |
2398 | print 'done. Executing edited code...' |
|
2398 | print 'done. Executing edited code...' | |
2399 | if opts_r: |
|
2399 | if opts_r: | |
2400 | self.shell.runlines(file_read(filename)) |
|
2400 | self.shell.runlines(file_read(filename)) | |
2401 | else: |
|
2401 | else: | |
2402 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2402 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2403 | self.shell.user_ns) |
|
2403 | self.shell.user_ns) | |
2404 |
|
2404 | |||
2405 |
|
2405 | |||
2406 | if use_temp: |
|
2406 | if use_temp: | |
2407 | try: |
|
2407 | try: | |
2408 | return open(filename).read() |
|
2408 | return open(filename).read() | |
2409 | except IOError,msg: |
|
2409 | except IOError,msg: | |
2410 | if msg.filename == filename: |
|
2410 | if msg.filename == filename: | |
2411 | warn('File not found. Did you forget to save?') |
|
2411 | warn('File not found. Did you forget to save?') | |
2412 | return |
|
2412 | return | |
2413 | else: |
|
2413 | else: | |
2414 | self.shell.showtraceback() |
|
2414 | self.shell.showtraceback() | |
2415 |
|
2415 | |||
2416 | def magic_xmode(self,parameter_s = ''): |
|
2416 | def magic_xmode(self,parameter_s = ''): | |
2417 | """Switch modes for the exception handlers. |
|
2417 | """Switch modes for the exception handlers. | |
2418 |
|
2418 | |||
2419 | Valid modes: Plain, Context and Verbose. |
|
2419 | Valid modes: Plain, Context and Verbose. | |
2420 |
|
2420 | |||
2421 | If called without arguments, acts as a toggle.""" |
|
2421 | If called without arguments, acts as a toggle.""" | |
2422 |
|
2422 | |||
2423 | def xmode_switch_err(name): |
|
2423 | def xmode_switch_err(name): | |
2424 | warn('Error changing %s exception modes.\n%s' % |
|
2424 | warn('Error changing %s exception modes.\n%s' % | |
2425 | (name,sys.exc_info()[1])) |
|
2425 | (name,sys.exc_info()[1])) | |
2426 |
|
2426 | |||
2427 | shell = self.shell |
|
2427 | shell = self.shell | |
2428 | new_mode = parameter_s.strip().capitalize() |
|
2428 | new_mode = parameter_s.strip().capitalize() | |
2429 | try: |
|
2429 | try: | |
2430 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2430 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2431 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2431 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2432 | except: |
|
2432 | except: | |
2433 | xmode_switch_err('user') |
|
2433 | xmode_switch_err('user') | |
2434 |
|
2434 | |||
2435 | # threaded shells use a special handler in sys.excepthook |
|
2435 | # threaded shells use a special handler in sys.excepthook | |
2436 | if shell.isthreaded: |
|
2436 | if shell.isthreaded: | |
2437 | try: |
|
2437 | try: | |
2438 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2438 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2439 | except: |
|
2439 | except: | |
2440 | xmode_switch_err('threaded') |
|
2440 | xmode_switch_err('threaded') | |
2441 |
|
2441 | |||
2442 | def magic_colors(self,parameter_s = ''): |
|
2442 | def magic_colors(self,parameter_s = ''): | |
2443 | """Switch color scheme for prompts, info system and exception handlers. |
|
2443 | """Switch color scheme for prompts, info system and exception handlers. | |
2444 |
|
2444 | |||
2445 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2445 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2446 |
|
2446 | |||
2447 | Color scheme names are not case-sensitive.""" |
|
2447 | Color scheme names are not case-sensitive.""" | |
2448 |
|
2448 | |||
2449 | def color_switch_err(name): |
|
2449 | def color_switch_err(name): | |
2450 | warn('Error changing %s color schemes.\n%s' % |
|
2450 | warn('Error changing %s color schemes.\n%s' % | |
2451 | (name,sys.exc_info()[1])) |
|
2451 | (name,sys.exc_info()[1])) | |
2452 |
|
2452 | |||
2453 |
|
2453 | |||
2454 | new_scheme = parameter_s.strip() |
|
2454 | new_scheme = parameter_s.strip() | |
2455 | if not new_scheme: |
|
2455 | if not new_scheme: | |
2456 | raise UsageError( |
|
2456 | raise UsageError( | |
2457 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2457 | "%colors: you must specify a color scheme. See '%colors?'") | |
2458 | return |
|
2458 | return | |
2459 | # local shortcut |
|
2459 | # local shortcut | |
2460 | shell = self.shell |
|
2460 | shell = self.shell | |
2461 |
|
2461 | |||
2462 | import IPython.utils.rlineimpl as readline |
|
2462 | import IPython.utils.rlineimpl as readline | |
2463 |
|
2463 | |||
2464 | if not readline.have_readline and sys.platform == "win32": |
|
2464 | if not readline.have_readline and sys.platform == "win32": | |
2465 | msg = """\ |
|
2465 | msg = """\ | |
2466 | Proper color support under MS Windows requires the pyreadline library. |
|
2466 | Proper color support under MS Windows requires the pyreadline library. | |
2467 | You can find it at: |
|
2467 | You can find it at: | |
2468 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2468 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2469 | Gary's readline needs the ctypes module, from: |
|
2469 | Gary's readline needs the ctypes module, from: | |
2470 | http://starship.python.net/crew/theller/ctypes |
|
2470 | http://starship.python.net/crew/theller/ctypes | |
2471 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2471 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2472 |
|
2472 | |||
2473 | Defaulting color scheme to 'NoColor'""" |
|
2473 | Defaulting color scheme to 'NoColor'""" | |
2474 | new_scheme = 'NoColor' |
|
2474 | new_scheme = 'NoColor' | |
2475 | warn(msg) |
|
2475 | warn(msg) | |
2476 |
|
2476 | |||
2477 | # readline option is 0 |
|
2477 | # readline option is 0 | |
2478 | if not shell.has_readline: |
|
2478 | if not shell.has_readline: | |
2479 | new_scheme = 'NoColor' |
|
2479 | new_scheme = 'NoColor' | |
2480 |
|
2480 | |||
2481 | # Set prompt colors |
|
2481 | # Set prompt colors | |
2482 | try: |
|
2482 | try: | |
2483 | shell.outputcache.set_colors(new_scheme) |
|
2483 | shell.outputcache.set_colors(new_scheme) | |
2484 | except: |
|
2484 | except: | |
2485 | color_switch_err('prompt') |
|
2485 | color_switch_err('prompt') | |
2486 | else: |
|
2486 | else: | |
2487 | shell.colors = \ |
|
2487 | shell.colors = \ | |
2488 | shell.outputcache.color_table.active_scheme_name |
|
2488 | shell.outputcache.color_table.active_scheme_name | |
2489 | # Set exception colors |
|
2489 | # Set exception colors | |
2490 | try: |
|
2490 | try: | |
2491 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2491 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2492 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2492 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2493 | except: |
|
2493 | except: | |
2494 | color_switch_err('exception') |
|
2494 | color_switch_err('exception') | |
2495 |
|
2495 | |||
2496 | # threaded shells use a verbose traceback in sys.excepthook |
|
2496 | # threaded shells use a verbose traceback in sys.excepthook | |
2497 | if shell.isthreaded: |
|
2497 | if shell.isthreaded: | |
2498 | try: |
|
2498 | try: | |
2499 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2499 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2500 | except: |
|
2500 | except: | |
2501 | color_switch_err('system exception handler') |
|
2501 | color_switch_err('system exception handler') | |
2502 |
|
2502 | |||
2503 | # Set info (for 'object?') colors |
|
2503 | # Set info (for 'object?') colors | |
2504 | if shell.color_info: |
|
2504 | if shell.color_info: | |
2505 | try: |
|
2505 | try: | |
2506 | shell.inspector.set_active_scheme(new_scheme) |
|
2506 | shell.inspector.set_active_scheme(new_scheme) | |
2507 | except: |
|
2507 | except: | |
2508 | color_switch_err('object inspector') |
|
2508 | color_switch_err('object inspector') | |
2509 | else: |
|
2509 | else: | |
2510 | shell.inspector.set_active_scheme('NoColor') |
|
2510 | shell.inspector.set_active_scheme('NoColor') | |
2511 |
|
2511 | |||
2512 | def magic_color_info(self,parameter_s = ''): |
|
2512 | def magic_color_info(self,parameter_s = ''): | |
2513 | """Toggle color_info. |
|
2513 | """Toggle color_info. | |
2514 |
|
2514 | |||
2515 | The color_info configuration parameter controls whether colors are |
|
2515 | The color_info configuration parameter controls whether colors are | |
2516 | used for displaying object details (by things like %psource, %pfile or |
|
2516 | used for displaying object details (by things like %psource, %pfile or | |
2517 | the '?' system). This function toggles this value with each call. |
|
2517 | the '?' system). This function toggles this value with each call. | |
2518 |
|
2518 | |||
2519 | Note that unless you have a fairly recent pager (less works better |
|
2519 | Note that unless you have a fairly recent pager (less works better | |
2520 | than more) in your system, using colored object information displays |
|
2520 | than more) in your system, using colored object information displays | |
2521 | will not work properly. Test it and see.""" |
|
2521 | will not work properly. Test it and see.""" | |
2522 |
|
2522 | |||
2523 | self.shell.color_info = not self.shell.color_info |
|
2523 | self.shell.color_info = not self.shell.color_info | |
2524 | self.magic_colors(self.shell.colors) |
|
2524 | self.magic_colors(self.shell.colors) | |
2525 | print 'Object introspection functions have now coloring:', |
|
2525 | print 'Object introspection functions have now coloring:', | |
2526 | print ['OFF','ON'][int(self.shell.color_info)] |
|
2526 | print ['OFF','ON'][int(self.shell.color_info)] | |
2527 |
|
2527 | |||
2528 | def magic_Pprint(self, parameter_s=''): |
|
2528 | def magic_Pprint(self, parameter_s=''): | |
2529 | """Toggle pretty printing on/off.""" |
|
2529 | """Toggle pretty printing on/off.""" | |
2530 |
|
2530 | |||
2531 | self.shell.pprint = 1 - self.shell.pprint |
|
2531 | self.shell.pprint = 1 - self.shell.pprint | |
2532 | print 'Pretty printing has been turned', \ |
|
2532 | print 'Pretty printing has been turned', \ | |
2533 | ['OFF','ON'][self.shell.pprint] |
|
2533 | ['OFF','ON'][self.shell.pprint] | |
2534 |
|
2534 | |||
2535 | def magic_Exit(self, parameter_s=''): |
|
2535 | def magic_Exit(self, parameter_s=''): | |
2536 | """Exit IPython without confirmation.""" |
|
2536 | """Exit IPython without confirmation.""" | |
2537 |
|
2537 | |||
2538 | self.shell.ask_exit() |
|
2538 | self.shell.ask_exit() | |
2539 |
|
2539 | |||
2540 | #...................................................................... |
|
2540 | #...................................................................... | |
2541 | # Functions to implement unix shell-type things |
|
2541 | # Functions to implement unix shell-type things | |
2542 |
|
2542 | |||
2543 | @testdec.skip_doctest |
|
2543 | @testdec.skip_doctest | |
2544 | def magic_alias(self, parameter_s = ''): |
|
2544 | def magic_alias(self, parameter_s = ''): | |
2545 | """Define an alias for a system command. |
|
2545 | """Define an alias for a system command. | |
2546 |
|
2546 | |||
2547 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2547 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2548 |
|
2548 | |||
2549 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2549 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2550 | params' (from your underlying operating system). |
|
2550 | params' (from your underlying operating system). | |
2551 |
|
2551 | |||
2552 | Aliases have lower precedence than magic functions and Python normal |
|
2552 | Aliases have lower precedence than magic functions and Python normal | |
2553 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2553 | variables, so if 'foo' is both a Python variable and an alias, the | |
2554 | alias can not be executed until 'del foo' removes the Python variable. |
|
2554 | alias can not be executed until 'del foo' removes the Python variable. | |
2555 |
|
2555 | |||
2556 | You can use the %l specifier in an alias definition to represent the |
|
2556 | You can use the %l specifier in an alias definition to represent the | |
2557 | whole line when the alias is called. For example: |
|
2557 | whole line when the alias is called. For example: | |
2558 |
|
2558 | |||
2559 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2559 | In [2]: alias all echo "Input in brackets: <%l>" | |
2560 | In [3]: all hello world |
|
2560 | In [3]: all hello world | |
2561 | Input in brackets: <hello world> |
|
2561 | Input in brackets: <hello world> | |
2562 |
|
2562 | |||
2563 | You can also define aliases with parameters using %s specifiers (one |
|
2563 | You can also define aliases with parameters using %s specifiers (one | |
2564 | per parameter): |
|
2564 | per parameter): | |
2565 |
|
2565 | |||
2566 | In [1]: alias parts echo first %s second %s |
|
2566 | In [1]: alias parts echo first %s second %s | |
2567 | In [2]: %parts A B |
|
2567 | In [2]: %parts A B | |
2568 | first A second B |
|
2568 | first A second B | |
2569 | In [3]: %parts A |
|
2569 | In [3]: %parts A | |
2570 | Incorrect number of arguments: 2 expected. |
|
2570 | Incorrect number of arguments: 2 expected. | |
2571 | parts is an alias to: 'echo first %s second %s' |
|
2571 | parts is an alias to: 'echo first %s second %s' | |
2572 |
|
2572 | |||
2573 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2573 | Note that %l and %s are mutually exclusive. You can only use one or | |
2574 | the other in your aliases. |
|
2574 | the other in your aliases. | |
2575 |
|
2575 | |||
2576 | Aliases expand Python variables just like system calls using ! or !! |
|
2576 | Aliases expand Python variables just like system calls using ! or !! | |
2577 | do: all expressions prefixed with '$' get expanded. For details of |
|
2577 | do: all expressions prefixed with '$' get expanded. For details of | |
2578 | the semantic rules, see PEP-215: |
|
2578 | the semantic rules, see PEP-215: | |
2579 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2579 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2580 | IPython for variable expansion. If you want to access a true shell |
|
2580 | IPython for variable expansion. If you want to access a true shell | |
2581 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2581 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2582 |
|
2582 | |||
2583 | In [6]: alias show echo |
|
2583 | In [6]: alias show echo | |
2584 | In [7]: PATH='A Python string' |
|
2584 | In [7]: PATH='A Python string' | |
2585 | In [8]: show $PATH |
|
2585 | In [8]: show $PATH | |
2586 | A Python string |
|
2586 | A Python string | |
2587 | In [9]: show $$PATH |
|
2587 | In [9]: show $$PATH | |
2588 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2588 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2589 |
|
2589 | |||
2590 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2590 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2591 | and %rehashx functions, which automatically create aliases for the |
|
2591 | and %rehashx functions, which automatically create aliases for the | |
2592 | contents of your $PATH. |
|
2592 | contents of your $PATH. | |
2593 |
|
2593 | |||
2594 | If called with no parameters, %alias prints the current alias table.""" |
|
2594 | If called with no parameters, %alias prints the current alias table.""" | |
2595 |
|
2595 | |||
2596 | par = parameter_s.strip() |
|
2596 | par = parameter_s.strip() | |
2597 | if not par: |
|
2597 | if not par: | |
2598 | stored = self.db.get('stored_aliases', {} ) |
|
2598 | stored = self.db.get('stored_aliases', {} ) | |
2599 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2599 | aliases = sorted(self.shell.alias_manager.aliases) | |
2600 | # for k, v in stored: |
|
2600 | # for k, v in stored: | |
2601 | # atab.append(k, v[0]) |
|
2601 | # atab.append(k, v[0]) | |
2602 |
|
2602 | |||
2603 | print "Total number of aliases:", len(aliases) |
|
2603 | print "Total number of aliases:", len(aliases) | |
2604 | return aliases |
|
2604 | return aliases | |
2605 |
|
2605 | |||
2606 | # Now try to define a new one |
|
2606 | # Now try to define a new one | |
2607 | try: |
|
2607 | try: | |
2608 | alias,cmd = par.split(None, 1) |
|
2608 | alias,cmd = par.split(None, 1) | |
2609 | except: |
|
2609 | except: | |
2610 | print oinspect.getdoc(self.magic_alias) |
|
2610 | print oinspect.getdoc(self.magic_alias) | |
2611 | else: |
|
2611 | else: | |
2612 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2612 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2613 | # end magic_alias |
|
2613 | # end magic_alias | |
2614 |
|
2614 | |||
2615 | def magic_unalias(self, parameter_s = ''): |
|
2615 | def magic_unalias(self, parameter_s = ''): | |
2616 | """Remove an alias""" |
|
2616 | """Remove an alias""" | |
2617 |
|
2617 | |||
2618 | aname = parameter_s.strip() |
|
2618 | aname = parameter_s.strip() | |
2619 | self.shell.alias_manager.undefine_alias(aname) |
|
2619 | self.shell.alias_manager.undefine_alias(aname) | |
2620 | stored = self.db.get('stored_aliases', {} ) |
|
2620 | stored = self.db.get('stored_aliases', {} ) | |
2621 | if aname in stored: |
|
2621 | if aname in stored: | |
2622 | print "Removing %stored alias",aname |
|
2622 | print "Removing %stored alias",aname | |
2623 | del stored[aname] |
|
2623 | del stored[aname] | |
2624 | self.db['stored_aliases'] = stored |
|
2624 | self.db['stored_aliases'] = stored | |
2625 |
|
2625 | |||
2626 |
|
2626 | |||
2627 | def magic_rehashx(self, parameter_s = ''): |
|
2627 | def magic_rehashx(self, parameter_s = ''): | |
2628 | """Update the alias table with all executable files in $PATH. |
|
2628 | """Update the alias table with all executable files in $PATH. | |
2629 |
|
2629 | |||
2630 | This version explicitly checks that every entry in $PATH is a file |
|
2630 | This version explicitly checks that every entry in $PATH is a file | |
2631 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2631 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2632 |
|
2632 | |||
2633 | Under Windows, it checks executability as a match agains a |
|
2633 | Under Windows, it checks executability as a match agains a | |
2634 | '|'-separated string of extensions, stored in the IPython config |
|
2634 | '|'-separated string of extensions, stored in the IPython config | |
2635 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2635 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2636 |
|
2636 | |||
2637 | This function also resets the root module cache of module completer, |
|
2637 | This function also resets the root module cache of module completer, | |
2638 | used on slow filesystems. |
|
2638 | used on slow filesystems. | |
2639 | """ |
|
2639 | """ | |
2640 | from IPython.core.alias import InvalidAliasError |
|
2640 | from IPython.core.alias import InvalidAliasError | |
2641 |
|
2641 | |||
2642 | # for the benefit of module completer in ipy_completers.py |
|
2642 | # for the benefit of module completer in ipy_completers.py | |
2643 | del self.db['rootmodules'] |
|
2643 | del self.db['rootmodules'] | |
2644 |
|
2644 | |||
2645 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2645 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2646 | os.environ.get('PATH','').split(os.pathsep)] |
|
2646 | os.environ.get('PATH','').split(os.pathsep)] | |
2647 | path = filter(os.path.isdir,path) |
|
2647 | path = filter(os.path.isdir,path) | |
2648 |
|
2648 | |||
2649 | syscmdlist = [] |
|
2649 | syscmdlist = [] | |
2650 | # Now define isexec in a cross platform manner. |
|
2650 | # Now define isexec in a cross platform manner. | |
2651 | if os.name == 'posix': |
|
2651 | if os.name == 'posix': | |
2652 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2652 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2653 | os.access(fname,os.X_OK) |
|
2653 | os.access(fname,os.X_OK) | |
2654 | else: |
|
2654 | else: | |
2655 | try: |
|
2655 | try: | |
2656 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2656 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2657 | except KeyError: |
|
2657 | except KeyError: | |
2658 | winext = 'exe|com|bat|py' |
|
2658 | winext = 'exe|com|bat|py' | |
2659 | if 'py' not in winext: |
|
2659 | if 'py' not in winext: | |
2660 | winext += '|py' |
|
2660 | winext += '|py' | |
2661 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2661 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2662 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2662 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2663 | savedir = os.getcwd() |
|
2663 | savedir = os.getcwd() | |
2664 |
|
2664 | |||
2665 | # Now walk the paths looking for executables to alias. |
|
2665 | # Now walk the paths looking for executables to alias. | |
2666 | try: |
|
2666 | try: | |
2667 | # write the whole loop for posix/Windows so we don't have an if in |
|
2667 | # write the whole loop for posix/Windows so we don't have an if in | |
2668 | # the innermost part |
|
2668 | # the innermost part | |
2669 | if os.name == 'posix': |
|
2669 | if os.name == 'posix': | |
2670 | for pdir in path: |
|
2670 | for pdir in path: | |
2671 | os.chdir(pdir) |
|
2671 | os.chdir(pdir) | |
2672 | for ff in os.listdir(pdir): |
|
2672 | for ff in os.listdir(pdir): | |
2673 | if isexec(ff): |
|
2673 | if isexec(ff): | |
2674 | try: |
|
2674 | try: | |
2675 | # Removes dots from the name since ipython |
|
2675 | # Removes dots from the name since ipython | |
2676 | # will assume names with dots to be python. |
|
2676 | # will assume names with dots to be python. | |
2677 | self.shell.alias_manager.define_alias( |
|
2677 | self.shell.alias_manager.define_alias( | |
2678 | ff.replace('.',''), ff) |
|
2678 | ff.replace('.',''), ff) | |
2679 | except InvalidAliasError: |
|
2679 | except InvalidAliasError: | |
2680 | pass |
|
2680 | pass | |
2681 | else: |
|
2681 | else: | |
2682 | syscmdlist.append(ff) |
|
2682 | syscmdlist.append(ff) | |
2683 | else: |
|
2683 | else: | |
2684 | for pdir in path: |
|
2684 | for pdir in path: | |
2685 | os.chdir(pdir) |
|
2685 | os.chdir(pdir) | |
2686 | for ff in os.listdir(pdir): |
|
2686 | for ff in os.listdir(pdir): | |
2687 | base, ext = os.path.splitext(ff) |
|
2687 | base, ext = os.path.splitext(ff) | |
2688 | if isexec(ff) and base.lower() not in self.shell.no_alias: |
|
2688 | if isexec(ff) and base.lower() not in self.shell.no_alias: | |
2689 | if ext.lower() == '.exe': |
|
2689 | if ext.lower() == '.exe': | |
2690 | ff = base |
|
2690 | ff = base | |
2691 | try: |
|
2691 | try: | |
2692 | # Removes dots from the name since ipython |
|
2692 | # Removes dots from the name since ipython | |
2693 | # will assume names with dots to be python. |
|
2693 | # will assume names with dots to be python. | |
2694 | self.shell.alias_manager.define_alias( |
|
2694 | self.shell.alias_manager.define_alias( | |
2695 | base.lower().replace('.',''), ff) |
|
2695 | base.lower().replace('.',''), ff) | |
2696 | except InvalidAliasError: |
|
2696 | except InvalidAliasError: | |
2697 | pass |
|
2697 | pass | |
2698 | syscmdlist.append(ff) |
|
2698 | syscmdlist.append(ff) | |
2699 | db = self.db |
|
2699 | db = self.db | |
2700 | db['syscmdlist'] = syscmdlist |
|
2700 | db['syscmdlist'] = syscmdlist | |
2701 | finally: |
|
2701 | finally: | |
2702 | os.chdir(savedir) |
|
2702 | os.chdir(savedir) | |
2703 |
|
2703 | |||
2704 | def magic_pwd(self, parameter_s = ''): |
|
2704 | def magic_pwd(self, parameter_s = ''): | |
2705 | """Return the current working directory path.""" |
|
2705 | """Return the current working directory path.""" | |
2706 | return os.getcwd() |
|
2706 | return os.getcwd() | |
2707 |
|
2707 | |||
2708 | def magic_cd(self, parameter_s=''): |
|
2708 | def magic_cd(self, parameter_s=''): | |
2709 | """Change the current working directory. |
|
2709 | """Change the current working directory. | |
2710 |
|
2710 | |||
2711 | This command automatically maintains an internal list of directories |
|
2711 | This command automatically maintains an internal list of directories | |
2712 | you visit during your IPython session, in the variable _dh. The |
|
2712 | you visit during your IPython session, in the variable _dh. The | |
2713 | command %dhist shows this history nicely formatted. You can also |
|
2713 | command %dhist shows this history nicely formatted. You can also | |
2714 | do 'cd -<tab>' to see directory history conveniently. |
|
2714 | do 'cd -<tab>' to see directory history conveniently. | |
2715 |
|
2715 | |||
2716 | Usage: |
|
2716 | Usage: | |
2717 |
|
2717 | |||
2718 | cd 'dir': changes to directory 'dir'. |
|
2718 | cd 'dir': changes to directory 'dir'. | |
2719 |
|
2719 | |||
2720 | cd -: changes to the last visited directory. |
|
2720 | cd -: changes to the last visited directory. | |
2721 |
|
2721 | |||
2722 | cd -<n>: changes to the n-th directory in the directory history. |
|
2722 | cd -<n>: changes to the n-th directory in the directory history. | |
2723 |
|
2723 | |||
2724 | cd --foo: change to directory that matches 'foo' in history |
|
2724 | cd --foo: change to directory that matches 'foo' in history | |
2725 |
|
2725 | |||
2726 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2726 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2727 | (note: cd <bookmark_name> is enough if there is no |
|
2727 | (note: cd <bookmark_name> is enough if there is no | |
2728 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2728 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2729 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2729 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2730 |
|
2730 | |||
2731 | Options: |
|
2731 | Options: | |
2732 |
|
2732 | |||
2733 | -q: quiet. Do not print the working directory after the cd command is |
|
2733 | -q: quiet. Do not print the working directory after the cd command is | |
2734 | executed. By default IPython's cd command does print this directory, |
|
2734 | executed. By default IPython's cd command does print this directory, | |
2735 | since the default prompts do not display path information. |
|
2735 | since the default prompts do not display path information. | |
2736 |
|
2736 | |||
2737 | Note that !cd doesn't work for this purpose because the shell where |
|
2737 | Note that !cd doesn't work for this purpose because the shell where | |
2738 | !command runs is immediately discarded after executing 'command'.""" |
|
2738 | !command runs is immediately discarded after executing 'command'.""" | |
2739 |
|
2739 | |||
2740 | parameter_s = parameter_s.strip() |
|
2740 | parameter_s = parameter_s.strip() | |
2741 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2741 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2742 |
|
2742 | |||
2743 | oldcwd = os.getcwd() |
|
2743 | oldcwd = os.getcwd() | |
2744 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2744 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2745 | # jump in directory history by number |
|
2745 | # jump in directory history by number | |
2746 | if numcd: |
|
2746 | if numcd: | |
2747 | nn = int(numcd.group(2)) |
|
2747 | nn = int(numcd.group(2)) | |
2748 | try: |
|
2748 | try: | |
2749 | ps = self.shell.user_ns['_dh'][nn] |
|
2749 | ps = self.shell.user_ns['_dh'][nn] | |
2750 | except IndexError: |
|
2750 | except IndexError: | |
2751 | print 'The requested directory does not exist in history.' |
|
2751 | print 'The requested directory does not exist in history.' | |
2752 | return |
|
2752 | return | |
2753 | else: |
|
2753 | else: | |
2754 | opts = {} |
|
2754 | opts = {} | |
2755 | elif parameter_s.startswith('--'): |
|
2755 | elif parameter_s.startswith('--'): | |
2756 | ps = None |
|
2756 | ps = None | |
2757 | fallback = None |
|
2757 | fallback = None | |
2758 | pat = parameter_s[2:] |
|
2758 | pat = parameter_s[2:] | |
2759 | dh = self.shell.user_ns['_dh'] |
|
2759 | dh = self.shell.user_ns['_dh'] | |
2760 | # first search only by basename (last component) |
|
2760 | # first search only by basename (last component) | |
2761 | for ent in reversed(dh): |
|
2761 | for ent in reversed(dh): | |
2762 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2762 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2763 | ps = ent |
|
2763 | ps = ent | |
2764 | break |
|
2764 | break | |
2765 |
|
2765 | |||
2766 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2766 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2767 | fallback = ent |
|
2767 | fallback = ent | |
2768 |
|
2768 | |||
2769 | # if we have no last part match, pick the first full path match |
|
2769 | # if we have no last part match, pick the first full path match | |
2770 | if ps is None: |
|
2770 | if ps is None: | |
2771 | ps = fallback |
|
2771 | ps = fallback | |
2772 |
|
2772 | |||
2773 | if ps is None: |
|
2773 | if ps is None: | |
2774 | print "No matching entry in directory history" |
|
2774 | print "No matching entry in directory history" | |
2775 | return |
|
2775 | return | |
2776 | else: |
|
2776 | else: | |
2777 | opts = {} |
|
2777 | opts = {} | |
2778 |
|
2778 | |||
2779 |
|
2779 | |||
2780 | else: |
|
2780 | else: | |
2781 | #turn all non-space-escaping backslashes to slashes, |
|
2781 | #turn all non-space-escaping backslashes to slashes, | |
2782 | # for c:\windows\directory\names\ |
|
2782 | # for c:\windows\directory\names\ | |
2783 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2783 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2784 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2784 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2785 | # jump to previous |
|
2785 | # jump to previous | |
2786 | if ps == '-': |
|
2786 | if ps == '-': | |
2787 | try: |
|
2787 | try: | |
2788 | ps = self.shell.user_ns['_dh'][-2] |
|
2788 | ps = self.shell.user_ns['_dh'][-2] | |
2789 | except IndexError: |
|
2789 | except IndexError: | |
2790 | raise UsageError('%cd -: No previous directory to change to.') |
|
2790 | raise UsageError('%cd -: No previous directory to change to.') | |
2791 | # jump to bookmark if needed |
|
2791 | # jump to bookmark if needed | |
2792 | else: |
|
2792 | else: | |
2793 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2793 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2794 | bkms = self.db.get('bookmarks', {}) |
|
2794 | bkms = self.db.get('bookmarks', {}) | |
2795 |
|
2795 | |||
2796 | if bkms.has_key(ps): |
|
2796 | if bkms.has_key(ps): | |
2797 | target = bkms[ps] |
|
2797 | target = bkms[ps] | |
2798 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2798 | print '(bookmark:%s) -> %s' % (ps,target) | |
2799 | ps = target |
|
2799 | ps = target | |
2800 | else: |
|
2800 | else: | |
2801 | if opts.has_key('b'): |
|
2801 | if opts.has_key('b'): | |
2802 | raise UsageError("Bookmark '%s' not found. " |
|
2802 | raise UsageError("Bookmark '%s' not found. " | |
2803 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2803 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2804 |
|
2804 | |||
2805 | # at this point ps should point to the target dir |
|
2805 | # at this point ps should point to the target dir | |
2806 | if ps: |
|
2806 | if ps: | |
2807 | try: |
|
2807 | try: | |
2808 | os.chdir(os.path.expanduser(ps)) |
|
2808 | os.chdir(os.path.expanduser(ps)) | |
2809 | if self.shell.term_title: |
|
2809 | if self.shell.term_title: | |
2810 | platutils.set_term_title('IPython: ' + abbrev_cwd()) |
|
2810 | platutils.set_term_title('IPython: ' + abbrev_cwd()) | |
2811 | except OSError: |
|
2811 | except OSError: | |
2812 | print sys.exc_info()[1] |
|
2812 | print sys.exc_info()[1] | |
2813 | else: |
|
2813 | else: | |
2814 | cwd = os.getcwd() |
|
2814 | cwd = os.getcwd() | |
2815 | dhist = self.shell.user_ns['_dh'] |
|
2815 | dhist = self.shell.user_ns['_dh'] | |
2816 | if oldcwd != cwd: |
|
2816 | if oldcwd != cwd: | |
2817 | dhist.append(cwd) |
|
2817 | dhist.append(cwd) | |
2818 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2818 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2819 |
|
2819 | |||
2820 | else: |
|
2820 | else: | |
2821 | os.chdir(self.shell.home_dir) |
|
2821 | os.chdir(self.shell.home_dir) | |
2822 | if self.shell.term_title: |
|
2822 | if self.shell.term_title: | |
2823 | platutils.set_term_title('IPython: ' + '~') |
|
2823 | platutils.set_term_title('IPython: ' + '~') | |
2824 | cwd = os.getcwd() |
|
2824 | cwd = os.getcwd() | |
2825 | dhist = self.shell.user_ns['_dh'] |
|
2825 | dhist = self.shell.user_ns['_dh'] | |
2826 |
|
2826 | |||
2827 | if oldcwd != cwd: |
|
2827 | if oldcwd != cwd: | |
2828 | dhist.append(cwd) |
|
2828 | dhist.append(cwd) | |
2829 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2829 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2830 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2830 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2831 | print self.shell.user_ns['_dh'][-1] |
|
2831 | print self.shell.user_ns['_dh'][-1] | |
2832 |
|
2832 | |||
2833 |
|
2833 | |||
2834 | def magic_env(self, parameter_s=''): |
|
2834 | def magic_env(self, parameter_s=''): | |
2835 | """List environment variables.""" |
|
2835 | """List environment variables.""" | |
2836 |
|
2836 | |||
2837 | return os.environ.data |
|
2837 | return os.environ.data | |
2838 |
|
2838 | |||
2839 | def magic_pushd(self, parameter_s=''): |
|
2839 | def magic_pushd(self, parameter_s=''): | |
2840 | """Place the current dir on stack and change directory. |
|
2840 | """Place the current dir on stack and change directory. | |
2841 |
|
2841 | |||
2842 | Usage:\\ |
|
2842 | Usage:\\ | |
2843 | %pushd ['dirname'] |
|
2843 | %pushd ['dirname'] | |
2844 | """ |
|
2844 | """ | |
2845 |
|
2845 | |||
2846 | dir_s = self.shell.dir_stack |
|
2846 | dir_s = self.shell.dir_stack | |
2847 | tgt = os.path.expanduser(parameter_s) |
|
2847 | tgt = os.path.expanduser(parameter_s) | |
2848 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2848 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2849 | if tgt: |
|
2849 | if tgt: | |
2850 | self.magic_cd(parameter_s) |
|
2850 | self.magic_cd(parameter_s) | |
2851 | dir_s.insert(0,cwd) |
|
2851 | dir_s.insert(0,cwd) | |
2852 | return self.magic_dirs() |
|
2852 | return self.magic_dirs() | |
2853 |
|
2853 | |||
2854 | def magic_popd(self, parameter_s=''): |
|
2854 | def magic_popd(self, parameter_s=''): | |
2855 | """Change to directory popped off the top of the stack. |
|
2855 | """Change to directory popped off the top of the stack. | |
2856 | """ |
|
2856 | """ | |
2857 | if not self.shell.dir_stack: |
|
2857 | if not self.shell.dir_stack: | |
2858 | raise UsageError("%popd on empty stack") |
|
2858 | raise UsageError("%popd on empty stack") | |
2859 | top = self.shell.dir_stack.pop(0) |
|
2859 | top = self.shell.dir_stack.pop(0) | |
2860 | self.magic_cd(top) |
|
2860 | self.magic_cd(top) | |
2861 | print "popd ->",top |
|
2861 | print "popd ->",top | |
2862 |
|
2862 | |||
2863 | def magic_dirs(self, parameter_s=''): |
|
2863 | def magic_dirs(self, parameter_s=''): | |
2864 | """Return the current directory stack.""" |
|
2864 | """Return the current directory stack.""" | |
2865 |
|
2865 | |||
2866 | return self.shell.dir_stack |
|
2866 | return self.shell.dir_stack | |
2867 |
|
2867 | |||
2868 | def magic_dhist(self, parameter_s=''): |
|
2868 | def magic_dhist(self, parameter_s=''): | |
2869 | """Print your history of visited directories. |
|
2869 | """Print your history of visited directories. | |
2870 |
|
2870 | |||
2871 | %dhist -> print full history\\ |
|
2871 | %dhist -> print full history\\ | |
2872 | %dhist n -> print last n entries only\\ |
|
2872 | %dhist n -> print last n entries only\\ | |
2873 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2873 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2874 |
|
2874 | |||
2875 | This history is automatically maintained by the %cd command, and |
|
2875 | This history is automatically maintained by the %cd command, and | |
2876 | always available as the global list variable _dh. You can use %cd -<n> |
|
2876 | always available as the global list variable _dh. You can use %cd -<n> | |
2877 | to go to directory number <n>. |
|
2877 | to go to directory number <n>. | |
2878 |
|
2878 | |||
2879 | Note that most of time, you should view directory history by entering |
|
2879 | Note that most of time, you should view directory history by entering | |
2880 | cd -<TAB>. |
|
2880 | cd -<TAB>. | |
2881 |
|
2881 | |||
2882 | """ |
|
2882 | """ | |
2883 |
|
2883 | |||
2884 | dh = self.shell.user_ns['_dh'] |
|
2884 | dh = self.shell.user_ns['_dh'] | |
2885 | if parameter_s: |
|
2885 | if parameter_s: | |
2886 | try: |
|
2886 | try: | |
2887 | args = map(int,parameter_s.split()) |
|
2887 | args = map(int,parameter_s.split()) | |
2888 | except: |
|
2888 | except: | |
2889 | self.arg_err(Magic.magic_dhist) |
|
2889 | self.arg_err(Magic.magic_dhist) | |
2890 | return |
|
2890 | return | |
2891 | if len(args) == 1: |
|
2891 | if len(args) == 1: | |
2892 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2892 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2893 | elif len(args) == 2: |
|
2893 | elif len(args) == 2: | |
2894 | ini,fin = args |
|
2894 | ini,fin = args | |
2895 | else: |
|
2895 | else: | |
2896 | self.arg_err(Magic.magic_dhist) |
|
2896 | self.arg_err(Magic.magic_dhist) | |
2897 | return |
|
2897 | return | |
2898 | else: |
|
2898 | else: | |
2899 | ini,fin = 0,len(dh) |
|
2899 | ini,fin = 0,len(dh) | |
2900 | nlprint(dh, |
|
2900 | nlprint(dh, | |
2901 | header = 'Directory history (kept in _dh)', |
|
2901 | header = 'Directory history (kept in _dh)', | |
2902 | start=ini,stop=fin) |
|
2902 | start=ini,stop=fin) | |
2903 |
|
2903 | |||
2904 | @testdec.skip_doctest |
|
2904 | @testdec.skip_doctest | |
2905 | def magic_sc(self, parameter_s=''): |
|
2905 | def magic_sc(self, parameter_s=''): | |
2906 | """Shell capture - execute a shell command and capture its output. |
|
2906 | """Shell capture - execute a shell command and capture its output. | |
2907 |
|
2907 | |||
2908 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2908 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2909 |
|
2909 | |||
2910 | You should use the form 'var = !command' instead. Example: |
|
2910 | You should use the form 'var = !command' instead. Example: | |
2911 |
|
2911 | |||
2912 | "%sc -l myfiles = ls ~" should now be written as |
|
2912 | "%sc -l myfiles = ls ~" should now be written as | |
2913 |
|
2913 | |||
2914 | "myfiles = !ls ~" |
|
2914 | "myfiles = !ls ~" | |
2915 |
|
2915 | |||
2916 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2916 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2917 | below. |
|
2917 | below. | |
2918 |
|
2918 | |||
2919 | -- |
|
2919 | -- | |
2920 | %sc [options] varname=command |
|
2920 | %sc [options] varname=command | |
2921 |
|
2921 | |||
2922 | IPython will run the given command using commands.getoutput(), and |
|
2922 | IPython will run the given command using commands.getoutput(), and | |
2923 | will then update the user's interactive namespace with a variable |
|
2923 | will then update the user's interactive namespace with a variable | |
2924 | called varname, containing the value of the call. Your command can |
|
2924 | called varname, containing the value of the call. Your command can | |
2925 | contain shell wildcards, pipes, etc. |
|
2925 | contain shell wildcards, pipes, etc. | |
2926 |
|
2926 | |||
2927 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2927 | The '=' sign in the syntax is mandatory, and the variable name you | |
2928 | supply must follow Python's standard conventions for valid names. |
|
2928 | supply must follow Python's standard conventions for valid names. | |
2929 |
|
2929 | |||
2930 | (A special format without variable name exists for internal use) |
|
2930 | (A special format without variable name exists for internal use) | |
2931 |
|
2931 | |||
2932 | Options: |
|
2932 | Options: | |
2933 |
|
2933 | |||
2934 | -l: list output. Split the output on newlines into a list before |
|
2934 | -l: list output. Split the output on newlines into a list before | |
2935 | assigning it to the given variable. By default the output is stored |
|
2935 | assigning it to the given variable. By default the output is stored | |
2936 | as a single string. |
|
2936 | as a single string. | |
2937 |
|
2937 | |||
2938 | -v: verbose. Print the contents of the variable. |
|
2938 | -v: verbose. Print the contents of the variable. | |
2939 |
|
2939 | |||
2940 | In most cases you should not need to split as a list, because the |
|
2940 | In most cases you should not need to split as a list, because the | |
2941 | returned value is a special type of string which can automatically |
|
2941 | returned value is a special type of string which can automatically | |
2942 | provide its contents either as a list (split on newlines) or as a |
|
2942 | provide its contents either as a list (split on newlines) or as a | |
2943 | space-separated string. These are convenient, respectively, either |
|
2943 | space-separated string. These are convenient, respectively, either | |
2944 | for sequential processing or to be passed to a shell command. |
|
2944 | for sequential processing or to be passed to a shell command. | |
2945 |
|
2945 | |||
2946 | For example: |
|
2946 | For example: | |
2947 |
|
2947 | |||
2948 | # all-random |
|
2948 | # all-random | |
2949 |
|
2949 | |||
2950 | # Capture into variable a |
|
2950 | # Capture into variable a | |
2951 | In [1]: sc a=ls *py |
|
2951 | In [1]: sc a=ls *py | |
2952 |
|
2952 | |||
2953 | # a is a string with embedded newlines |
|
2953 | # a is a string with embedded newlines | |
2954 | In [2]: a |
|
2954 | In [2]: a | |
2955 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2955 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2956 |
|
2956 | |||
2957 | # which can be seen as a list: |
|
2957 | # which can be seen as a list: | |
2958 | In [3]: a.l |
|
2958 | In [3]: a.l | |
2959 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2959 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2960 |
|
2960 | |||
2961 | # or as a whitespace-separated string: |
|
2961 | # or as a whitespace-separated string: | |
2962 | In [4]: a.s |
|
2962 | In [4]: a.s | |
2963 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2963 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2964 |
|
2964 | |||
2965 | # a.s is useful to pass as a single command line: |
|
2965 | # a.s is useful to pass as a single command line: | |
2966 | In [5]: !wc -l $a.s |
|
2966 | In [5]: !wc -l $a.s | |
2967 | 146 setup.py |
|
2967 | 146 setup.py | |
2968 | 130 win32_manual_post_install.py |
|
2968 | 130 win32_manual_post_install.py | |
2969 | 276 total |
|
2969 | 276 total | |
2970 |
|
2970 | |||
2971 | # while the list form is useful to loop over: |
|
2971 | # while the list form is useful to loop over: | |
2972 | In [6]: for f in a.l: |
|
2972 | In [6]: for f in a.l: | |
2973 | ...: !wc -l $f |
|
2973 | ...: !wc -l $f | |
2974 | ...: |
|
2974 | ...: | |
2975 | 146 setup.py |
|
2975 | 146 setup.py | |
2976 | 130 win32_manual_post_install.py |
|
2976 | 130 win32_manual_post_install.py | |
2977 |
|
2977 | |||
2978 | Similiarly, the lists returned by the -l option are also special, in |
|
2978 | Similiarly, the lists returned by the -l option are also special, in | |
2979 | the sense that you can equally invoke the .s attribute on them to |
|
2979 | the sense that you can equally invoke the .s attribute on them to | |
2980 | automatically get a whitespace-separated string from their contents: |
|
2980 | automatically get a whitespace-separated string from their contents: | |
2981 |
|
2981 | |||
2982 | In [7]: sc -l b=ls *py |
|
2982 | In [7]: sc -l b=ls *py | |
2983 |
|
2983 | |||
2984 | In [8]: b |
|
2984 | In [8]: b | |
2985 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2985 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2986 |
|
2986 | |||
2987 | In [9]: b.s |
|
2987 | In [9]: b.s | |
2988 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2988 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2989 |
|
2989 | |||
2990 | In summary, both the lists and strings used for ouptut capture have |
|
2990 | In summary, both the lists and strings used for ouptut capture have | |
2991 | the following special attributes: |
|
2991 | the following special attributes: | |
2992 |
|
2992 | |||
2993 | .l (or .list) : value as list. |
|
2993 | .l (or .list) : value as list. | |
2994 | .n (or .nlstr): value as newline-separated string. |
|
2994 | .n (or .nlstr): value as newline-separated string. | |
2995 | .s (or .spstr): value as space-separated string. |
|
2995 | .s (or .spstr): value as space-separated string. | |
2996 | """ |
|
2996 | """ | |
2997 |
|
2997 | |||
2998 | opts,args = self.parse_options(parameter_s,'lv') |
|
2998 | opts,args = self.parse_options(parameter_s,'lv') | |
2999 | # Try to get a variable name and command to run |
|
2999 | # Try to get a variable name and command to run | |
3000 | try: |
|
3000 | try: | |
3001 | # the variable name must be obtained from the parse_options |
|
3001 | # the variable name must be obtained from the parse_options | |
3002 | # output, which uses shlex.split to strip options out. |
|
3002 | # output, which uses shlex.split to strip options out. | |
3003 | var,_ = args.split('=',1) |
|
3003 | var,_ = args.split('=',1) | |
3004 | var = var.strip() |
|
3004 | var = var.strip() | |
3005 | # But the the command has to be extracted from the original input |
|
3005 | # But the the command has to be extracted from the original input | |
3006 | # parameter_s, not on what parse_options returns, to avoid the |
|
3006 | # parameter_s, not on what parse_options returns, to avoid the | |
3007 | # quote stripping which shlex.split performs on it. |
|
3007 | # quote stripping which shlex.split performs on it. | |
3008 | _,cmd = parameter_s.split('=',1) |
|
3008 | _,cmd = parameter_s.split('=',1) | |
3009 | except ValueError: |
|
3009 | except ValueError: | |
3010 | var,cmd = '','' |
|
3010 | var,cmd = '','' | |
3011 | # If all looks ok, proceed |
|
3011 | # If all looks ok, proceed | |
3012 | out,err = self.shell.getoutputerror(cmd) |
|
3012 | out,err = self.shell.getoutputerror(cmd) | |
3013 | if err: |
|
3013 | if err: | |
3014 | print >> Term.cerr,err |
|
3014 | print >> Term.cerr,err | |
3015 | if opts.has_key('l'): |
|
3015 | if opts.has_key('l'): | |
3016 | out = SList(out.split('\n')) |
|
3016 | out = SList(out.split('\n')) | |
3017 | else: |
|
3017 | else: | |
3018 | out = LSString(out) |
|
3018 | out = LSString(out) | |
3019 | if opts.has_key('v'): |
|
3019 | if opts.has_key('v'): | |
3020 | print '%s ==\n%s' % (var,pformat(out)) |
|
3020 | print '%s ==\n%s' % (var,pformat(out)) | |
3021 | if var: |
|
3021 | if var: | |
3022 | self.shell.user_ns.update({var:out}) |
|
3022 | self.shell.user_ns.update({var:out}) | |
3023 | else: |
|
3023 | else: | |
3024 | return out |
|
3024 | return out | |
3025 |
|
3025 | |||
3026 | def magic_sx(self, parameter_s=''): |
|
3026 | def magic_sx(self, parameter_s=''): | |
3027 | """Shell execute - run a shell command and capture its output. |
|
3027 | """Shell execute - run a shell command and capture its output. | |
3028 |
|
3028 | |||
3029 | %sx command |
|
3029 | %sx command | |
3030 |
|
3030 | |||
3031 | IPython will run the given command using commands.getoutput(), and |
|
3031 | IPython will run the given command using commands.getoutput(), and | |
3032 | return the result formatted as a list (split on '\\n'). Since the |
|
3032 | return the result formatted as a list (split on '\\n'). Since the | |
3033 | output is _returned_, it will be stored in ipython's regular output |
|
3033 | output is _returned_, it will be stored in ipython's regular output | |
3034 | cache Out[N] and in the '_N' automatic variables. |
|
3034 | cache Out[N] and in the '_N' automatic variables. | |
3035 |
|
3035 | |||
3036 | Notes: |
|
3036 | Notes: | |
3037 |
|
3037 | |||
3038 | 1) If an input line begins with '!!', then %sx is automatically |
|
3038 | 1) If an input line begins with '!!', then %sx is automatically | |
3039 | invoked. That is, while: |
|
3039 | invoked. That is, while: | |
3040 | !ls |
|
3040 | !ls | |
3041 | causes ipython to simply issue system('ls'), typing |
|
3041 | causes ipython to simply issue system('ls'), typing | |
3042 | !!ls |
|
3042 | !!ls | |
3043 | is a shorthand equivalent to: |
|
3043 | is a shorthand equivalent to: | |
3044 | %sx ls |
|
3044 | %sx ls | |
3045 |
|
3045 | |||
3046 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3046 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3047 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3047 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3048 | to process line-oriented shell output via further python commands. |
|
3048 | to process line-oriented shell output via further python commands. | |
3049 | %sc is meant to provide much finer control, but requires more |
|
3049 | %sc is meant to provide much finer control, but requires more | |
3050 | typing. |
|
3050 | typing. | |
3051 |
|
3051 | |||
3052 | 3) Just like %sc -l, this is a list with special attributes: |
|
3052 | 3) Just like %sc -l, this is a list with special attributes: | |
3053 |
|
3053 | |||
3054 | .l (or .list) : value as list. |
|
3054 | .l (or .list) : value as list. | |
3055 | .n (or .nlstr): value as newline-separated string. |
|
3055 | .n (or .nlstr): value as newline-separated string. | |
3056 | .s (or .spstr): value as whitespace-separated string. |
|
3056 | .s (or .spstr): value as whitespace-separated string. | |
3057 |
|
3057 | |||
3058 | This is very useful when trying to use such lists as arguments to |
|
3058 | This is very useful when trying to use such lists as arguments to | |
3059 | system commands.""" |
|
3059 | system commands.""" | |
3060 |
|
3060 | |||
3061 | if parameter_s: |
|
3061 | if parameter_s: | |
3062 | out,err = self.shell.getoutputerror(parameter_s) |
|
3062 | out,err = self.shell.getoutputerror(parameter_s) | |
3063 | if err: |
|
3063 | if err: | |
3064 | print >> Term.cerr,err |
|
3064 | print >> Term.cerr,err | |
3065 | return SList(out.split('\n')) |
|
3065 | return SList(out.split('\n')) | |
3066 |
|
3066 | |||
3067 | def magic_bg(self, parameter_s=''): |
|
3067 | def magic_bg(self, parameter_s=''): | |
3068 | """Run a job in the background, in a separate thread. |
|
3068 | """Run a job in the background, in a separate thread. | |
3069 |
|
3069 | |||
3070 | For example, |
|
3070 | For example, | |
3071 |
|
3071 | |||
3072 | %bg myfunc(x,y,z=1) |
|
3072 | %bg myfunc(x,y,z=1) | |
3073 |
|
3073 | |||
3074 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3074 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
3075 | execution starts, a message will be printed indicating the job |
|
3075 | execution starts, a message will be printed indicating the job | |
3076 | number. If your job number is 5, you can use |
|
3076 | number. If your job number is 5, you can use | |
3077 |
|
3077 | |||
3078 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3078 | myvar = jobs.result(5) or myvar = jobs[5].result | |
3079 |
|
3079 | |||
3080 | to assign this result to variable 'myvar'. |
|
3080 | to assign this result to variable 'myvar'. | |
3081 |
|
3081 | |||
3082 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3082 | IPython has a job manager, accessible via the 'jobs' object. You can | |
3083 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3083 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
3084 | its attributes. All attributes not starting with an underscore are |
|
3084 | its attributes. All attributes not starting with an underscore are | |
3085 | meant for public use. |
|
3085 | meant for public use. | |
3086 |
|
3086 | |||
3087 | In particular, look at the jobs.new() method, which is used to create |
|
3087 | In particular, look at the jobs.new() method, which is used to create | |
3088 | new jobs. This magic %bg function is just a convenience wrapper |
|
3088 | new jobs. This magic %bg function is just a convenience wrapper | |
3089 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3089 | around jobs.new(), for expression-based jobs. If you want to create a | |
3090 | new job with an explicit function object and arguments, you must call |
|
3090 | new job with an explicit function object and arguments, you must call | |
3091 | jobs.new() directly. |
|
3091 | jobs.new() directly. | |
3092 |
|
3092 | |||
3093 | The jobs.new docstring also describes in detail several important |
|
3093 | The jobs.new docstring also describes in detail several important | |
3094 | caveats associated with a thread-based model for background job |
|
3094 | caveats associated with a thread-based model for background job | |
3095 | execution. Type jobs.new? for details. |
|
3095 | execution. Type jobs.new? for details. | |
3096 |
|
3096 | |||
3097 | You can check the status of all jobs with jobs.status(). |
|
3097 | You can check the status of all jobs with jobs.status(). | |
3098 |
|
3098 | |||
3099 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3099 | The jobs variable is set by IPython into the Python builtin namespace. | |
3100 | If you ever declare a variable named 'jobs', you will shadow this |
|
3100 | If you ever declare a variable named 'jobs', you will shadow this | |
3101 | name. You can either delete your global jobs variable to regain |
|
3101 | name. You can either delete your global jobs variable to regain | |
3102 | access to the job manager, or make a new name and assign it manually |
|
3102 | access to the job manager, or make a new name and assign it manually | |
3103 | to the manager (stored in IPython's namespace). For example, to |
|
3103 | to the manager (stored in IPython's namespace). For example, to | |
3104 | assign the job manager to the Jobs name, use: |
|
3104 | assign the job manager to the Jobs name, use: | |
3105 |
|
3105 | |||
3106 | Jobs = __builtins__.jobs""" |
|
3106 | Jobs = __builtins__.jobs""" | |
3107 |
|
3107 | |||
3108 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3108 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
3109 |
|
3109 | |||
3110 | def magic_r(self, parameter_s=''): |
|
3110 | def magic_r(self, parameter_s=''): | |
3111 | """Repeat previous input. |
|
3111 | """Repeat previous input. | |
3112 |
|
3112 | |||
3113 | Note: Consider using the more powerfull %rep instead! |
|
3113 | Note: Consider using the more powerfull %rep instead! | |
3114 |
|
3114 | |||
3115 | If given an argument, repeats the previous command which starts with |
|
3115 | If given an argument, repeats the previous command which starts with | |
3116 | the same string, otherwise it just repeats the previous input. |
|
3116 | the same string, otherwise it just repeats the previous input. | |
3117 |
|
3117 | |||
3118 | Shell escaped commands (with ! as first character) are not recognized |
|
3118 | Shell escaped commands (with ! as first character) are not recognized | |
3119 | by this system, only pure python code and magic commands. |
|
3119 | by this system, only pure python code and magic commands. | |
3120 | """ |
|
3120 | """ | |
3121 |
|
3121 | |||
3122 | start = parameter_s.strip() |
|
3122 | start = parameter_s.strip() | |
3123 | esc_magic = ESC_MAGIC |
|
3123 | esc_magic = ESC_MAGIC | |
3124 | # Identify magic commands even if automagic is on (which means |
|
3124 | # Identify magic commands even if automagic is on (which means | |
3125 | # the in-memory version is different from that typed by the user). |
|
3125 | # the in-memory version is different from that typed by the user). | |
3126 | if self.shell.automagic: |
|
3126 | if self.shell.automagic: | |
3127 | start_magic = esc_magic+start |
|
3127 | start_magic = esc_magic+start | |
3128 | else: |
|
3128 | else: | |
3129 | start_magic = start |
|
3129 | start_magic = start | |
3130 | # Look through the input history in reverse |
|
3130 | # Look through the input history in reverse | |
3131 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3131 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3132 | input = self.shell.input_hist[n] |
|
3132 | input = self.shell.input_hist[n] | |
3133 | # skip plain 'r' lines so we don't recurse to infinity |
|
3133 | # skip plain 'r' lines so we don't recurse to infinity | |
3134 | if input != '_ip.magic("r")\n' and \ |
|
3134 | if input != '_ip.magic("r")\n' and \ | |
3135 | (input.startswith(start) or input.startswith(start_magic)): |
|
3135 | (input.startswith(start) or input.startswith(start_magic)): | |
3136 | #print 'match',`input` # dbg |
|
3136 | #print 'match',`input` # dbg | |
3137 | print 'Executing:',input, |
|
3137 | print 'Executing:',input, | |
3138 | self.shell.runlines(input) |
|
3138 | self.shell.runlines(input) | |
3139 | return |
|
3139 | return | |
3140 | print 'No previous input matching `%s` found.' % start |
|
3140 | print 'No previous input matching `%s` found.' % start | |
3141 |
|
3141 | |||
3142 |
|
3142 | |||
3143 | def magic_bookmark(self, parameter_s=''): |
|
3143 | def magic_bookmark(self, parameter_s=''): | |
3144 | """Manage IPython's bookmark system. |
|
3144 | """Manage IPython's bookmark system. | |
3145 |
|
3145 | |||
3146 | %bookmark <name> - set bookmark to current dir |
|
3146 | %bookmark <name> - set bookmark to current dir | |
3147 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3147 | %bookmark <name> <dir> - set bookmark to <dir> | |
3148 | %bookmark -l - list all bookmarks |
|
3148 | %bookmark -l - list all bookmarks | |
3149 | %bookmark -d <name> - remove bookmark |
|
3149 | %bookmark -d <name> - remove bookmark | |
3150 | %bookmark -r - remove all bookmarks |
|
3150 | %bookmark -r - remove all bookmarks | |
3151 |
|
3151 | |||
3152 | You can later on access a bookmarked folder with: |
|
3152 | You can later on access a bookmarked folder with: | |
3153 | %cd -b <name> |
|
3153 | %cd -b <name> | |
3154 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3154 | or simply '%cd <name>' if there is no directory called <name> AND | |
3155 | there is such a bookmark defined. |
|
3155 | there is such a bookmark defined. | |
3156 |
|
3156 | |||
3157 | Your bookmarks persist through IPython sessions, but they are |
|
3157 | Your bookmarks persist through IPython sessions, but they are | |
3158 | associated with each profile.""" |
|
3158 | associated with each profile.""" | |
3159 |
|
3159 | |||
3160 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3160 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3161 | if len(args) > 2: |
|
3161 | if len(args) > 2: | |
3162 | raise UsageError("%bookmark: too many arguments") |
|
3162 | raise UsageError("%bookmark: too many arguments") | |
3163 |
|
3163 | |||
3164 | bkms = self.db.get('bookmarks',{}) |
|
3164 | bkms = self.db.get('bookmarks',{}) | |
3165 |
|
3165 | |||
3166 | if opts.has_key('d'): |
|
3166 | if opts.has_key('d'): | |
3167 | try: |
|
3167 | try: | |
3168 | todel = args[0] |
|
3168 | todel = args[0] | |
3169 | except IndexError: |
|
3169 | except IndexError: | |
3170 | raise UsageError( |
|
3170 | raise UsageError( | |
3171 | "%bookmark -d: must provide a bookmark to delete") |
|
3171 | "%bookmark -d: must provide a bookmark to delete") | |
3172 | else: |
|
3172 | else: | |
3173 | try: |
|
3173 | try: | |
3174 | del bkms[todel] |
|
3174 | del bkms[todel] | |
3175 | except KeyError: |
|
3175 | except KeyError: | |
3176 | raise UsageError( |
|
3176 | raise UsageError( | |
3177 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3177 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3178 |
|
3178 | |||
3179 | elif opts.has_key('r'): |
|
3179 | elif opts.has_key('r'): | |
3180 | bkms = {} |
|
3180 | bkms = {} | |
3181 | elif opts.has_key('l'): |
|
3181 | elif opts.has_key('l'): | |
3182 | bks = bkms.keys() |
|
3182 | bks = bkms.keys() | |
3183 | bks.sort() |
|
3183 | bks.sort() | |
3184 | if bks: |
|
3184 | if bks: | |
3185 | size = max(map(len,bks)) |
|
3185 | size = max(map(len,bks)) | |
3186 | else: |
|
3186 | else: | |
3187 | size = 0 |
|
3187 | size = 0 | |
3188 | fmt = '%-'+str(size)+'s -> %s' |
|
3188 | fmt = '%-'+str(size)+'s -> %s' | |
3189 | print 'Current bookmarks:' |
|
3189 | print 'Current bookmarks:' | |
3190 | for bk in bks: |
|
3190 | for bk in bks: | |
3191 | print fmt % (bk,bkms[bk]) |
|
3191 | print fmt % (bk,bkms[bk]) | |
3192 | else: |
|
3192 | else: | |
3193 | if not args: |
|
3193 | if not args: | |
3194 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3194 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3195 | elif len(args)==1: |
|
3195 | elif len(args)==1: | |
3196 | bkms[args[0]] = os.getcwd() |
|
3196 | bkms[args[0]] = os.getcwd() | |
3197 | elif len(args)==2: |
|
3197 | elif len(args)==2: | |
3198 | bkms[args[0]] = args[1] |
|
3198 | bkms[args[0]] = args[1] | |
3199 | self.db['bookmarks'] = bkms |
|
3199 | self.db['bookmarks'] = bkms | |
3200 |
|
3200 | |||
3201 | def magic_pycat(self, parameter_s=''): |
|
3201 | def magic_pycat(self, parameter_s=''): | |
3202 | """Show a syntax-highlighted file through a pager. |
|
3202 | """Show a syntax-highlighted file through a pager. | |
3203 |
|
3203 | |||
3204 | This magic is similar to the cat utility, but it will assume the file |
|
3204 | This magic is similar to the cat utility, but it will assume the file | |
3205 | to be Python source and will show it with syntax highlighting. """ |
|
3205 | to be Python source and will show it with syntax highlighting. """ | |
3206 |
|
3206 | |||
3207 | try: |
|
3207 | try: | |
3208 | filename = get_py_filename(parameter_s) |
|
3208 | filename = get_py_filename(parameter_s) | |
3209 | cont = file_read(filename) |
|
3209 | cont = file_read(filename) | |
3210 | except IOError: |
|
3210 | except IOError: | |
3211 | try: |
|
3211 | try: | |
3212 | cont = eval(parameter_s,self.user_ns) |
|
3212 | cont = eval(parameter_s,self.user_ns) | |
3213 | except NameError: |
|
3213 | except NameError: | |
3214 | cont = None |
|
3214 | cont = None | |
3215 | if cont is None: |
|
3215 | if cont is None: | |
3216 | print "Error: no such file or variable" |
|
3216 | print "Error: no such file or variable" | |
3217 | return |
|
3217 | return | |
3218 |
|
3218 | |||
3219 | page(self.shell.pycolorize(cont), |
|
3219 | page(self.shell.pycolorize(cont), | |
3220 | screen_lines=self.shell.usable_screen_length) |
|
3220 | screen_lines=self.shell.usable_screen_length) | |
3221 |
|
3221 | |||
3222 | def _rerun_pasted(self): |
|
3222 | def _rerun_pasted(self): | |
3223 | """ Rerun a previously pasted command. |
|
3223 | """ Rerun a previously pasted command. | |
3224 | """ |
|
3224 | """ | |
3225 | b = self.user_ns.get('pasted_block', None) |
|
3225 | b = self.user_ns.get('pasted_block', None) | |
3226 | if b is None: |
|
3226 | if b is None: | |
3227 | raise UsageError('No previous pasted block available') |
|
3227 | raise UsageError('No previous pasted block available') | |
3228 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3228 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3229 | exec b in self.user_ns |
|
3229 | exec b in self.user_ns | |
3230 |
|
3230 | |||
3231 | def _get_pasted_lines(self, sentinel): |
|
3231 | def _get_pasted_lines(self, sentinel): | |
3232 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3232 | """ Yield pasted lines until the user enters the given sentinel value. | |
3233 | """ |
|
3233 | """ | |
3234 | from IPython.core import iplib |
|
3234 | from IPython.core import iplib | |
3235 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3235 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3236 | while True: |
|
3236 | while True: | |
3237 | l = iplib.raw_input_original(':') |
|
3237 | l = iplib.raw_input_original(':') | |
3238 | if l == sentinel: |
|
3238 | if l == sentinel: | |
3239 | return |
|
3239 | return | |
3240 | else: |
|
3240 | else: | |
3241 | yield l |
|
3241 | yield l | |
3242 |
|
3242 | |||
3243 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3243 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3244 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3244 | """ Strip non-code parts of a sequence of lines to return a block of | |
3245 | code. |
|
3245 | code. | |
3246 | """ |
|
3246 | """ | |
3247 | # Regular expressions that declare text we strip from the input: |
|
3247 | # Regular expressions that declare text we strip from the input: | |
3248 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3248 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3249 | r'^\s*(\s?>)+', # Python input prompt |
|
3249 | r'^\s*(\s?>)+', # Python input prompt | |
3250 | r'^\s*\.{3,}', # Continuation prompts |
|
3250 | r'^\s*\.{3,}', # Continuation prompts | |
3251 | r'^\++', |
|
3251 | r'^\++', | |
3252 | ] |
|
3252 | ] | |
3253 |
|
3253 | |||
3254 | strip_from_start = map(re.compile,strip_re) |
|
3254 | strip_from_start = map(re.compile,strip_re) | |
3255 |
|
3255 | |||
3256 | lines = [] |
|
3256 | lines = [] | |
3257 | for l in raw_lines: |
|
3257 | for l in raw_lines: | |
3258 | for pat in strip_from_start: |
|
3258 | for pat in strip_from_start: | |
3259 | l = pat.sub('',l) |
|
3259 | l = pat.sub('',l) | |
3260 | lines.append(l) |
|
3260 | lines.append(l) | |
3261 |
|
3261 | |||
3262 | block = "\n".join(lines) + '\n' |
|
3262 | block = "\n".join(lines) + '\n' | |
3263 | #print "block:\n",block |
|
3263 | #print "block:\n",block | |
3264 | return block |
|
3264 | return block | |
3265 |
|
3265 | |||
3266 | def _execute_block(self, block, par): |
|
3266 | def _execute_block(self, block, par): | |
3267 | """ Execute a block, or store it in a variable, per the user's request. |
|
3267 | """ Execute a block, or store it in a variable, per the user's request. | |
3268 | """ |
|
3268 | """ | |
3269 | if not par: |
|
3269 | if not par: | |
3270 | b = textwrap.dedent(block) |
|
3270 | b = textwrap.dedent(block) | |
3271 | self.user_ns['pasted_block'] = b |
|
3271 | self.user_ns['pasted_block'] = b | |
3272 | exec b in self.user_ns |
|
3272 | exec b in self.user_ns | |
3273 | else: |
|
3273 | else: | |
3274 | self.user_ns[par] = SList(block.splitlines()) |
|
3274 | self.user_ns[par] = SList(block.splitlines()) | |
3275 | print "Block assigned to '%s'" % par |
|
3275 | print "Block assigned to '%s'" % par | |
3276 |
|
3276 | |||
3277 | def magic_cpaste(self, parameter_s=''): |
|
3277 | def magic_cpaste(self, parameter_s=''): | |
3278 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3278 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3279 |
|
3279 | |||
3280 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3280 | You must terminate the block with '--' (two minus-signs) alone on the | |
3281 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3281 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3282 | is the new sentinel for this operation) |
|
3282 | is the new sentinel for this operation) | |
3283 |
|
3283 | |||
3284 | The block is dedented prior to execution to enable execution of method |
|
3284 | The block is dedented prior to execution to enable execution of method | |
3285 | definitions. '>' and '+' characters at the beginning of a line are |
|
3285 | definitions. '>' and '+' characters at the beginning of a line are | |
3286 | ignored, to allow pasting directly from e-mails, diff files and |
|
3286 | ignored, to allow pasting directly from e-mails, diff files and | |
3287 | doctests (the '...' continuation prompt is also stripped). The |
|
3287 | doctests (the '...' continuation prompt is also stripped). The | |
3288 | executed block is also assigned to variable named 'pasted_block' for |
|
3288 | executed block is also assigned to variable named 'pasted_block' for | |
3289 | later editing with '%edit pasted_block'. |
|
3289 | later editing with '%edit pasted_block'. | |
3290 |
|
3290 | |||
3291 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3291 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3292 | This assigns the pasted block to variable 'foo' as string, without |
|
3292 | This assigns the pasted block to variable 'foo' as string, without | |
3293 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3293 | dedenting or executing it (preceding >>> and + is still stripped) | |
3294 |
|
3294 | |||
3295 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3295 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
3296 |
|
3296 | |||
3297 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3297 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3298 | Just press enter and type -- (and press enter again) and the block |
|
3298 | Just press enter and type -- (and press enter again) and the block | |
3299 | will be what was just pasted. |
|
3299 | will be what was just pasted. | |
3300 |
|
3300 | |||
3301 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3301 | IPython statements (magics, shell escapes) are not supported (yet). | |
3302 |
|
3302 | |||
3303 | See also |
|
3303 | See also | |
3304 | -------- |
|
3304 | -------- | |
3305 | paste: automatically pull code from clipboard. |
|
3305 | paste: automatically pull code from clipboard. | |
3306 | """ |
|
3306 | """ | |
3307 |
|
3307 | |||
3308 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3308 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
3309 | par = args.strip() |
|
3309 | par = args.strip() | |
3310 | if opts.has_key('r'): |
|
3310 | if opts.has_key('r'): | |
3311 | self._rerun_pasted() |
|
3311 | self._rerun_pasted() | |
3312 | return |
|
3312 | return | |
3313 |
|
3313 | |||
3314 | sentinel = opts.get('s','--') |
|
3314 | sentinel = opts.get('s','--') | |
3315 |
|
3315 | |||
3316 | block = self._strip_pasted_lines_for_code( |
|
3316 | block = self._strip_pasted_lines_for_code( | |
3317 | self._get_pasted_lines(sentinel)) |
|
3317 | self._get_pasted_lines(sentinel)) | |
3318 |
|
3318 | |||
3319 | self._execute_block(block, par) |
|
3319 | self._execute_block(block, par) | |
3320 |
|
3320 | |||
3321 | def magic_paste(self, parameter_s=''): |
|
3321 | def magic_paste(self, parameter_s=''): | |
3322 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3322 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3323 |
|
3323 | |||
3324 | The text is pulled directly from the clipboard without user |
|
3324 | The text is pulled directly from the clipboard without user | |
3325 | intervention and printed back on the screen before execution (unless |
|
3325 | intervention and printed back on the screen before execution (unless | |
3326 | the -q flag is given to force quiet mode). |
|
3326 | the -q flag is given to force quiet mode). | |
3327 |
|
3327 | |||
3328 | The block is dedented prior to execution to enable execution of method |
|
3328 | The block is dedented prior to execution to enable execution of method | |
3329 | definitions. '>' and '+' characters at the beginning of a line are |
|
3329 | definitions. '>' and '+' characters at the beginning of a line are | |
3330 | ignored, to allow pasting directly from e-mails, diff files and |
|
3330 | ignored, to allow pasting directly from e-mails, diff files and | |
3331 | doctests (the '...' continuation prompt is also stripped). The |
|
3331 | doctests (the '...' continuation prompt is also stripped). The | |
3332 | executed block is also assigned to variable named 'pasted_block' for |
|
3332 | executed block is also assigned to variable named 'pasted_block' for | |
3333 | later editing with '%edit pasted_block'. |
|
3333 | later editing with '%edit pasted_block'. | |
3334 |
|
3334 | |||
3335 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3335 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
3336 | This assigns the pasted block to variable 'foo' as string, without |
|
3336 | This assigns the pasted block to variable 'foo' as string, without | |
3337 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3337 | dedenting or executing it (preceding >>> and + is still stripped) | |
3338 |
|
3338 | |||
3339 | Options |
|
3339 | Options | |
3340 | ------- |
|
3340 | ------- | |
3341 |
|
3341 | |||
3342 | -r: re-executes the block previously entered by cpaste. |
|
3342 | -r: re-executes the block previously entered by cpaste. | |
3343 |
|
3343 | |||
3344 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3344 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
3345 |
|
3345 | |||
3346 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3346 | IPython statements (magics, shell escapes) are not supported (yet). | |
3347 |
|
3347 | |||
3348 | See also |
|
3348 | See also | |
3349 | -------- |
|
3349 | -------- | |
3350 | cpaste: manually paste code into terminal until you mark its end. |
|
3350 | cpaste: manually paste code into terminal until you mark its end. | |
3351 | """ |
|
3351 | """ | |
3352 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3352 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
3353 | par = args.strip() |
|
3353 | par = args.strip() | |
3354 | if opts.has_key('r'): |
|
3354 | if opts.has_key('r'): | |
3355 | self._rerun_pasted() |
|
3355 | self._rerun_pasted() | |
3356 | return |
|
3356 | return | |
3357 |
|
3357 | |||
3358 | text = self.shell.hooks.clipboard_get() |
|
3358 | text = self.shell.hooks.clipboard_get() | |
3359 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3359 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
3360 |
|
3360 | |||
3361 | # By default, echo back to terminal unless quiet mode is requested |
|
3361 | # By default, echo back to terminal unless quiet mode is requested | |
3362 | if not opts.has_key('q'): |
|
3362 | if not opts.has_key('q'): | |
3363 | write = self.shell.write |
|
3363 | write = self.shell.write | |
3364 | write(self.shell.pycolorize(block)) |
|
3364 | write(self.shell.pycolorize(block)) | |
3365 | if not block.endswith('\n'): |
|
3365 | if not block.endswith('\n'): | |
3366 | write('\n') |
|
3366 | write('\n') | |
3367 | write("## -- End pasted text --\n") |
|
3367 | write("## -- End pasted text --\n") | |
3368 |
|
3368 | |||
3369 | self._execute_block(block, par) |
|
3369 | self._execute_block(block, par) | |
3370 |
|
3370 | |||
3371 | def magic_quickref(self,arg): |
|
3371 | def magic_quickref(self,arg): | |
3372 | """ Show a quick reference sheet """ |
|
3372 | """ Show a quick reference sheet """ | |
3373 | import IPython.core.usage |
|
3373 | import IPython.core.usage | |
3374 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3374 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3375 |
|
3375 | |||
3376 | page(qr) |
|
3376 | page(qr) | |
3377 |
|
3377 | |||
3378 | def magic_doctest_mode(self,parameter_s=''): |
|
3378 | def magic_doctest_mode(self,parameter_s=''): | |
3379 | """Toggle doctest mode on and off. |
|
3379 | """Toggle doctest mode on and off. | |
3380 |
|
3380 | |||
3381 | This mode allows you to toggle the prompt behavior between normal |
|
3381 | This mode allows you to toggle the prompt behavior between normal | |
3382 | IPython prompts and ones that are as similar to the default IPython |
|
3382 | IPython prompts and ones that are as similar to the default IPython | |
3383 | interpreter as possible. |
|
3383 | interpreter as possible. | |
3384 |
|
3384 | |||
3385 | It also supports the pasting of code snippets that have leading '>>>' |
|
3385 | It also supports the pasting of code snippets that have leading '>>>' | |
3386 | and '...' prompts in them. This means that you can paste doctests from |
|
3386 | and '...' prompts in them. This means that you can paste doctests from | |
3387 | files or docstrings (even if they have leading whitespace), and the |
|
3387 | files or docstrings (even if they have leading whitespace), and the | |
3388 | code will execute correctly. You can then use '%history -tn' to see |
|
3388 | code will execute correctly. You can then use '%history -tn' to see | |
3389 | the translated history without line numbers; this will give you the |
|
3389 | the translated history without line numbers; this will give you the | |
3390 | input after removal of all the leading prompts and whitespace, which |
|
3390 | input after removal of all the leading prompts and whitespace, which | |
3391 | can be pasted back into an editor. |
|
3391 | can be pasted back into an editor. | |
3392 |
|
3392 | |||
3393 | With these features, you can switch into this mode easily whenever you |
|
3393 | With these features, you can switch into this mode easily whenever you | |
3394 | need to do testing and changes to doctests, without having to leave |
|
3394 | need to do testing and changes to doctests, without having to leave | |
3395 | your existing IPython session. |
|
3395 | your existing IPython session. | |
3396 | """ |
|
3396 | """ | |
3397 |
|
3397 | |||
3398 | from IPython.utils.ipstruct import Struct |
|
3398 | from IPython.utils.ipstruct import Struct | |
3399 |
|
3399 | |||
3400 | # Shorthands |
|
3400 | # Shorthands | |
3401 | shell = self.shell |
|
3401 | shell = self.shell | |
3402 | oc = shell.outputcache |
|
3402 | oc = shell.outputcache | |
3403 | meta = shell.meta |
|
3403 | meta = shell.meta | |
3404 | # dstore is a data store kept in the instance metadata bag to track any |
|
3404 | # dstore is a data store kept in the instance metadata bag to track any | |
3405 | # changes we make, so we can undo them later. |
|
3405 | # changes we make, so we can undo them later. | |
3406 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3406 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3407 | save_dstore = dstore.setdefault |
|
3407 | save_dstore = dstore.setdefault | |
3408 |
|
3408 | |||
3409 | # save a few values we'll need to recover later |
|
3409 | # save a few values we'll need to recover later | |
3410 | mode = save_dstore('mode',False) |
|
3410 | mode = save_dstore('mode',False) | |
3411 | save_dstore('rc_pprint',shell.pprint) |
|
3411 | save_dstore('rc_pprint',shell.pprint) | |
3412 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3412 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3413 | save_dstore('rc_separate_out',shell.separate_out) |
|
3413 | save_dstore('rc_separate_out',shell.separate_out) | |
3414 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3414 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3415 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3415 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3416 | save_dstore('rc_separate_in',shell.separate_in) |
|
3416 | save_dstore('rc_separate_in',shell.separate_in) | |
3417 |
|
3417 | |||
3418 | if mode == False: |
|
3418 | if mode == False: | |
3419 | # turn on |
|
3419 | # turn on | |
3420 | oc.prompt1.p_template = '>>> ' |
|
3420 | oc.prompt1.p_template = '>>> ' | |
3421 | oc.prompt2.p_template = '... ' |
|
3421 | oc.prompt2.p_template = '... ' | |
3422 | oc.prompt_out.p_template = '' |
|
3422 | oc.prompt_out.p_template = '' | |
3423 |
|
3423 | |||
3424 | # Prompt separators like plain python |
|
3424 | # Prompt separators like plain python | |
3425 | oc.input_sep = oc.prompt1.sep = '' |
|
3425 | oc.input_sep = oc.prompt1.sep = '' | |
3426 | oc.output_sep = '' |
|
3426 | oc.output_sep = '' | |
3427 | oc.output_sep2 = '' |
|
3427 | oc.output_sep2 = '' | |
3428 |
|
3428 | |||
3429 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3429 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3430 | oc.prompt_out.pad_left = False |
|
3430 | oc.prompt_out.pad_left = False | |
3431 |
|
3431 | |||
3432 | shell.pprint = False |
|
3432 | shell.pprint = False | |
3433 |
|
3433 | |||
3434 | shell.magic_xmode('Plain') |
|
3434 | shell.magic_xmode('Plain') | |
3435 |
|
3435 | |||
3436 | else: |
|
3436 | else: | |
3437 | # turn off |
|
3437 | # turn off | |
3438 | oc.prompt1.p_template = shell.prompt_in1 |
|
3438 | oc.prompt1.p_template = shell.prompt_in1 | |
3439 | oc.prompt2.p_template = shell.prompt_in2 |
|
3439 | oc.prompt2.p_template = shell.prompt_in2 | |
3440 | oc.prompt_out.p_template = shell.prompt_out |
|
3440 | oc.prompt_out.p_template = shell.prompt_out | |
3441 |
|
3441 | |||
3442 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3442 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3443 |
|
3443 | |||
3444 | oc.output_sep = dstore.rc_separate_out |
|
3444 | oc.output_sep = dstore.rc_separate_out | |
3445 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3445 | oc.output_sep2 = dstore.rc_separate_out2 | |
3446 |
|
3446 | |||
3447 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3447 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3448 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3448 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3449 |
|
3449 | |||
3450 | shell.pprint = dstore.rc_pprint |
|
3450 | shell.pprint = dstore.rc_pprint | |
3451 |
|
3451 | |||
3452 | shell.magic_xmode(dstore.xmode) |
|
3452 | shell.magic_xmode(dstore.xmode) | |
3453 |
|
3453 | |||
3454 | # Store new mode and inform |
|
3454 | # Store new mode and inform | |
3455 | dstore.mode = bool(1-int(mode)) |
|
3455 | dstore.mode = bool(1-int(mode)) | |
3456 | print 'Doctest mode is:', |
|
3456 | print 'Doctest mode is:', | |
3457 | print ['OFF','ON'][dstore.mode] |
|
3457 | print ['OFF','ON'][dstore.mode] | |
3458 |
|
3458 | |||
3459 | def magic_gui(self, parameter_s=''): |
|
3459 | def magic_gui(self, parameter_s=''): | |
3460 | """Enable or disable IPython GUI event loop integration. |
|
3460 | """Enable or disable IPython GUI event loop integration. | |
3461 |
|
3461 | |||
3462 | %gui [-a] [GUINAME] |
|
3462 | %gui [-a] [GUINAME] | |
3463 |
|
3463 | |||
3464 | This magic replaces IPython's threaded shells that were activated |
|
3464 | This magic replaces IPython's threaded shells that were activated | |
3465 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3465 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3466 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3466 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3467 | interrupts should work without any problems. The following toolkits |
|
3467 | interrupts should work without any problems. The following toolkits | |
3468 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3468 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3469 |
|
3469 | |||
3470 | %gui wx # enable wxPython event loop integration |
|
3470 | %gui wx # enable wxPython event loop integration | |
3471 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3471 | %gui qt4|qt # enable PyQt4 event loop integration | |
3472 | %gui gtk # enable PyGTK event loop integration |
|
3472 | %gui gtk # enable PyGTK event loop integration | |
3473 | %gui tk # enable Tk event loop integration |
|
3473 | %gui tk # enable Tk event loop integration | |
3474 | %gui # disable all event loop integration |
|
3474 | %gui # disable all event loop integration | |
3475 |
|
3475 | |||
3476 | WARNING: after any of these has been called you can simply create |
|
3476 | WARNING: after any of these has been called you can simply create | |
3477 | an application object, but DO NOT start the event loop yourself, as |
|
3477 | an application object, but DO NOT start the event loop yourself, as | |
3478 | we have already handled that. |
|
3478 | we have already handled that. | |
3479 |
|
3479 | |||
3480 | If you want us to create an appropriate application object add the |
|
3480 | If you want us to create an appropriate application object add the | |
3481 | "-a" flag to your command:: |
|
3481 | "-a" flag to your command:: | |
3482 |
|
3482 | |||
3483 | %gui -a wx |
|
3483 | %gui -a wx | |
3484 |
|
3484 | |||
3485 | This is highly recommended for most users. |
|
3485 | This is highly recommended for most users. | |
3486 | """ |
|
3486 | """ | |
3487 | opts, arg = self.parse_options(parameter_s,'a') |
|
3487 | opts, arg = self.parse_options(parameter_s,'a') | |
3488 | if arg=='': arg = None |
|
3488 | if arg=='': arg = None | |
3489 | return enable_gui(arg, 'a' in opts) |
|
3489 | return enable_gui(arg, 'a' in opts) | |
3490 |
|
3490 | |||
3491 | def magic_load_ext(self, module_str): |
|
3491 | def magic_load_ext(self, module_str): | |
3492 | """Load an IPython extension by its module name.""" |
|
3492 | """Load an IPython extension by its module name.""" | |
3493 | return self.load_extension(module_str) |
|
3493 | return self.load_extension(module_str) | |
3494 |
|
3494 | |||
3495 | def magic_unload_ext(self, module_str): |
|
3495 | def magic_unload_ext(self, module_str): | |
3496 | """Unload an IPython extension by its module name.""" |
|
3496 | """Unload an IPython extension by its module name.""" | |
3497 | self.unload_extension(module_str) |
|
3497 | self.unload_extension(module_str) | |
3498 |
|
3498 | |||
3499 | def magic_reload_ext(self, module_str): |
|
3499 | def magic_reload_ext(self, module_str): | |
3500 | """Reload an IPython extension by its module name.""" |
|
3500 | """Reload an IPython extension by its module name.""" | |
3501 | self.reload_extension(module_str) |
|
3501 | self.reload_extension(module_str) | |
3502 |
|
3502 | |||
3503 | @testdec.skip_doctest |
|
3503 | @testdec.skip_doctest | |
3504 | def magic_install_profiles(self, s): |
|
3504 | def magic_install_profiles(self, s): | |
3505 | """Install the default IPython profiles into the .ipython dir. |
|
3505 | """Install the default IPython profiles into the .ipython dir. | |
3506 |
|
3506 | |||
3507 | If the default profiles have already been installed, they will not |
|
3507 | If the default profiles have already been installed, they will not | |
3508 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3508 | be overwritten. You can force overwriting them by using the ``-o`` | |
3509 | option:: |
|
3509 | option:: | |
3510 |
|
3510 | |||
3511 | In [1]: %install_profiles -o |
|
3511 | In [1]: %install_profiles -o | |
3512 | """ |
|
3512 | """ | |
3513 | if '-o' in s: |
|
3513 | if '-o' in s: | |
3514 | overwrite = True |
|
3514 | overwrite = True | |
3515 | else: |
|
3515 | else: | |
3516 | overwrite = False |
|
3516 | overwrite = False | |
3517 | from IPython.config import profile |
|
3517 | from IPython.config import profile | |
3518 | profile_dir = os.path.split(profile.__file__)[0] |
|
3518 | profile_dir = os.path.split(profile.__file__)[0] | |
3519 | ipython_dir = self.ipython_dir |
|
3519 | ipython_dir = self.ipython_dir | |
3520 | files = os.listdir(profile_dir) |
|
3520 | files = os.listdir(profile_dir) | |
3521 |
|
3521 | |||
3522 | to_install = [] |
|
3522 | to_install = [] | |
3523 | for f in files: |
|
3523 | for f in files: | |
3524 | if f.startswith('ipython_config'): |
|
3524 | if f.startswith('ipython_config'): | |
3525 | src = os.path.join(profile_dir, f) |
|
3525 | src = os.path.join(profile_dir, f) | |
3526 | dst = os.path.join(ipython_dir, f) |
|
3526 | dst = os.path.join(ipython_dir, f) | |
3527 | if (not os.path.isfile(dst)) or overwrite: |
|
3527 | if (not os.path.isfile(dst)) or overwrite: | |
3528 | to_install.append((f, src, dst)) |
|
3528 | to_install.append((f, src, dst)) | |
3529 | if len(to_install)>0: |
|
3529 | if len(to_install)>0: | |
3530 | print "Installing profiles to: ", ipython_dir |
|
3530 | print "Installing profiles to: ", ipython_dir | |
3531 | for (f, src, dst) in to_install: |
|
3531 | for (f, src, dst) in to_install: | |
3532 | shutil.copy(src, dst) |
|
3532 | shutil.copy(src, dst) | |
3533 | print " %s" % f |
|
3533 | print " %s" % f | |
3534 |
|
3534 | |||
3535 | def magic_install_default_config(self, s): |
|
3535 | def magic_install_default_config(self, s): | |
3536 | """Install IPython's default config file into the .ipython dir. |
|
3536 | """Install IPython's default config file into the .ipython dir. | |
3537 |
|
3537 | |||
3538 | If the default config file (:file:`ipython_config.py`) is already |
|
3538 | If the default config file (:file:`ipython_config.py`) is already | |
3539 | installed, it will not be overwritten. You can force overwriting |
|
3539 | installed, it will not be overwritten. You can force overwriting | |
3540 | by using the ``-o`` option:: |
|
3540 | by using the ``-o`` option:: | |
3541 |
|
3541 | |||
3542 | In [1]: %install_default_config |
|
3542 | In [1]: %install_default_config | |
3543 | """ |
|
3543 | """ | |
3544 | if '-o' in s: |
|
3544 | if '-o' in s: | |
3545 | overwrite = True |
|
3545 | overwrite = True | |
3546 | else: |
|
3546 | else: | |
3547 | overwrite = False |
|
3547 | overwrite = False | |
3548 | from IPython.config import default |
|
3548 | from IPython.config import default | |
3549 | config_dir = os.path.split(default.__file__)[0] |
|
3549 | config_dir = os.path.split(default.__file__)[0] | |
3550 | ipython_dir = self.ipython_dir |
|
3550 | ipython_dir = self.ipython_dir | |
3551 | default_config_file_name = 'ipython_config.py' |
|
3551 | default_config_file_name = 'ipython_config.py' | |
3552 | src = os.path.join(config_dir, default_config_file_name) |
|
3552 | src = os.path.join(config_dir, default_config_file_name) | |
3553 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3553 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3554 | if (not os.path.isfile(dst)) or overwrite: |
|
3554 | if (not os.path.isfile(dst)) or overwrite: | |
3555 | shutil.copy(src, dst) |
|
3555 | shutil.copy(src, dst) | |
3556 | print "Installing default config file: %s" % dst |
|
3556 | print "Installing default config file: %s" % dst | |
3557 |
|
3557 | |||
3558 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3558 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3559 | # handling and modify slightly %run |
|
3559 | # handling and modify slightly %run | |
3560 |
|
3560 | |||
3561 | @testdec.skip_doctest |
|
3561 | @testdec.skip_doctest | |
3562 | def _pylab_magic_run(self, parameter_s=''): |
|
3562 | def _pylab_magic_run(self, parameter_s=''): | |
3563 | Magic.magic_run(self, parameter_s, |
|
3563 | Magic.magic_run(self, parameter_s, | |
3564 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3564 | runner=mpl_runner(self.shell.safe_execfile)) | |
3565 |
|
3565 | |||
3566 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3566 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3567 |
|
3567 | |||
3568 | @testdec.skip_doctest |
|
3568 | @testdec.skip_doctest | |
3569 | def magic_pylab(self, s): |
|
3569 | def magic_pylab(self, s): | |
3570 | """Load numpy and matplotlib to work interactively. |
|
3570 | """Load numpy and matplotlib to work interactively. | |
3571 |
|
3571 | |||
3572 | %pylab [GUINAME] |
|
3572 | %pylab [GUINAME] | |
3573 |
|
3573 | |||
3574 | This function lets you activate pylab (matplotlib, numpy and |
|
3574 | This function lets you activate pylab (matplotlib, numpy and | |
3575 | interactive support) at any point during an IPython session. |
|
3575 | interactive support) at any point during an IPython session. | |
3576 |
|
3576 | |||
3577 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3577 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3578 | pylab and mlab, as well as all names from numpy and pylab. |
|
3578 | pylab and mlab, as well as all names from numpy and pylab. | |
3579 |
|
3579 | |||
3580 | Parameters |
|
3580 | Parameters | |
3581 | ---------- |
|
3581 | ---------- | |
3582 | guiname : optional |
|
3582 | guiname : optional | |
3583 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3583 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3584 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3584 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3585 | otherwise matplotlib's default (which you can override in your |
|
3585 | otherwise matplotlib's default (which you can override in your | |
3586 | matplotlib config file) is used. |
|
3586 | matplotlib config file) is used. | |
3587 |
|
3587 | |||
3588 | Examples |
|
3588 | Examples | |
3589 | -------- |
|
3589 | -------- | |
3590 | In this case, where the MPL default is TkAgg: |
|
3590 | In this case, where the MPL default is TkAgg: | |
3591 | In [2]: %pylab |
|
3591 | In [2]: %pylab | |
3592 |
|
3592 | |||
3593 | Welcome to pylab, a matplotlib-based Python environment. |
|
3593 | Welcome to pylab, a matplotlib-based Python environment. | |
3594 | Backend in use: TkAgg |
|
3594 | Backend in use: TkAgg | |
3595 | For more information, type 'help(pylab)'. |
|
3595 | For more information, type 'help(pylab)'. | |
3596 |
|
3596 | |||
3597 | But you can explicitly request a different backend: |
|
3597 | But you can explicitly request a different backend: | |
3598 | In [3]: %pylab qt |
|
3598 | In [3]: %pylab qt | |
3599 |
|
3599 | |||
3600 | Welcome to pylab, a matplotlib-based Python environment. |
|
3600 | Welcome to pylab, a matplotlib-based Python environment. | |
3601 | Backend in use: Qt4Agg |
|
3601 | Backend in use: Qt4Agg | |
3602 | For more information, type 'help(pylab)'. |
|
3602 | For more information, type 'help(pylab)'. | |
3603 | """ |
|
3603 | """ | |
3604 | self.shell.enable_pylab(s) |
|
3604 | self.shell.enable_pylab(s) | |
3605 |
|
3605 | |||
|
3606 | def magic_tb(self, s): | |||
|
3607 | """Print the last traceback with the currently active exception mode. | |||
|
3608 | ||||
|
3609 | See %xmode for changing exception reporting modes.""" | |||
|
3610 | self.shell.showtraceback() | |||
|
3611 | ||||
3606 | # end Magic |
|
3612 | # end Magic |
@@ -1,75 +1,245 b'' | |||||
1 | """Tests for the key iplib module, where the main ipython class is defined. |
|
1 | """Tests for the key iplib module, where the main ipython class is defined. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Module imports |
|
4 | # Module imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 |
|
6 | |||
7 | # stdlib |
|
7 | # stdlib | |
8 | import os |
|
8 | import os | |
9 | import shutil |
|
9 | import shutil | |
10 | import tempfile |
|
10 | import tempfile | |
11 |
|
11 | |||
12 | # third party |
|
12 | # third party | |
13 | import nose.tools as nt |
|
13 | import nose.tools as nt | |
14 |
|
14 | |||
15 | # our own packages |
|
15 | # our own packages | |
16 | from IPython.core import iplib |
|
|||
17 | from IPython.core import ipapi |
|
|||
18 | from IPython.testing import decorators as dec |
|
16 | from IPython.testing import decorators as dec | |
|
17 | from IPython.testing.globalipapp import get_ipython | |||
19 |
|
18 | |||
20 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
21 | # Globals |
|
20 | # Globals | |
22 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
23 |
|
22 | |||
24 | # Useful global ipapi object and main IPython one. Unfortunately we have a |
|
23 | # Get the public instance of IPython | |
25 | # long precedent of carrying the 'ipapi' global object which is injected into |
|
24 | ip = get_ipython() | |
26 | # the system namespace as _ip, but that keeps a pointer to the actual IPython |
|
|||
27 | # InteractiveShell instance, which is named IP. Since in testing we do need |
|
|||
28 | # access to the real thing (we want to probe beyond what ipapi exposes), make |
|
|||
29 | # here a global reference to each. In general, things that are exposed by the |
|
|||
30 | # ipapi instance should be read from there, but we also will often need to use |
|
|||
31 | # the actual IPython one. |
|
|||
32 |
|
||||
33 | # Get the public instance of IPython, and if it's None, make one so we can use |
|
|||
34 | # it for testing |
|
|||
35 | ip = ipapi.get() |
|
|||
36 | if ip is None: |
|
|||
37 | # IPython not running yet, make one from the testing machinery for |
|
|||
38 | # consistency when the test suite is being run via iptest |
|
|||
39 | from IPython.testing.plugin import ipdoctest |
|
|||
40 | ip = ipapi.get() |
|
|||
41 |
|
25 | |||
42 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
43 | # Test functions |
|
27 | # Test functions | |
44 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
45 |
|
29 | |||
46 | @dec.parametric |
|
30 | @dec.parametric | |
47 | def test_reset(): |
|
31 | def test_reset(): | |
48 | """reset must clear most namespaces.""" |
|
32 | """reset must clear most namespaces.""" | |
49 | # The number of variables in the private user_config_ns is not zero, but it |
|
33 | # The number of variables in the private user_config_ns is not zero, but it | |
50 | # should be constant regardless of what we do |
|
34 | # should be constant regardless of what we do | |
51 | nvars_config_ns = len(ip.user_config_ns) |
|
35 | nvars_config_ns = len(ip.user_config_ns) | |
52 |
|
36 | |||
53 | # Check that reset runs without error |
|
37 | # Check that reset runs without error | |
54 | ip.reset() |
|
38 | ip.reset() | |
55 |
|
39 | |||
56 | # Once we've reset it (to clear of any junk that might have been there from |
|
40 | # Once we've reset it (to clear of any junk that might have been there from | |
57 | # other tests, we can count how many variables are in the user's namespace |
|
41 | # other tests, we can count how many variables are in the user's namespace | |
58 | nvars_user_ns = len(ip.user_ns) |
|
42 | nvars_user_ns = len(ip.user_ns) | |
59 |
|
43 | |||
60 | # Now add a few variables to user_ns, and check that reset clears them |
|
44 | # Now add a few variables to user_ns, and check that reset clears them | |
61 | ip.user_ns['x'] = 1 |
|
45 | ip.user_ns['x'] = 1 | |
62 | ip.user_ns['y'] = 1 |
|
46 | ip.user_ns['y'] = 1 | |
63 | ip.reset() |
|
47 | ip.reset() | |
64 |
|
48 | |||
65 | # Finally, check that all namespaces have only as many variables as we |
|
49 | # Finally, check that all namespaces have only as many variables as we | |
66 | # expect to find in them: |
|
50 | # expect to find in them: | |
67 | for ns in ip.ns_refs_table: |
|
51 | for ns in ip.ns_refs_table: | |
68 | if ns is ip.user_ns: |
|
52 | if ns is ip.user_ns: | |
69 | nvars_expected = nvars_user_ns |
|
53 | nvars_expected = nvars_user_ns | |
70 | elif ns is ip.user_config_ns: |
|
54 | elif ns is ip.user_config_ns: | |
71 | nvars_expected = nvars_config_ns |
|
55 | nvars_expected = nvars_config_ns | |
72 | else: |
|
56 | else: | |
73 | nvars_expected = 0 |
|
57 | nvars_expected = 0 | |
74 |
|
58 | |||
75 | yield nt.assert_equals(len(ns), nvars_expected) |
|
59 | yield nt.assert_equals(len(ns), nvars_expected) | |
|
60 | ||||
|
61 | ||||
|
62 | # Tests for reporting of exceptions in various modes, handling of SystemExit, | |||
|
63 | # and %tb functionality. This is really a mix of testing ultraTB and iplib. | |||
|
64 | ||||
|
65 | def doctest_tb_plain(): | |||
|
66 | """ | |||
|
67 | In [18]: xmode plain | |||
|
68 | Exception reporting mode: Plain | |||
|
69 | ||||
|
70 | In [19]: run simpleerr.py | |||
|
71 | Traceback (most recent call last): | |||
|
72 | ...line 32, in <module> | |||
|
73 | bar(mode) | |||
|
74 | ...line 16, in bar | |||
|
75 | div0() | |||
|
76 | ...line 8, in div0 | |||
|
77 | x/y | |||
|
78 | ZeroDivisionError: integer division or modulo by zero | |||
|
79 | """ | |||
|
80 | ||||
|
81 | ||||
|
82 | def doctest_tb_context(): | |||
|
83 | """ | |||
|
84 | In [3]: xmode context | |||
|
85 | Exception reporting mode: Context | |||
|
86 | ||||
|
87 | In [4]: run simpleerr.py | |||
|
88 | --------------------------------------------------------------------------- | |||
|
89 | ZeroDivisionError Traceback (most recent call last) | |||
|
90 | <BLANKLINE> | |||
|
91 | ... in <module>() | |||
|
92 | 30 mode = 'div' | |||
|
93 | 31 | |||
|
94 | ---> 32 bar(mode) | |||
|
95 | 33 | |||
|
96 | 34 | |||
|
97 | <BLANKLINE> | |||
|
98 | ... in bar(mode) | |||
|
99 | 14 "bar" | |||
|
100 | 15 if mode=='div': | |||
|
101 | ---> 16 div0() | |||
|
102 | 17 elif mode=='exit': | |||
|
103 | 18 try: | |||
|
104 | <BLANKLINE> | |||
|
105 | ... in div0() | |||
|
106 | 6 x = 1 | |||
|
107 | 7 y = 0 | |||
|
108 | ----> 8 x/y | |||
|
109 | 9 | |||
|
110 | 10 def sysexit(stat, mode): | |||
|
111 | <BLANKLINE> | |||
|
112 | ZeroDivisionError: integer division or modulo by zero | |||
|
113 | """ | |||
|
114 | ||||
|
115 | ||||
|
116 | def doctest_tb_verbose(): | |||
|
117 | """ | |||
|
118 | In [5]: xmode verbose | |||
|
119 | Exception reporting mode: Verbose | |||
|
120 | ||||
|
121 | In [6]: run simpleerr.py | |||
|
122 | --------------------------------------------------------------------------- | |||
|
123 | ZeroDivisionError Traceback (most recent call last) | |||
|
124 | <BLANKLINE> | |||
|
125 | ... in <module>() | |||
|
126 | 30 mode = 'div' | |||
|
127 | 31 | |||
|
128 | ---> 32 bar(mode) | |||
|
129 | global bar = <function bar at ...> | |||
|
130 | global mode = 'div' | |||
|
131 | 33 | |||
|
132 | 34 | |||
|
133 | <BLANKLINE> | |||
|
134 | ... in bar(mode='div') | |||
|
135 | 14 "bar" | |||
|
136 | 15 if mode=='div': | |||
|
137 | ---> 16 div0() | |||
|
138 | global div0 = <function div0 at ...> | |||
|
139 | 17 elif mode=='exit': | |||
|
140 | 18 try: | |||
|
141 | <BLANKLINE> | |||
|
142 | ... in div0() | |||
|
143 | 6 x = 1 | |||
|
144 | 7 y = 0 | |||
|
145 | ----> 8 x/y | |||
|
146 | x = 1 | |||
|
147 | y = 0 | |||
|
148 | 9 | |||
|
149 | 10 def sysexit(stat, mode): | |||
|
150 | <BLANKLINE> | |||
|
151 | ZeroDivisionError: integer division or modulo by zero | |||
|
152 | """ | |||
|
153 | ||||
|
154 | ||||
|
155 | def doctest_tb_sysexit(): | |||
|
156 | """ | |||
|
157 | In [17]: %xmode plain | |||
|
158 | Exception reporting mode: Plain | |||
|
159 | ||||
|
160 | In [18]: %run simpleerr.py exit | |||
|
161 | An exception has occurred, use %tb to see the full traceback. | |||
|
162 | SystemExit: (1, 'Mode = exit') | |||
|
163 | ||||
|
164 | In [19]: %run simpleerr.py exit 2 | |||
|
165 | An exception has occurred, use %tb to see the full traceback. | |||
|
166 | SystemExit: (2, 'Mode = exit') | |||
|
167 | ||||
|
168 | In [20]: %tb | |||
|
169 | Traceback (most recent call last): | |||
|
170 | File ... in <module> | |||
|
171 | bar(mode) | |||
|
172 | File ... line 22, in bar | |||
|
173 | sysexit(stat, mode) | |||
|
174 | File ... line 11, in sysexit | |||
|
175 | raise SystemExit(stat, 'Mode = %s' % mode) | |||
|
176 | SystemExit: (2, 'Mode = exit') | |||
|
177 | ||||
|
178 | In [21]: %xmode context | |||
|
179 | Exception reporting mode: Context | |||
|
180 | ||||
|
181 | In [22]: %tb | |||
|
182 | --------------------------------------------------------------------------- | |||
|
183 | SystemExit Traceback (most recent call last) | |||
|
184 | <BLANKLINE> | |||
|
185 | ...<module>() | |||
|
186 | 30 mode = 'div' | |||
|
187 | 31 | |||
|
188 | ---> 32 bar(mode) | |||
|
189 | 33 | |||
|
190 | 34 | |||
|
191 | <BLANKLINE> | |||
|
192 | ...bar(mode) | |||
|
193 | 20 except: | |||
|
194 | 21 stat = 1 | |||
|
195 | ---> 22 sysexit(stat, mode) | |||
|
196 | 23 else: | |||
|
197 | 24 raise ValueError('Unknown mode') | |||
|
198 | <BLANKLINE> | |||
|
199 | ...sysexit(stat, mode) | |||
|
200 | 9 | |||
|
201 | 10 def sysexit(stat, mode): | |||
|
202 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |||
|
203 | 12 | |||
|
204 | 13 def bar(mode): | |||
|
205 | <BLANKLINE> | |||
|
206 | SystemExit: (2, 'Mode = exit') | |||
|
207 | ||||
|
208 | In [23]: %xmode verbose | |||
|
209 | Exception reporting mode: Verbose | |||
|
210 | ||||
|
211 | In [24]: %tb | |||
|
212 | --------------------------------------------------------------------------- | |||
|
213 | SystemExit Traceback (most recent call last) | |||
|
214 | <BLANKLINE> | |||
|
215 | ... in <module>() | |||
|
216 | 30 mode = 'div' | |||
|
217 | 31 | |||
|
218 | ---> 32 bar(mode) | |||
|
219 | global bar = <function bar at ...> | |||
|
220 | global mode = 'exit' | |||
|
221 | 33 | |||
|
222 | 34 | |||
|
223 | <BLANKLINE> | |||
|
224 | ... in bar(mode='exit') | |||
|
225 | 20 except: | |||
|
226 | 21 stat = 1 | |||
|
227 | ---> 22 sysexit(stat, mode) | |||
|
228 | global sysexit = <function sysexit at ...> | |||
|
229 | stat = 2 | |||
|
230 | mode = 'exit' | |||
|
231 | 23 else: | |||
|
232 | 24 raise ValueError('Unknown mode') | |||
|
233 | <BLANKLINE> | |||
|
234 | ... in sysexit(stat=2, mode='exit') | |||
|
235 | 9 | |||
|
236 | 10 def sysexit(stat, mode): | |||
|
237 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |||
|
238 | global SystemExit = undefined | |||
|
239 | stat = 2 | |||
|
240 | mode = 'exit' | |||
|
241 | 12 | |||
|
242 | 13 def bar(mode): | |||
|
243 | <BLANKLINE> | |||
|
244 | SystemExit: (2, 'Mode = exit') | |||
|
245 | """ |
@@ -1,1062 +1,1098 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | ultratb.py -- Spice up your tracebacks! |
|
3 | ultratb.py -- Spice up your tracebacks! | |
4 |
|
4 | |||
5 | * ColorTB |
|
5 | * ColorTB | |
6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
6 | I've always found it a bit hard to visually parse tracebacks in Python. The | |
7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
7 | ColorTB class is a solution to that problem. It colors the different parts of a | |
8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
8 | traceback in a manner similar to what you would expect from a syntax-highlighting | |
9 | text editor. |
|
9 | text editor. | |
10 |
|
10 | |||
11 | Installation instructions for ColorTB: |
|
11 | Installation instructions for ColorTB: | |
12 | import sys,ultratb |
|
12 | import sys,ultratb | |
13 | sys.excepthook = ultratb.ColorTB() |
|
13 | sys.excepthook = ultratb.ColorTB() | |
14 |
|
14 | |||
15 | * VerboseTB |
|
15 | * VerboseTB | |
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | |
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
17 | of useful info when a traceback occurs. Ping originally had it spit out HTML | |
18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
18 | and intended it for CGI programmers, but why should they have all the fun? I | |
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, | |
20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
20 | but kind of neat, and maybe useful for long-running programs that you believe | |
21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
21 | are bug-free. If a crash *does* occur in that type of program you want details. | |
22 | Give it a shot--you'll love it or you'll hate it. |
|
22 | Give it a shot--you'll love it or you'll hate it. | |
23 |
|
23 | |||
24 | Note: |
|
24 | Note: | |
25 |
|
25 | |||
26 | The Verbose mode prints the variables currently visible where the exception |
|
26 | The Verbose mode prints the variables currently visible where the exception | |
27 | happened (shortening their strings if too long). This can potentially be |
|
27 | happened (shortening their strings if too long). This can potentially be | |
28 | very slow, if you happen to have a huge data structure whose string |
|
28 | very slow, if you happen to have a huge data structure whose string | |
29 | representation is complex to compute. Your computer may appear to freeze for |
|
29 | representation is complex to compute. Your computer may appear to freeze for | |
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback | |
31 | with Ctrl-C (maybe hitting it more than once). |
|
31 | with Ctrl-C (maybe hitting it more than once). | |
32 |
|
32 | |||
33 | If you encounter this kind of situation often, you may want to use the |
|
33 | If you encounter this kind of situation often, you may want to use the | |
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting | |
35 | variables (but otherwise includes the information and context given by |
|
35 | variables (but otherwise includes the information and context given by | |
36 | Verbose). |
|
36 | Verbose). | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | Installation instructions for ColorTB: |
|
39 | Installation instructions for ColorTB: | |
40 | import sys,ultratb |
|
40 | import sys,ultratb | |
41 | sys.excepthook = ultratb.VerboseTB() |
|
41 | sys.excepthook = ultratb.VerboseTB() | |
42 |
|
42 | |||
43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
43 | Note: Much of the code in this module was lifted verbatim from the standard | |
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | |
45 |
|
45 | |||
46 | * Color schemes |
|
46 | * Color schemes | |
47 | The colors are defined in the class TBTools through the use of the |
|
47 | The colors are defined in the class TBTools through the use of the | |
48 | ColorSchemeTable class. Currently the following exist: |
|
48 | ColorSchemeTable class. Currently the following exist: | |
49 |
|
49 | |||
50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
50 | - NoColor: allows all of this module to be used in any terminal (the color | |
51 | escapes are just dummy blank strings). |
|
51 | escapes are just dummy blank strings). | |
52 |
|
52 | |||
53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
53 | - Linux: is meant to look good in a terminal like the Linux console (black | |
54 | or very dark background). |
|
54 | or very dark background). | |
55 |
|
55 | |||
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable | |
57 | in light background terminals. |
|
57 | in light background terminals. | |
58 |
|
58 | |||
59 | You can implement other color schemes easily, the syntax is fairly |
|
59 | You can implement other color schemes easily, the syntax is fairly | |
60 | self-explanatory. Please send back new schemes you develop to the author for |
|
60 | self-explanatory. Please send back new schemes you develop to the author for | |
61 | possible inclusion in future releases. |
|
61 | possible inclusion in future releases. | |
62 | """ |
|
62 | """ | |
63 |
|
63 | |||
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | |
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
67 | # |
|
67 | # | |
68 | # Distributed under the terms of the BSD License. The full license is in |
|
68 | # Distributed under the terms of the BSD License. The full license is in | |
69 | # the file COPYING, distributed as part of this software. |
|
69 | # the file COPYING, distributed as part of this software. | |
70 | #***************************************************************************** |
|
70 | #***************************************************************************** | |
71 |
|
71 | |||
72 | from __future__ import with_statement |
|
72 | from __future__ import with_statement | |
73 |
|
73 | |||
74 | import inspect |
|
74 | import inspect | |
75 | import keyword |
|
75 | import keyword | |
76 | import linecache |
|
76 | import linecache | |
77 | import os |
|
77 | import os | |
78 | import pydoc |
|
78 | import pydoc | |
79 | import re |
|
79 | import re | |
80 | import string |
|
80 | import string | |
81 | import sys |
|
81 | import sys | |
82 | import time |
|
82 | import time | |
83 | import tokenize |
|
83 | import tokenize | |
84 | import traceback |
|
84 | import traceback | |
85 | import types |
|
85 | import types | |
86 |
|
86 | |||
87 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
87 | # For purposes of monkeypatching inspect to fix a bug in it. | |
88 | from inspect import getsourcefile, getfile, getmodule,\ |
|
88 | from inspect import getsourcefile, getfile, getmodule,\ | |
89 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
89 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | # IPython's own modules |
|
92 | # IPython's own modules | |
93 | # Modified pdb which doesn't damage IPython's readline handling |
|
93 | # Modified pdb which doesn't damage IPython's readline handling | |
94 | from IPython.utils import PyColorize |
|
94 | from IPython.utils import PyColorize | |
95 | from IPython.core import debugger, ipapi |
|
95 | from IPython.core import debugger, ipapi | |
96 | from IPython.core.display_trap import DisplayTrap |
|
96 | from IPython.core.display_trap import DisplayTrap | |
97 | from IPython.utils.ipstruct import Struct |
|
97 | from IPython.utils.ipstruct import Struct | |
98 | from IPython.core.excolors import exception_colors |
|
98 | from IPython.core.excolors import exception_colors | |
99 | from IPython.utils.genutils import Term, uniq_stable, error, info |
|
99 | from IPython.utils.genutils import Term, uniq_stable, error, info | |
100 |
|
100 | |||
101 | # Globals |
|
101 | # Globals | |
102 | # amount of space to put line numbers before verbose tracebacks |
|
102 | # amount of space to put line numbers before verbose tracebacks | |
103 | INDENT_SIZE = 8 |
|
103 | INDENT_SIZE = 8 | |
104 |
|
104 | |||
105 | # Default color scheme. This is used, for example, by the traceback |
|
105 | # Default color scheme. This is used, for example, by the traceback | |
106 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
106 | # formatter. When running in an actual IPython instance, the user's rc.colors | |
107 | # value is used, but havinga module global makes this functionality available |
|
107 | # value is used, but havinga module global makes this functionality available | |
108 | # to users of ultratb who are NOT running inside ipython. |
|
108 | # to users of ultratb who are NOT running inside ipython. | |
109 | DEFAULT_SCHEME = 'NoColor' |
|
109 | DEFAULT_SCHEME = 'NoColor' | |
110 |
|
110 | |||
111 | #--------------------------------------------------------------------------- |
|
111 | #--------------------------------------------------------------------------- | |
112 | # Code begins |
|
112 | # Code begins | |
113 |
|
113 | |||
114 | # Utility functions |
|
114 | # Utility functions | |
115 | def inspect_error(): |
|
115 | def inspect_error(): | |
116 | """Print a message about internal inspect errors. |
|
116 | """Print a message about internal inspect errors. | |
117 |
|
117 | |||
118 | These are unfortunately quite common.""" |
|
118 | These are unfortunately quite common.""" | |
119 |
|
119 | |||
120 | error('Internal Python error in the inspect module.\n' |
|
120 | error('Internal Python error in the inspect module.\n' | |
121 | 'Below is the traceback from this internal error.\n') |
|
121 | 'Below is the traceback from this internal error.\n') | |
122 |
|
122 | |||
123 |
|
123 | |||
124 | def findsource(object): |
|
124 | def findsource(object): | |
125 | """Return the entire source file and starting line number for an object. |
|
125 | """Return the entire source file and starting line number for an object. | |
126 |
|
126 | |||
127 | The argument may be a module, class, method, function, traceback, frame, |
|
127 | The argument may be a module, class, method, function, traceback, frame, | |
128 | or code object. The source code is returned as a list of all the lines |
|
128 | or code object. The source code is returned as a list of all the lines | |
129 | in the file and the line number indexes a line in that list. An IOError |
|
129 | in the file and the line number indexes a line in that list. An IOError | |
130 | is raised if the source code cannot be retrieved. |
|
130 | is raised if the source code cannot be retrieved. | |
131 |
|
131 | |||
132 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
132 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" | |
133 |
|
133 | |||
134 | file = getsourcefile(object) or getfile(object) |
|
134 | file = getsourcefile(object) or getfile(object) | |
135 | # If the object is a frame, then trying to get the globals dict from its |
|
135 | # If the object is a frame, then trying to get the globals dict from its | |
136 | # module won't work. Instead, the frame object itself has the globals |
|
136 | # module won't work. Instead, the frame object itself has the globals | |
137 | # dictionary. |
|
137 | # dictionary. | |
138 | globals_dict = None |
|
138 | globals_dict = None | |
139 | if inspect.isframe(object): |
|
139 | if inspect.isframe(object): | |
140 | # XXX: can this ever be false? |
|
140 | # XXX: can this ever be false? | |
141 | globals_dict = object.f_globals |
|
141 | globals_dict = object.f_globals | |
142 | else: |
|
142 | else: | |
143 | module = getmodule(object, file) |
|
143 | module = getmodule(object, file) | |
144 | if module: |
|
144 | if module: | |
145 | globals_dict = module.__dict__ |
|
145 | globals_dict = module.__dict__ | |
146 | lines = linecache.getlines(file, globals_dict) |
|
146 | lines = linecache.getlines(file, globals_dict) | |
147 | if not lines: |
|
147 | if not lines: | |
148 | raise IOError('could not get source code') |
|
148 | raise IOError('could not get source code') | |
149 |
|
149 | |||
150 | if ismodule(object): |
|
150 | if ismodule(object): | |
151 | return lines, 0 |
|
151 | return lines, 0 | |
152 |
|
152 | |||
153 | if isclass(object): |
|
153 | if isclass(object): | |
154 | name = object.__name__ |
|
154 | name = object.__name__ | |
155 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
155 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') | |
156 | # make some effort to find the best matching class definition: |
|
156 | # make some effort to find the best matching class definition: | |
157 | # use the one with the least indentation, which is the one |
|
157 | # use the one with the least indentation, which is the one | |
158 | # that's most probably not inside a function definition. |
|
158 | # that's most probably not inside a function definition. | |
159 | candidates = [] |
|
159 | candidates = [] | |
160 | for i in range(len(lines)): |
|
160 | for i in range(len(lines)): | |
161 | match = pat.match(lines[i]) |
|
161 | match = pat.match(lines[i]) | |
162 | if match: |
|
162 | if match: | |
163 | # if it's at toplevel, it's already the best one |
|
163 | # if it's at toplevel, it's already the best one | |
164 | if lines[i][0] == 'c': |
|
164 | if lines[i][0] == 'c': | |
165 | return lines, i |
|
165 | return lines, i | |
166 | # else add whitespace to candidate list |
|
166 | # else add whitespace to candidate list | |
167 | candidates.append((match.group(1), i)) |
|
167 | candidates.append((match.group(1), i)) | |
168 | if candidates: |
|
168 | if candidates: | |
169 | # this will sort by whitespace, and by line number, |
|
169 | # this will sort by whitespace, and by line number, | |
170 | # less whitespace first |
|
170 | # less whitespace first | |
171 | candidates.sort() |
|
171 | candidates.sort() | |
172 | return lines, candidates[0][1] |
|
172 | return lines, candidates[0][1] | |
173 | else: |
|
173 | else: | |
174 | raise IOError('could not find class definition') |
|
174 | raise IOError('could not find class definition') | |
175 |
|
175 | |||
176 | if ismethod(object): |
|
176 | if ismethod(object): | |
177 | object = object.im_func |
|
177 | object = object.im_func | |
178 | if isfunction(object): |
|
178 | if isfunction(object): | |
179 | object = object.func_code |
|
179 | object = object.func_code | |
180 | if istraceback(object): |
|
180 | if istraceback(object): | |
181 | object = object.tb_frame |
|
181 | object = object.tb_frame | |
182 | if isframe(object): |
|
182 | if isframe(object): | |
183 | object = object.f_code |
|
183 | object = object.f_code | |
184 | if iscode(object): |
|
184 | if iscode(object): | |
185 | if not hasattr(object, 'co_firstlineno'): |
|
185 | if not hasattr(object, 'co_firstlineno'): | |
186 | raise IOError('could not find function definition') |
|
186 | raise IOError('could not find function definition') | |
187 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
187 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') | |
188 | pmatch = pat.match |
|
188 | pmatch = pat.match | |
189 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
189 | # fperez - fix: sometimes, co_firstlineno can give a number larger than | |
190 | # the length of lines, which causes an error. Safeguard against that. |
|
190 | # the length of lines, which causes an error. Safeguard against that. | |
191 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
191 | lnum = min(object.co_firstlineno,len(lines))-1 | |
192 | while lnum > 0: |
|
192 | while lnum > 0: | |
193 | if pmatch(lines[lnum]): break |
|
193 | if pmatch(lines[lnum]): break | |
194 | lnum -= 1 |
|
194 | lnum -= 1 | |
195 |
|
195 | |||
196 | return lines, lnum |
|
196 | return lines, lnum | |
197 | raise IOError('could not find code object') |
|
197 | raise IOError('could not find code object') | |
198 |
|
198 | |||
199 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
199 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 | |
200 | if sys.version_info[:2] >= (2,5): |
|
200 | if sys.version_info[:2] >= (2,5): | |
201 | inspect.findsource = findsource |
|
201 | inspect.findsource = findsource | |
202 |
|
202 | |||
203 | def fix_frame_records_filenames(records): |
|
203 | def fix_frame_records_filenames(records): | |
204 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
204 | """Try to fix the filenames in each record from inspect.getinnerframes(). | |
205 |
|
205 | |||
206 | Particularly, modules loaded from within zip files have useless filenames |
|
206 | Particularly, modules loaded from within zip files have useless filenames | |
207 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
207 | attached to their code object, and inspect.getinnerframes() just uses it. | |
208 | """ |
|
208 | """ | |
209 | fixed_records = [] |
|
209 | fixed_records = [] | |
210 | for frame, filename, line_no, func_name, lines, index in records: |
|
210 | for frame, filename, line_no, func_name, lines, index in records: | |
211 | # Look inside the frame's globals dictionary for __file__, which should |
|
211 | # Look inside the frame's globals dictionary for __file__, which should | |
212 | # be better. |
|
212 | # be better. | |
213 | better_fn = frame.f_globals.get('__file__', None) |
|
213 | better_fn = frame.f_globals.get('__file__', None) | |
214 | if isinstance(better_fn, str): |
|
214 | if isinstance(better_fn, str): | |
215 | # Check the type just in case someone did something weird with |
|
215 | # Check the type just in case someone did something weird with | |
216 | # __file__. It might also be None if the error occurred during |
|
216 | # __file__. It might also be None if the error occurred during | |
217 | # import. |
|
217 | # import. | |
218 | filename = better_fn |
|
218 | filename = better_fn | |
219 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
219 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) | |
220 | return fixed_records |
|
220 | return fixed_records | |
221 |
|
221 | |||
222 |
|
222 | |||
223 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
223 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): | |
224 | import linecache |
|
224 | import linecache | |
225 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
225 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 | |
226 |
|
226 | |||
227 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
227 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) | |
228 |
|
228 | |||
229 | # If the error is at the console, don't build any context, since it would |
|
229 | # If the error is at the console, don't build any context, since it would | |
230 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
230 | # otherwise produce 5 blank lines printed out (there is no file at the | |
231 | # console) |
|
231 | # console) | |
232 | rec_check = records[tb_offset:] |
|
232 | rec_check = records[tb_offset:] | |
233 | try: |
|
233 | try: | |
234 | rname = rec_check[0][1] |
|
234 | rname = rec_check[0][1] | |
235 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
235 | if rname == '<ipython console>' or rname.endswith('<string>'): | |
236 | return rec_check |
|
236 | return rec_check | |
237 | except IndexError: |
|
237 | except IndexError: | |
238 | pass |
|
238 | pass | |
239 |
|
239 | |||
240 | aux = traceback.extract_tb(etb) |
|
240 | aux = traceback.extract_tb(etb) | |
241 | assert len(records) == len(aux) |
|
241 | assert len(records) == len(aux) | |
242 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
242 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): | |
243 | maybeStart = lnum-1 - context//2 |
|
243 | maybeStart = lnum-1 - context//2 | |
244 | start = max(maybeStart, 0) |
|
244 | start = max(maybeStart, 0) | |
245 | end = start + context |
|
245 | end = start + context | |
246 | lines = linecache.getlines(file)[start:end] |
|
246 | lines = linecache.getlines(file)[start:end] | |
247 | # pad with empty lines if necessary |
|
247 | # pad with empty lines if necessary | |
248 | if maybeStart < 0: |
|
248 | if maybeStart < 0: | |
249 | lines = (['\n'] * -maybeStart) + lines |
|
249 | lines = (['\n'] * -maybeStart) + lines | |
250 | if len(lines) < context: |
|
250 | if len(lines) < context: | |
251 | lines += ['\n'] * (context - len(lines)) |
|
251 | lines += ['\n'] * (context - len(lines)) | |
252 | buf = list(records[i]) |
|
252 | buf = list(records[i]) | |
253 | buf[LNUM_POS] = lnum |
|
253 | buf[LNUM_POS] = lnum | |
254 | buf[INDEX_POS] = lnum - 1 - start |
|
254 | buf[INDEX_POS] = lnum - 1 - start | |
255 | buf[LINES_POS] = lines |
|
255 | buf[LINES_POS] = lines | |
256 | records[i] = tuple(buf) |
|
256 | records[i] = tuple(buf) | |
257 | return records[tb_offset:] |
|
257 | return records[tb_offset:] | |
258 |
|
258 | |||
259 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
259 | # Helper function -- largely belongs to VerboseTB, but we need the same | |
260 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
260 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | |
261 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
261 | # can be recognized properly by ipython.el's py-traceback-line-re | |
262 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
262 | # (SyntaxErrors have to be treated specially because they have no traceback) | |
263 |
|
263 | |||
264 | _parser = PyColorize.Parser() |
|
264 | _parser = PyColorize.Parser() | |
265 |
|
265 | |||
266 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
266 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): | |
267 | numbers_width = INDENT_SIZE - 1 |
|
267 | numbers_width = INDENT_SIZE - 1 | |
268 | res = [] |
|
268 | res = [] | |
269 | i = lnum - index |
|
269 | i = lnum - index | |
270 |
|
270 | |||
271 | # This lets us get fully syntax-highlighted tracebacks. |
|
271 | # This lets us get fully syntax-highlighted tracebacks. | |
272 | if scheme is None: |
|
272 | if scheme is None: | |
273 | ipinst = ipapi.get() |
|
273 | ipinst = ipapi.get() | |
274 | if ipinst is not None: |
|
274 | if ipinst is not None: | |
275 | scheme = ipinst.colors |
|
275 | scheme = ipinst.colors | |
276 | else: |
|
276 | else: | |
277 | scheme = DEFAULT_SCHEME |
|
277 | scheme = DEFAULT_SCHEME | |
278 |
|
278 | |||
279 | _line_format = _parser.format2 |
|
279 | _line_format = _parser.format2 | |
280 |
|
280 | |||
281 | for line in lines: |
|
281 | for line in lines: | |
282 | new_line, err = _line_format(line,'str',scheme) |
|
282 | new_line, err = _line_format(line,'str',scheme) | |
283 | if not err: line = new_line |
|
283 | if not err: line = new_line | |
284 |
|
284 | |||
285 | if i == lnum: |
|
285 | if i == lnum: | |
286 | # This is the line with the error |
|
286 | # This is the line with the error | |
287 | pad = numbers_width - len(str(i)) |
|
287 | pad = numbers_width - len(str(i)) | |
288 | if pad >= 3: |
|
288 | if pad >= 3: | |
289 | marker = '-'*(pad-3) + '-> ' |
|
289 | marker = '-'*(pad-3) + '-> ' | |
290 | elif pad == 2: |
|
290 | elif pad == 2: | |
291 | marker = '> ' |
|
291 | marker = '> ' | |
292 | elif pad == 1: |
|
292 | elif pad == 1: | |
293 | marker = '>' |
|
293 | marker = '>' | |
294 | else: |
|
294 | else: | |
295 | marker = '' |
|
295 | marker = '' | |
296 | num = marker + str(i) |
|
296 | num = marker + str(i) | |
297 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
297 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, | |
298 | Colors.line, line, Colors.Normal) |
|
298 | Colors.line, line, Colors.Normal) | |
299 | else: |
|
299 | else: | |
300 | num = '%*s' % (numbers_width,i) |
|
300 | num = '%*s' % (numbers_width,i) | |
301 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
301 | line = '%s%s%s %s' %(Colors.lineno, num, | |
302 | Colors.Normal, line) |
|
302 | Colors.Normal, line) | |
303 |
|
303 | |||
304 | res.append(line) |
|
304 | res.append(line) | |
305 | if lvals and i == lnum: |
|
305 | if lvals and i == lnum: | |
306 | res.append(lvals + '\n') |
|
306 | res.append(lvals + '\n') | |
307 | i = i + 1 |
|
307 | i = i + 1 | |
308 | return res |
|
308 | return res | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | #--------------------------------------------------------------------------- |
|
311 | #--------------------------------------------------------------------------- | |
312 | # Module classes |
|
312 | # Module classes | |
313 | class TBTools: |
|
313 | class TBTools: | |
314 | """Basic tools used by all traceback printer classes.""" |
|
314 | """Basic tools used by all traceback printer classes.""" | |
|
315 | #: Default output stream, can be overridden at call time. A special value | |||
|
316 | #: of 'stdout' *as a string* can be given to force extraction of sys.stdout | |||
|
317 | #: at runtime. This allows testing exception printing with doctests, that | |||
|
318 | #: swap sys.stdout just at execution time. | |||
|
319 | out_stream = sys.stderr | |||
315 |
|
320 | |||
316 | def __init__(self,color_scheme = 'NoColor',call_pdb=False): |
|
321 | def __init__(self,color_scheme = 'NoColor',call_pdb=False): | |
317 | # Whether to call the interactive pdb debugger after printing |
|
322 | # Whether to call the interactive pdb debugger after printing | |
318 | # tracebacks or not |
|
323 | # tracebacks or not | |
319 | self.call_pdb = call_pdb |
|
324 | self.call_pdb = call_pdb | |
320 |
|
325 | |||
321 | # Create color table |
|
326 | # Create color table | |
322 | self.color_scheme_table = exception_colors() |
|
327 | self.color_scheme_table = exception_colors() | |
323 |
|
328 | |||
324 | self.set_colors(color_scheme) |
|
329 | self.set_colors(color_scheme) | |
325 | self.old_scheme = color_scheme # save initial value for toggles |
|
330 | self.old_scheme = color_scheme # save initial value for toggles | |
326 |
|
331 | |||
327 | if call_pdb: |
|
332 | if call_pdb: | |
328 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
333 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) | |
329 | else: |
|
334 | else: | |
330 | self.pdb = None |
|
335 | self.pdb = None | |
331 |
|
336 | |||
332 | def set_colors(self,*args,**kw): |
|
337 | def set_colors(self,*args,**kw): | |
333 | """Shorthand access to the color table scheme selector method.""" |
|
338 | """Shorthand access to the color table scheme selector method.""" | |
334 |
|
339 | |||
335 | # Set own color table |
|
340 | # Set own color table | |
336 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
341 | self.color_scheme_table.set_active_scheme(*args,**kw) | |
337 | # for convenience, set Colors to the active scheme |
|
342 | # for convenience, set Colors to the active scheme | |
338 | self.Colors = self.color_scheme_table.active_colors |
|
343 | self.Colors = self.color_scheme_table.active_colors | |
339 | # Also set colors of debugger |
|
344 | # Also set colors of debugger | |
340 | if hasattr(self,'pdb') and self.pdb is not None: |
|
345 | if hasattr(self,'pdb') and self.pdb is not None: | |
341 | self.pdb.set_colors(*args,**kw) |
|
346 | self.pdb.set_colors(*args,**kw) | |
342 |
|
347 | |||
343 | def color_toggle(self): |
|
348 | def color_toggle(self): | |
344 | """Toggle between the currently active color scheme and NoColor.""" |
|
349 | """Toggle between the currently active color scheme and NoColor.""" | |
345 |
|
350 | |||
346 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
351 | if self.color_scheme_table.active_scheme_name == 'NoColor': | |
347 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
352 | self.color_scheme_table.set_active_scheme(self.old_scheme) | |
348 | self.Colors = self.color_scheme_table.active_colors |
|
353 | self.Colors = self.color_scheme_table.active_colors | |
349 | else: |
|
354 | else: | |
350 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
355 | self.old_scheme = self.color_scheme_table.active_scheme_name | |
351 | self.color_scheme_table.set_active_scheme('NoColor') |
|
356 | self.color_scheme_table.set_active_scheme('NoColor') | |
352 | self.Colors = self.color_scheme_table.active_colors |
|
357 | self.Colors = self.color_scheme_table.active_colors | |
353 |
|
358 | |||
354 | #--------------------------------------------------------------------------- |
|
359 | #--------------------------------------------------------------------------- | |
355 | class ListTB(TBTools): |
|
360 | class ListTB(TBTools): | |
356 | """Print traceback information from a traceback list, with optional color. |
|
361 | """Print traceback information from a traceback list, with optional color. | |
357 |
|
362 | |||
358 | Calling: requires 3 arguments: |
|
363 | Calling: requires 3 arguments: | |
359 | (etype, evalue, elist) |
|
364 | (etype, evalue, elist) | |
360 | as would be obtained by: |
|
365 | as would be obtained by: | |
361 | etype, evalue, tb = sys.exc_info() |
|
366 | etype, evalue, tb = sys.exc_info() | |
362 | if tb: |
|
367 | if tb: | |
363 | elist = traceback.extract_tb(tb) |
|
368 | elist = traceback.extract_tb(tb) | |
364 | else: |
|
369 | else: | |
365 | elist = None |
|
370 | elist = None | |
366 |
|
371 | |||
367 | It can thus be used by programs which need to process the traceback before |
|
372 | It can thus be used by programs which need to process the traceback before | |
368 | printing (such as console replacements based on the code module from the |
|
373 | printing (such as console replacements based on the code module from the | |
369 | standard library). |
|
374 | standard library). | |
370 |
|
375 | |||
371 | Because they are meant to be called without a full traceback (only a |
|
376 | Because they are meant to be called without a full traceback (only a | |
372 | list), instances of this class can't call the interactive pdb debugger.""" |
|
377 | list), instances of this class can't call the interactive pdb debugger.""" | |
373 |
|
378 | |||
374 | def __init__(self,color_scheme = 'NoColor'): |
|
379 | def __init__(self,color_scheme = 'NoColor'): | |
375 | TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0) |
|
380 | TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0) | |
376 |
|
381 | |||
377 | def __call__(self, etype, value, elist): |
|
382 | def __call__(self, etype, value, elist): | |
378 | Term.cout.flush() |
|
383 | Term.cout.flush() | |
379 | print >> Term.cerr, self.text(etype,value,elist) |
|
384 | print >> Term.cerr, self.text(etype,value,elist) | |
380 | Term.cerr.flush() |
|
385 | Term.cerr.flush() | |
381 |
|
386 | |||
382 | def text(self,etype, value, elist,context=5): |
|
387 | def text(self, etype, value, elist, context=5): | |
383 |
"""Return a color formatted string with the traceback info. |
|
388 | """Return a color formatted string with the traceback info. | |
|
389 | ||||
|
390 | Parameters | |||
|
391 | ---------- | |||
|
392 | etype : exception type | |||
|
393 | Type of the exception raised. | |||
|
394 | ||||
|
395 | value : object | |||
|
396 | Data stored in the exception | |||
|
397 | ||||
|
398 | elist : list | |||
|
399 | List of frames, see class docstring for details. | |||
|
400 | ||||
|
401 | Returns | |||
|
402 | ------- | |||
|
403 | String with formatted exception. | |||
|
404 | """ | |||
384 |
|
405 | |||
385 | Colors = self.Colors |
|
406 | Colors = self.Colors | |
386 | out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)] |
|
407 | out_string = [] | |
387 | if elist: |
|
408 | if elist: | |
388 |
out_string.append('Traceback %s(most recent call last)%s:' % |
|
409 | out_string.append('Traceback %s(most recent call last)%s:' % | |
389 | (Colors.normalEm, Colors.Normal) + '\n') |
|
410 | (Colors.normalEm, Colors.Normal) + '\n') | |
390 | out_string.extend(self._format_list(elist)) |
|
411 | out_string.extend(self._format_list(elist)) | |
391 | lines = self._format_exception_only(etype, value) |
|
412 | lines = self._format_exception_only(etype, value) | |
392 | for line in lines[:-1]: |
|
413 | for line in lines[:-1]: | |
393 | out_string.append(" "+line) |
|
414 | out_string.append(" "+line) | |
394 | out_string.append(lines[-1]) |
|
415 | out_string.append(lines[-1]) | |
395 | return ''.join(out_string) |
|
416 | return ''.join(out_string) | |
396 |
|
417 | |||
397 | def _format_list(self, extracted_list): |
|
418 | def _format_list(self, extracted_list): | |
398 | """Format a list of traceback entry tuples for printing. |
|
419 | """Format a list of traceback entry tuples for printing. | |
399 |
|
420 | |||
400 | Given a list of tuples as returned by extract_tb() or |
|
421 | Given a list of tuples as returned by extract_tb() or | |
401 | extract_stack(), return a list of strings ready for printing. |
|
422 | extract_stack(), return a list of strings ready for printing. | |
402 | Each string in the resulting list corresponds to the item with the |
|
423 | Each string in the resulting list corresponds to the item with the | |
403 | same index in the argument list. Each string ends in a newline; |
|
424 | same index in the argument list. Each string ends in a newline; | |
404 | the strings may contain internal newlines as well, for those items |
|
425 | the strings may contain internal newlines as well, for those items | |
405 | whose source text line is not None. |
|
426 | whose source text line is not None. | |
406 |
|
427 | |||
407 | Lifted almost verbatim from traceback.py |
|
428 | Lifted almost verbatim from traceback.py | |
408 | """ |
|
429 | """ | |
409 |
|
430 | |||
410 | Colors = self.Colors |
|
431 | Colors = self.Colors | |
411 | list = [] |
|
432 | list = [] | |
412 | for filename, lineno, name, line in extracted_list[:-1]: |
|
433 | for filename, lineno, name, line in extracted_list[:-1]: | |
413 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
434 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ | |
414 | (Colors.filename, filename, Colors.Normal, |
|
435 | (Colors.filename, filename, Colors.Normal, | |
415 | Colors.lineno, lineno, Colors.Normal, |
|
436 | Colors.lineno, lineno, Colors.Normal, | |
416 | Colors.name, name, Colors.Normal) |
|
437 | Colors.name, name, Colors.Normal) | |
417 | if line: |
|
438 | if line: | |
418 | item = item + ' %s\n' % line.strip() |
|
439 | item = item + ' %s\n' % line.strip() | |
419 | list.append(item) |
|
440 | list.append(item) | |
420 | # Emphasize the last entry |
|
441 | # Emphasize the last entry | |
421 | filename, lineno, name, line = extracted_list[-1] |
|
442 | filename, lineno, name, line = extracted_list[-1] | |
422 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
443 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ | |
423 | (Colors.normalEm, |
|
444 | (Colors.normalEm, | |
424 | Colors.filenameEm, filename, Colors.normalEm, |
|
445 | Colors.filenameEm, filename, Colors.normalEm, | |
425 | Colors.linenoEm, lineno, Colors.normalEm, |
|
446 | Colors.linenoEm, lineno, Colors.normalEm, | |
426 | Colors.nameEm, name, Colors.normalEm, |
|
447 | Colors.nameEm, name, Colors.normalEm, | |
427 | Colors.Normal) |
|
448 | Colors.Normal) | |
428 | if line: |
|
449 | if line: | |
429 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), |
|
450 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), | |
430 | Colors.Normal) |
|
451 | Colors.Normal) | |
431 | list.append(item) |
|
452 | list.append(item) | |
432 | return list |
|
453 | return list | |
433 |
|
454 | |||
434 | def _format_exception_only(self, etype, value): |
|
455 | def _format_exception_only(self, etype, value): | |
435 | """Format the exception part of a traceback. |
|
456 | """Format the exception part of a traceback. | |
436 |
|
457 | |||
437 | The arguments are the exception type and value such as given by |
|
458 | The arguments are the exception type and value such as given by | |
438 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
459 | sys.exc_info()[:2]. The return value is a list of strings, each ending | |
439 | in a newline. Normally, the list contains a single string; however, |
|
460 | in a newline. Normally, the list contains a single string; however, | |
440 | for SyntaxError exceptions, it contains several lines that (when |
|
461 | for SyntaxError exceptions, it contains several lines that (when | |
441 | printed) display detailed information about where the syntax error |
|
462 | printed) display detailed information about where the syntax error | |
442 | occurred. The message indicating which exception occurred is the |
|
463 | occurred. The message indicating which exception occurred is the | |
443 | always last string in the list. |
|
464 | always last string in the list. | |
444 |
|
465 | |||
445 | Also lifted nearly verbatim from traceback.py |
|
466 | Also lifted nearly verbatim from traceback.py | |
446 | """ |
|
467 | """ | |
447 |
|
468 | |||
448 | have_filedata = False |
|
469 | have_filedata = False | |
449 | Colors = self.Colors |
|
470 | Colors = self.Colors | |
450 | list = [] |
|
471 | list = [] | |
451 | try: |
|
472 | try: | |
452 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
473 | stype = Colors.excName + etype.__name__ + Colors.Normal | |
453 | except AttributeError: |
|
474 | except AttributeError: | |
454 | stype = etype # String exceptions don't get special coloring |
|
475 | stype = etype # String exceptions don't get special coloring | |
455 | if value is None: |
|
476 | if value is None: | |
456 | list.append( str(stype) + '\n') |
|
477 | list.append( str(stype) + '\n') | |
457 | else: |
|
478 | else: | |
458 | if etype is SyntaxError: |
|
479 | if etype is SyntaxError: | |
459 | try: |
|
480 | try: | |
460 | msg, (filename, lineno, offset, line) = value |
|
481 | msg, (filename, lineno, offset, line) = value | |
461 | except: |
|
482 | except: | |
462 | have_filedata = False |
|
483 | have_filedata = False | |
463 | else: |
|
484 | else: | |
464 | have_filedata = True |
|
485 | have_filedata = True | |
465 | #print 'filename is',filename # dbg |
|
486 | #print 'filename is',filename # dbg | |
466 | if not filename: filename = "<string>" |
|
487 | if not filename: filename = "<string>" | |
467 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
488 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ | |
468 | (Colors.normalEm, |
|
489 | (Colors.normalEm, | |
469 | Colors.filenameEm, filename, Colors.normalEm, |
|
490 | Colors.filenameEm, filename, Colors.normalEm, | |
470 | Colors.linenoEm, lineno, Colors.Normal )) |
|
491 | Colors.linenoEm, lineno, Colors.Normal )) | |
471 | if line is not None: |
|
492 | if line is not None: | |
472 | i = 0 |
|
493 | i = 0 | |
473 | while i < len(line) and line[i].isspace(): |
|
494 | while i < len(line) and line[i].isspace(): | |
474 | i = i+1 |
|
495 | i = i+1 | |
475 | list.append('%s %s%s\n' % (Colors.line, |
|
496 | list.append('%s %s%s\n' % (Colors.line, | |
476 | line.strip(), |
|
497 | line.strip(), | |
477 | Colors.Normal)) |
|
498 | Colors.Normal)) | |
478 | if offset is not None: |
|
499 | if offset is not None: | |
479 | s = ' ' |
|
500 | s = ' ' | |
480 | for c in line[i:offset-1]: |
|
501 | for c in line[i:offset-1]: | |
481 | if c.isspace(): |
|
502 | if c.isspace(): | |
482 | s = s + c |
|
503 | s = s + c | |
483 | else: |
|
504 | else: | |
484 | s = s + ' ' |
|
505 | s = s + ' ' | |
485 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
506 | list.append('%s%s^%s\n' % (Colors.caret, s, | |
486 | Colors.Normal) ) |
|
507 | Colors.Normal) ) | |
487 | value = msg |
|
508 | value = msg | |
488 | s = self._some_str(value) |
|
509 | s = self._some_str(value) | |
489 | if s: |
|
510 | if s: | |
490 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
511 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, | |
491 | Colors.Normal, s)) |
|
512 | Colors.Normal, s)) | |
492 | else: |
|
513 | else: | |
493 | list.append('%s\n' % str(stype)) |
|
514 | list.append('%s\n' % str(stype)) | |
494 |
|
515 | |||
495 | # vds:>> |
|
516 | # sync with user hooks | |
496 | if have_filedata: |
|
517 | if have_filedata: | |
497 | ipinst = ipapi.get() |
|
518 | ipinst = ipapi.get() | |
498 | if ipinst is not None: |
|
519 | if ipinst is not None: | |
499 | ipinst.hooks.synchronize_with_editor(filename, lineno, 0) |
|
520 | ipinst.hooks.synchronize_with_editor(filename, lineno, 0) | |
500 | # vds:<< |
|
|||
501 |
|
521 | |||
502 | return list |
|
522 | return list | |
503 |
|
523 | |||
|
524 | def show_exception_only(self, etype, value): | |||
|
525 | """Only print the exception type and message, without a traceback. | |||
|
526 | ||||
|
527 | Parameters | |||
|
528 | ---------- | |||
|
529 | etype : exception type | |||
|
530 | value : exception value | |||
|
531 | """ | |||
|
532 | # This method needs to use __call__ from *this* class, not the one from | |||
|
533 | # a subclass whose signature or behavior may be different | |||
|
534 | Term.cout.flush() | |||
|
535 | ostream = sys.stdout if self.out_stream == 'stdout' else Term.cerr | |||
|
536 | print >> ostream, ListTB.text(self, etype, value, []), | |||
|
537 | ostream.flush() | |||
|
538 | ||||
504 | def _some_str(self, value): |
|
539 | def _some_str(self, value): | |
505 | # Lifted from traceback.py |
|
540 | # Lifted from traceback.py | |
506 | try: |
|
541 | try: | |
507 | return str(value) |
|
542 | return str(value) | |
508 | except: |
|
543 | except: | |
509 | return '<unprintable %s object>' % type(value).__name__ |
|
544 | return '<unprintable %s object>' % type(value).__name__ | |
510 |
|
545 | |||
511 | #---------------------------------------------------------------------------- |
|
546 | #---------------------------------------------------------------------------- | |
512 | class VerboseTB(TBTools): |
|
547 | class VerboseTB(TBTools): | |
513 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
548 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | |
514 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
549 | of HTML. Requires inspect and pydoc. Crazy, man. | |
515 |
|
550 | |||
516 | Modified version which optionally strips the topmost entries from the |
|
551 | Modified version which optionally strips the topmost entries from the | |
517 | traceback, to be used with alternate interpreters (because their own code |
|
552 | traceback, to be used with alternate interpreters (because their own code | |
518 | would appear in the traceback).""" |
|
553 | would appear in the traceback).""" | |
519 |
|
554 | |||
520 | def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0, |
|
555 | def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0, | |
521 | call_pdb = 0, include_vars=1): |
|
556 | call_pdb = 0, include_vars=1): | |
522 | """Specify traceback offset, headers and color scheme. |
|
557 | """Specify traceback offset, headers and color scheme. | |
523 |
|
558 | |||
524 | Define how many frames to drop from the tracebacks. Calling it with |
|
559 | Define how many frames to drop from the tracebacks. Calling it with | |
525 | tb_offset=1 allows use of this handler in interpreters which will have |
|
560 | tb_offset=1 allows use of this handler in interpreters which will have | |
526 | their own code at the top of the traceback (VerboseTB will first |
|
561 | their own code at the top of the traceback (VerboseTB will first | |
527 | remove that frame before printing the traceback info).""" |
|
562 | remove that frame before printing the traceback info).""" | |
528 | TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb) |
|
563 | TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb) | |
529 | self.tb_offset = tb_offset |
|
564 | self.tb_offset = tb_offset | |
530 | self.long_header = long_header |
|
565 | self.long_header = long_header | |
531 | self.include_vars = include_vars |
|
566 | self.include_vars = include_vars | |
532 |
|
567 | |||
533 | def text(self, etype, evalue, etb, context=5): |
|
568 | def text(self, etype, evalue, etb, context=5): | |
534 | """Return a nice text document describing the traceback.""" |
|
569 | """Return a nice text document describing the traceback.""" | |
535 |
|
570 | |||
536 | # some locals |
|
571 | # some locals | |
537 | try: |
|
572 | try: | |
538 | etype = etype.__name__ |
|
573 | etype = etype.__name__ | |
539 | except AttributeError: |
|
574 | except AttributeError: | |
540 | pass |
|
575 | pass | |
541 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
576 | Colors = self.Colors # just a shorthand + quicker name lookup | |
542 | ColorsNormal = Colors.Normal # used a lot |
|
577 | ColorsNormal = Colors.Normal # used a lot | |
543 | col_scheme = self.color_scheme_table.active_scheme_name |
|
578 | col_scheme = self.color_scheme_table.active_scheme_name | |
544 | indent = ' '*INDENT_SIZE |
|
579 | indent = ' '*INDENT_SIZE | |
545 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
580 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) | |
546 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
581 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) | |
547 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
582 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) | |
548 |
|
583 | |||
549 | # some internal-use functions |
|
584 | # some internal-use functions | |
550 | def text_repr(value): |
|
585 | def text_repr(value): | |
551 | """Hopefully pretty robust repr equivalent.""" |
|
586 | """Hopefully pretty robust repr equivalent.""" | |
552 | # this is pretty horrible but should always return *something* |
|
587 | # this is pretty horrible but should always return *something* | |
553 | try: |
|
588 | try: | |
554 | return pydoc.text.repr(value) |
|
589 | return pydoc.text.repr(value) | |
555 | except KeyboardInterrupt: |
|
590 | except KeyboardInterrupt: | |
556 | raise |
|
591 | raise | |
557 | except: |
|
592 | except: | |
558 | try: |
|
593 | try: | |
559 | return repr(value) |
|
594 | return repr(value) | |
560 | except KeyboardInterrupt: |
|
595 | except KeyboardInterrupt: | |
561 | raise |
|
596 | raise | |
562 | except: |
|
597 | except: | |
563 | try: |
|
598 | try: | |
564 | # all still in an except block so we catch |
|
599 | # all still in an except block so we catch | |
565 | # getattr raising |
|
600 | # getattr raising | |
566 | name = getattr(value, '__name__', None) |
|
601 | name = getattr(value, '__name__', None) | |
567 | if name: |
|
602 | if name: | |
568 | # ick, recursion |
|
603 | # ick, recursion | |
569 | return text_repr(name) |
|
604 | return text_repr(name) | |
570 | klass = getattr(value, '__class__', None) |
|
605 | klass = getattr(value, '__class__', None) | |
571 | if klass: |
|
606 | if klass: | |
572 | return '%s instance' % text_repr(klass) |
|
607 | return '%s instance' % text_repr(klass) | |
573 | except KeyboardInterrupt: |
|
608 | except KeyboardInterrupt: | |
574 | raise |
|
609 | raise | |
575 | except: |
|
610 | except: | |
576 | return 'UNRECOVERABLE REPR FAILURE' |
|
611 | return 'UNRECOVERABLE REPR FAILURE' | |
577 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
612 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) | |
578 | def nullrepr(value, repr=text_repr): return '' |
|
613 | def nullrepr(value, repr=text_repr): return '' | |
579 |
|
614 | |||
580 | # meat of the code begins |
|
615 | # meat of the code begins | |
581 | try: |
|
616 | try: | |
582 | etype = etype.__name__ |
|
617 | etype = etype.__name__ | |
583 | except AttributeError: |
|
618 | except AttributeError: | |
584 | pass |
|
619 | pass | |
585 |
|
620 | |||
586 | if self.long_header: |
|
621 | if self.long_header: | |
587 | # Header with the exception type, python version, and date |
|
622 | # Header with the exception type, python version, and date | |
588 | pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable |
|
623 | pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable | |
589 | date = time.ctime(time.time()) |
|
624 | date = time.ctime(time.time()) | |
590 |
|
625 | |||
591 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
626 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, | |
592 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
627 | exc, ' '*(75-len(str(etype))-len(pyver)), | |
593 | pyver, string.rjust(date, 75) ) |
|
628 | pyver, string.rjust(date, 75) ) | |
594 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
629 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ | |
595 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
630 | "\ncalls leading up to the error, with the most recent (innermost) call last." | |
596 | else: |
|
631 | else: | |
597 | # Simplified header |
|
632 | # Simplified header | |
598 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
633 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, | |
599 | string.rjust('Traceback (most recent call last)', |
|
634 | string.rjust('Traceback (most recent call last)', | |
600 | 75 - len(str(etype)) ) ) |
|
635 | 75 - len(str(etype)) ) ) | |
601 | frames = [] |
|
636 | frames = [] | |
602 | # Flush cache before calling inspect. This helps alleviate some of the |
|
637 | # Flush cache before calling inspect. This helps alleviate some of the | |
603 | # problems with python 2.3's inspect.py. |
|
638 | # problems with python 2.3's inspect.py. | |
604 | linecache.checkcache() |
|
639 | linecache.checkcache() | |
605 | # Drop topmost frames if requested |
|
640 | # Drop topmost frames if requested | |
606 | try: |
|
641 | try: | |
607 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
642 | # Try the default getinnerframes and Alex's: Alex's fixes some | |
608 | # problems, but it generates empty tracebacks for console errors |
|
643 | # problems, but it generates empty tracebacks for console errors | |
609 | # (5 blanks lines) where none should be returned. |
|
644 | # (5 blanks lines) where none should be returned. | |
610 | #records = inspect.getinnerframes(etb, context)[self.tb_offset:] |
|
645 | #records = inspect.getinnerframes(etb, context)[self.tb_offset:] | |
611 | #print 'python records:', records # dbg |
|
646 | #print 'python records:', records # dbg | |
612 | records = _fixed_getinnerframes(etb, context,self.tb_offset) |
|
647 | records = _fixed_getinnerframes(etb, context,self.tb_offset) | |
613 | #print 'alex records:', records # dbg |
|
648 | #print 'alex records:', records # dbg | |
614 | except: |
|
649 | except: | |
615 |
|
650 | |||
616 | # FIXME: I've been getting many crash reports from python 2.3 |
|
651 | # FIXME: I've been getting many crash reports from python 2.3 | |
617 | # users, traceable to inspect.py. If I can find a small test-case |
|
652 | # users, traceable to inspect.py. If I can find a small test-case | |
618 | # to reproduce this, I should either write a better workaround or |
|
653 | # to reproduce this, I should either write a better workaround or | |
619 | # file a bug report against inspect (if that's the real problem). |
|
654 | # file a bug report against inspect (if that's the real problem). | |
620 | # So far, I haven't been able to find an isolated example to |
|
655 | # So far, I haven't been able to find an isolated example to | |
621 | # reproduce the problem. |
|
656 | # reproduce the problem. | |
622 | inspect_error() |
|
657 | inspect_error() | |
623 | traceback.print_exc(file=Term.cerr) |
|
658 | traceback.print_exc(file=Term.cerr) | |
624 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
659 | info('\nUnfortunately, your original traceback can not be constructed.\n') | |
625 | return '' |
|
660 | return '' | |
626 |
|
661 | |||
627 | # build some color string templates outside these nested loops |
|
662 | # build some color string templates outside these nested loops | |
628 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
663 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) | |
629 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
664 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, | |
630 | ColorsNormal) |
|
665 | ColorsNormal) | |
631 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
666 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ | |
632 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
667 | (Colors.vName, Colors.valEm, ColorsNormal) | |
633 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
668 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) | |
634 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
669 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, | |
635 | Colors.vName, ColorsNormal) |
|
670 | Colors.vName, ColorsNormal) | |
636 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
671 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) | |
637 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
672 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) | |
638 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
673 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, | |
639 | ColorsNormal) |
|
674 | ColorsNormal) | |
640 |
|
675 | |||
641 | # now, loop over all records printing context and info |
|
676 | # now, loop over all records printing context and info | |
642 | abspath = os.path.abspath |
|
677 | abspath = os.path.abspath | |
643 | for frame, file, lnum, func, lines, index in records: |
|
678 | for frame, file, lnum, func, lines, index in records: | |
644 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
679 | #print '*** record:',file,lnum,func,lines,index # dbg | |
645 | try: |
|
680 | try: | |
646 | file = file and abspath(file) or '?' |
|
681 | file = file and abspath(file) or '?' | |
647 | except OSError: |
|
682 | except OSError: | |
648 | # if file is '<console>' or something not in the filesystem, |
|
683 | # if file is '<console>' or something not in the filesystem, | |
649 | # the abspath call will throw an OSError. Just ignore it and |
|
684 | # the abspath call will throw an OSError. Just ignore it and | |
650 | # keep the original file string. |
|
685 | # keep the original file string. | |
651 | pass |
|
686 | pass | |
652 | link = tpl_link % file |
|
687 | link = tpl_link % file | |
653 | try: |
|
688 | try: | |
654 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
689 | args, varargs, varkw, locals = inspect.getargvalues(frame) | |
655 | except: |
|
690 | except: | |
656 | # This can happen due to a bug in python2.3. We should be |
|
691 | # This can happen due to a bug in python2.3. We should be | |
657 | # able to remove this try/except when 2.4 becomes a |
|
692 | # able to remove this try/except when 2.4 becomes a | |
658 | # requirement. Bug details at http://python.org/sf/1005466 |
|
693 | # requirement. Bug details at http://python.org/sf/1005466 | |
659 | inspect_error() |
|
694 | inspect_error() | |
660 | traceback.print_exc(file=Term.cerr) |
|
695 | traceback.print_exc(file=Term.cerr) | |
661 | info("\nIPython's exception reporting continues...\n") |
|
696 | info("\nIPython's exception reporting continues...\n") | |
662 |
|
697 | |||
663 | if func == '?': |
|
698 | if func == '?': | |
664 | call = '' |
|
699 | call = '' | |
665 | else: |
|
700 | else: | |
666 | # Decide whether to include variable details or not |
|
701 | # Decide whether to include variable details or not | |
667 | var_repr = self.include_vars and eqrepr or nullrepr |
|
702 | var_repr = self.include_vars and eqrepr or nullrepr | |
668 | try: |
|
703 | try: | |
669 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
704 | call = tpl_call % (func,inspect.formatargvalues(args, | |
670 | varargs, varkw, |
|
705 | varargs, varkw, | |
671 | locals,formatvalue=var_repr)) |
|
706 | locals,formatvalue=var_repr)) | |
672 | except KeyError: |
|
707 | except KeyError: | |
673 | # Very odd crash from inspect.formatargvalues(). The |
|
708 | # Very odd crash from inspect.formatargvalues(). The | |
674 | # scenario under which it appeared was a call to |
|
709 | # scenario under which it appeared was a call to | |
675 | # view(array,scale) in NumTut.view.view(), where scale had |
|
710 | # view(array,scale) in NumTut.view.view(), where scale had | |
676 | # been defined as a scalar (it should be a tuple). Somehow |
|
711 | # been defined as a scalar (it should be a tuple). Somehow | |
677 | # inspect messes up resolving the argument list of view() |
|
712 | # inspect messes up resolving the argument list of view() | |
678 | # and barfs out. At some point I should dig into this one |
|
713 | # and barfs out. At some point I should dig into this one | |
679 | # and file a bug report about it. |
|
714 | # and file a bug report about it. | |
680 | inspect_error() |
|
715 | inspect_error() | |
681 | traceback.print_exc(file=Term.cerr) |
|
716 | traceback.print_exc(file=Term.cerr) | |
682 | info("\nIPython's exception reporting continues...\n") |
|
717 | info("\nIPython's exception reporting continues...\n") | |
683 | call = tpl_call_fail % func |
|
718 | call = tpl_call_fail % func | |
684 |
|
719 | |||
685 | # Initialize a list of names on the current line, which the |
|
720 | # Initialize a list of names on the current line, which the | |
686 | # tokenizer below will populate. |
|
721 | # tokenizer below will populate. | |
687 | names = [] |
|
722 | names = [] | |
688 |
|
723 | |||
689 | def tokeneater(token_type, token, start, end, line): |
|
724 | def tokeneater(token_type, token, start, end, line): | |
690 | """Stateful tokeneater which builds dotted names. |
|
725 | """Stateful tokeneater which builds dotted names. | |
691 |
|
726 | |||
692 | The list of names it appends to (from the enclosing scope) can |
|
727 | The list of names it appends to (from the enclosing scope) can | |
693 | contain repeated composite names. This is unavoidable, since |
|
728 | contain repeated composite names. This is unavoidable, since | |
694 | there is no way to disambguate partial dotted structures until |
|
729 | there is no way to disambguate partial dotted structures until | |
695 | the full list is known. The caller is responsible for pruning |
|
730 | the full list is known. The caller is responsible for pruning | |
696 | the final list of duplicates before using it.""" |
|
731 | the final list of duplicates before using it.""" | |
697 |
|
732 | |||
698 | # build composite names |
|
733 | # build composite names | |
699 | if token == '.': |
|
734 | if token == '.': | |
700 | try: |
|
735 | try: | |
701 | names[-1] += '.' |
|
736 | names[-1] += '.' | |
702 | # store state so the next token is added for x.y.z names |
|
737 | # store state so the next token is added for x.y.z names | |
703 | tokeneater.name_cont = True |
|
738 | tokeneater.name_cont = True | |
704 | return |
|
739 | return | |
705 | except IndexError: |
|
740 | except IndexError: | |
706 | pass |
|
741 | pass | |
707 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
742 | if token_type == tokenize.NAME and token not in keyword.kwlist: | |
708 | if tokeneater.name_cont: |
|
743 | if tokeneater.name_cont: | |
709 | # Dotted names |
|
744 | # Dotted names | |
710 | names[-1] += token |
|
745 | names[-1] += token | |
711 | tokeneater.name_cont = False |
|
746 | tokeneater.name_cont = False | |
712 | else: |
|
747 | else: | |
713 | # Regular new names. We append everything, the caller |
|
748 | # Regular new names. We append everything, the caller | |
714 | # will be responsible for pruning the list later. It's |
|
749 | # will be responsible for pruning the list later. It's | |
715 | # very tricky to try to prune as we go, b/c composite |
|
750 | # very tricky to try to prune as we go, b/c composite | |
716 | # names can fool us. The pruning at the end is easy |
|
751 | # names can fool us. The pruning at the end is easy | |
717 | # to do (or the caller can print a list with repeated |
|
752 | # to do (or the caller can print a list with repeated | |
718 | # names if so desired. |
|
753 | # names if so desired. | |
719 | names.append(token) |
|
754 | names.append(token) | |
720 | elif token_type == tokenize.NEWLINE: |
|
755 | elif token_type == tokenize.NEWLINE: | |
721 | raise IndexError |
|
756 | raise IndexError | |
722 | # we need to store a bit of state in the tokenizer to build |
|
757 | # we need to store a bit of state in the tokenizer to build | |
723 | # dotted names |
|
758 | # dotted names | |
724 | tokeneater.name_cont = False |
|
759 | tokeneater.name_cont = False | |
725 |
|
760 | |||
726 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
761 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): | |
727 | line = getline(file, lnum[0]) |
|
762 | line = getline(file, lnum[0]) | |
728 | lnum[0] += 1 |
|
763 | lnum[0] += 1 | |
729 | return line |
|
764 | return line | |
730 |
|
765 | |||
731 | # Build the list of names on this line of code where the exception |
|
766 | # Build the list of names on this line of code where the exception | |
732 | # occurred. |
|
767 | # occurred. | |
733 | try: |
|
768 | try: | |
734 | # This builds the names list in-place by capturing it from the |
|
769 | # This builds the names list in-place by capturing it from the | |
735 | # enclosing scope. |
|
770 | # enclosing scope. | |
736 | tokenize.tokenize(linereader, tokeneater) |
|
771 | tokenize.tokenize(linereader, tokeneater) | |
737 | except IndexError: |
|
772 | except IndexError: | |
738 | # signals exit of tokenizer |
|
773 | # signals exit of tokenizer | |
739 | pass |
|
774 | pass | |
740 | except tokenize.TokenError,msg: |
|
775 | except tokenize.TokenError,msg: | |
741 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
776 | _m = ("An unexpected error occurred while tokenizing input\n" | |
742 | "The following traceback may be corrupted or invalid\n" |
|
777 | "The following traceback may be corrupted or invalid\n" | |
743 | "The error message is: %s\n" % msg) |
|
778 | "The error message is: %s\n" % msg) | |
744 | error(_m) |
|
779 | error(_m) | |
745 |
|
780 | |||
746 | # prune names list of duplicates, but keep the right order |
|
781 | # prune names list of duplicates, but keep the right order | |
747 | unique_names = uniq_stable(names) |
|
782 | unique_names = uniq_stable(names) | |
748 |
|
783 | |||
749 | # Start loop over vars |
|
784 | # Start loop over vars | |
750 | lvals = [] |
|
785 | lvals = [] | |
751 | if self.include_vars: |
|
786 | if self.include_vars: | |
752 | for name_full in unique_names: |
|
787 | for name_full in unique_names: | |
753 | name_base = name_full.split('.',1)[0] |
|
788 | name_base = name_full.split('.',1)[0] | |
754 | if name_base in frame.f_code.co_varnames: |
|
789 | if name_base in frame.f_code.co_varnames: | |
755 | if locals.has_key(name_base): |
|
790 | if locals.has_key(name_base): | |
756 | try: |
|
791 | try: | |
757 | value = repr(eval(name_full,locals)) |
|
792 | value = repr(eval(name_full,locals)) | |
758 | except: |
|
793 | except: | |
759 | value = undefined |
|
794 | value = undefined | |
760 | else: |
|
795 | else: | |
761 | value = undefined |
|
796 | value = undefined | |
762 | name = tpl_local_var % name_full |
|
797 | name = tpl_local_var % name_full | |
763 | else: |
|
798 | else: | |
764 | if frame.f_globals.has_key(name_base): |
|
799 | if frame.f_globals.has_key(name_base): | |
765 | try: |
|
800 | try: | |
766 | value = repr(eval(name_full,frame.f_globals)) |
|
801 | value = repr(eval(name_full,frame.f_globals)) | |
767 | except: |
|
802 | except: | |
768 | value = undefined |
|
803 | value = undefined | |
769 | else: |
|
804 | else: | |
770 | value = undefined |
|
805 | value = undefined | |
771 | name = tpl_global_var % name_full |
|
806 | name = tpl_global_var % name_full | |
772 | lvals.append(tpl_name_val % (name,value)) |
|
807 | lvals.append(tpl_name_val % (name,value)) | |
773 | if lvals: |
|
808 | if lvals: | |
774 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
809 | lvals = '%s%s' % (indent,em_normal.join(lvals)) | |
775 | else: |
|
810 | else: | |
776 | lvals = '' |
|
811 | lvals = '' | |
777 |
|
812 | |||
778 | level = '%s %s\n' % (link,call) |
|
813 | level = '%s %s\n' % (link,call) | |
779 |
|
814 | |||
780 | if index is None: |
|
815 | if index is None: | |
781 | frames.append(level) |
|
816 | frames.append(level) | |
782 | else: |
|
817 | else: | |
783 | frames.append('%s%s' % (level,''.join( |
|
818 | frames.append('%s%s' % (level,''.join( | |
784 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
819 | _format_traceback_lines(lnum,index,lines,Colors,lvals, | |
785 | col_scheme)))) |
|
820 | col_scheme)))) | |
786 |
|
821 | |||
787 | # Get (safely) a string form of the exception info |
|
822 | # Get (safely) a string form of the exception info | |
788 | try: |
|
823 | try: | |
789 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
824 | etype_str,evalue_str = map(str,(etype,evalue)) | |
790 | except: |
|
825 | except: | |
791 | # User exception is improperly defined. |
|
826 | # User exception is improperly defined. | |
792 | etype,evalue = str,sys.exc_info()[:2] |
|
827 | etype,evalue = str,sys.exc_info()[:2] | |
793 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
828 | etype_str,evalue_str = map(str,(etype,evalue)) | |
794 | # ... and format it |
|
829 | # ... and format it | |
795 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
830 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, | |
796 | ColorsNormal, evalue_str)] |
|
831 | ColorsNormal, evalue_str)] | |
797 | if type(evalue) is types.InstanceType: |
|
832 | if type(evalue) is types.InstanceType: | |
798 | try: |
|
833 | try: | |
799 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
834 | names = [w for w in dir(evalue) if isinstance(w, basestring)] | |
800 | except: |
|
835 | except: | |
801 | # Every now and then, an object with funny inernals blows up |
|
836 | # Every now and then, an object with funny inernals blows up | |
802 | # when dir() is called on it. We do the best we can to report |
|
837 | # when dir() is called on it. We do the best we can to report | |
803 | # the problem and continue |
|
838 | # the problem and continue | |
804 | _m = '%sException reporting error (object with broken dir())%s:' |
|
839 | _m = '%sException reporting error (object with broken dir())%s:' | |
805 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
840 | exception.append(_m % (Colors.excName,ColorsNormal)) | |
806 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
841 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) | |
807 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
842 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, | |
808 | ColorsNormal, evalue_str)) |
|
843 | ColorsNormal, evalue_str)) | |
809 | names = [] |
|
844 | names = [] | |
810 | for name in names: |
|
845 | for name in names: | |
811 | value = text_repr(getattr(evalue, name)) |
|
846 | value = text_repr(getattr(evalue, name)) | |
812 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
847 | exception.append('\n%s%s = %s' % (indent, name, value)) | |
813 |
|
848 | |||
814 | # vds: >> |
|
849 | # vds: >> | |
815 | if records: |
|
850 | if records: | |
816 | filepath, lnum = records[-1][1:3] |
|
851 | filepath, lnum = records[-1][1:3] | |
817 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
852 | #print "file:", str(file), "linenb", str(lnum) # dbg | |
818 | filepath = os.path.abspath(filepath) |
|
853 | filepath = os.path.abspath(filepath) | |
819 | ipinst = ipapi.get() |
|
854 | ipinst = ipapi.get() | |
820 | if ipinst is not None: |
|
855 | if ipinst is not None: | |
821 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
856 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) | |
822 | # vds: << |
|
857 | # vds: << | |
823 |
|
858 | |||
824 | # return all our info assembled as a single string |
|
859 | # return all our info assembled as a single string | |
825 | return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
860 | return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) | |
826 |
|
861 | |||
827 | def debugger(self,force=False): |
|
862 | def debugger(self,force=False): | |
828 | """Call up the pdb debugger if desired, always clean up the tb |
|
863 | """Call up the pdb debugger if desired, always clean up the tb | |
829 | reference. |
|
864 | reference. | |
830 |
|
865 | |||
831 | Keywords: |
|
866 | Keywords: | |
832 |
|
867 | |||
833 | - force(False): by default, this routine checks the instance call_pdb |
|
868 | - force(False): by default, this routine checks the instance call_pdb | |
834 | flag and does not actually invoke the debugger if the flag is false. |
|
869 | flag and does not actually invoke the debugger if the flag is false. | |
835 | The 'force' option forces the debugger to activate even if the flag |
|
870 | The 'force' option forces the debugger to activate even if the flag | |
836 | is false. |
|
871 | is false. | |
837 |
|
872 | |||
838 | If the call_pdb flag is set, the pdb interactive debugger is |
|
873 | If the call_pdb flag is set, the pdb interactive debugger is | |
839 | invoked. In all cases, the self.tb reference to the current traceback |
|
874 | invoked. In all cases, the self.tb reference to the current traceback | |
840 | is deleted to prevent lingering references which hamper memory |
|
875 | is deleted to prevent lingering references which hamper memory | |
841 | management. |
|
876 | management. | |
842 |
|
877 | |||
843 | Note that each call to pdb() does an 'import readline', so if your app |
|
878 | Note that each call to pdb() does an 'import readline', so if your app | |
844 | requires a special setup for the readline completers, you'll have to |
|
879 | requires a special setup for the readline completers, you'll have to | |
845 | fix that by hand after invoking the exception handler.""" |
|
880 | fix that by hand after invoking the exception handler.""" | |
846 |
|
881 | |||
847 | if force or self.call_pdb: |
|
882 | if force or self.call_pdb: | |
848 | if self.pdb is None: |
|
883 | if self.pdb is None: | |
849 | self.pdb = debugger.Pdb( |
|
884 | self.pdb = debugger.Pdb( | |
850 | self.color_scheme_table.active_scheme_name) |
|
885 | self.color_scheme_table.active_scheme_name) | |
851 | # the system displayhook may have changed, restore the original |
|
886 | # the system displayhook may have changed, restore the original | |
852 | # for pdb |
|
887 | # for pdb | |
853 | display_trap = DisplayTrap(None, sys.__displayhook__) |
|
888 | display_trap = DisplayTrap(None, sys.__displayhook__) | |
854 | with display_trap: |
|
889 | with display_trap: | |
855 | self.pdb.reset() |
|
890 | self.pdb.reset() | |
856 | # Find the right frame so we don't pop up inside ipython itself |
|
891 | # Find the right frame so we don't pop up inside ipython itself | |
857 | if hasattr(self,'tb') and self.tb is not None: |
|
892 | if hasattr(self,'tb') and self.tb is not None: | |
858 | etb = self.tb |
|
893 | etb = self.tb | |
859 | else: |
|
894 | else: | |
860 | etb = self.tb = sys.last_traceback |
|
895 | etb = self.tb = sys.last_traceback | |
861 | while self.tb is not None and self.tb.tb_next is not None: |
|
896 | while self.tb is not None and self.tb.tb_next is not None: | |
862 | self.tb = self.tb.tb_next |
|
897 | self.tb = self.tb.tb_next | |
863 | if etb and etb.tb_next: |
|
898 | if etb and etb.tb_next: | |
864 | etb = etb.tb_next |
|
899 | etb = etb.tb_next | |
865 | self.pdb.botframe = etb.tb_frame |
|
900 | self.pdb.botframe = etb.tb_frame | |
866 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
901 | self.pdb.interaction(self.tb.tb_frame, self.tb) | |
867 |
|
902 | |||
868 | if hasattr(self,'tb'): |
|
903 | if hasattr(self,'tb'): | |
869 | del self.tb |
|
904 | del self.tb | |
870 |
|
905 | |||
871 | def handler(self, info=None): |
|
906 | def handler(self, info=None): | |
872 | (etype, evalue, etb) = info or sys.exc_info() |
|
907 | (etype, evalue, etb) = info or sys.exc_info() | |
873 | self.tb = etb |
|
908 | self.tb = etb | |
874 | Term.cout.flush() |
|
909 | Term.cout.flush() | |
875 | print >> Term.cerr, self.text(etype, evalue, etb) |
|
910 | print >> Term.cerr, self.text(etype, evalue, etb) | |
876 | Term.cerr.flush() |
|
911 | Term.cerr.flush() | |
877 |
|
912 | |||
878 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
913 | # Changed so an instance can just be called as VerboseTB_inst() and print | |
879 | # out the right info on its own. |
|
914 | # out the right info on its own. | |
880 | def __call__(self, etype=None, evalue=None, etb=None): |
|
915 | def __call__(self, etype=None, evalue=None, etb=None): | |
881 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
916 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" | |
882 | if etb is None: |
|
917 | if etb is None: | |
883 | self.handler() |
|
918 | self.handler() | |
884 | else: |
|
919 | else: | |
885 | self.handler((etype, evalue, etb)) |
|
920 | self.handler((etype, evalue, etb)) | |
886 | try: |
|
921 | try: | |
887 | self.debugger() |
|
922 | self.debugger() | |
888 | except KeyboardInterrupt: |
|
923 | except KeyboardInterrupt: | |
889 | print "\nKeyboardInterrupt" |
|
924 | print "\nKeyboardInterrupt" | |
890 |
|
925 | |||
891 | #---------------------------------------------------------------------------- |
|
926 | #---------------------------------------------------------------------------- | |
892 | class FormattedTB(VerboseTB,ListTB): |
|
927 | class FormattedTB(VerboseTB,ListTB): | |
893 | """Subclass ListTB but allow calling with a traceback. |
|
928 | """Subclass ListTB but allow calling with a traceback. | |
894 |
|
929 | |||
895 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
930 | It can thus be used as a sys.excepthook for Python > 2.1. | |
896 |
|
931 | |||
897 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
932 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. | |
898 |
|
933 | |||
899 | Allows a tb_offset to be specified. This is useful for situations where |
|
934 | Allows a tb_offset to be specified. This is useful for situations where | |
900 | one needs to remove a number of topmost frames from the traceback (such as |
|
935 | one needs to remove a number of topmost frames from the traceback (such as | |
901 | occurs with python programs that themselves execute other python code, |
|
936 | occurs with python programs that themselves execute other python code, | |
902 | like Python shells). """ |
|
937 | like Python shells). """ | |
903 |
|
938 | |||
904 | def __init__(self, mode = 'Plain', color_scheme='Linux', |
|
939 | def __init__(self, mode = 'Plain', color_scheme='Linux', | |
905 | tb_offset = 0,long_header=0,call_pdb=0,include_vars=0): |
|
940 | tb_offset = 0,long_header=0,call_pdb=0,include_vars=0): | |
906 |
|
941 | |||
907 | # NEVER change the order of this list. Put new modes at the end: |
|
942 | # NEVER change the order of this list. Put new modes at the end: | |
908 | self.valid_modes = ['Plain','Context','Verbose'] |
|
943 | self.valid_modes = ['Plain','Context','Verbose'] | |
909 | self.verbose_modes = self.valid_modes[1:3] |
|
944 | self.verbose_modes = self.valid_modes[1:3] | |
910 |
|
945 | |||
911 | VerboseTB.__init__(self,color_scheme,tb_offset,long_header, |
|
946 | VerboseTB.__init__(self,color_scheme,tb_offset,long_header, | |
912 | call_pdb=call_pdb,include_vars=include_vars) |
|
947 | call_pdb=call_pdb,include_vars=include_vars) | |
913 | self.set_mode(mode) |
|
948 | self.set_mode(mode) | |
914 |
|
949 | |||
915 | def _extract_tb(self,tb): |
|
950 | def _extract_tb(self,tb): | |
916 | if tb: |
|
951 | if tb: | |
917 | return traceback.extract_tb(tb) |
|
952 | return traceback.extract_tb(tb) | |
918 | else: |
|
953 | else: | |
919 | return None |
|
954 | return None | |
920 |
|
955 | |||
921 | def text(self, etype, value, tb,context=5,mode=None): |
|
956 | def text(self, etype, value, tb,context=5,mode=None): | |
922 | """Return formatted traceback. |
|
957 | """Return formatted traceback. | |
923 |
|
958 | |||
924 | If the optional mode parameter is given, it overrides the current |
|
959 | If the optional mode parameter is given, it overrides the current | |
925 | mode.""" |
|
960 | mode.""" | |
926 |
|
961 | |||
927 | if mode is None: |
|
962 | if mode is None: | |
928 | mode = self.mode |
|
963 | mode = self.mode | |
929 | if mode in self.verbose_modes: |
|
964 | if mode in self.verbose_modes: | |
930 | # verbose modes need a full traceback |
|
965 | # verbose modes need a full traceback | |
931 | return VerboseTB.text(self,etype, value, tb,context=5) |
|
966 | return VerboseTB.text(self,etype, value, tb,context=5) | |
932 | else: |
|
967 | else: | |
933 | # We must check the source cache because otherwise we can print |
|
968 | # We must check the source cache because otherwise we can print | |
934 | # out-of-date source code. |
|
969 | # out-of-date source code. | |
935 | linecache.checkcache() |
|
970 | linecache.checkcache() | |
936 | # Now we can extract and format the exception |
|
971 | # Now we can extract and format the exception | |
937 | elist = self._extract_tb(tb) |
|
972 | elist = self._extract_tb(tb) | |
938 | if len(elist) > self.tb_offset: |
|
973 | if len(elist) > self.tb_offset: | |
939 | del elist[:self.tb_offset] |
|
974 | del elist[:self.tb_offset] | |
940 | return ListTB.text(self,etype,value,elist) |
|
975 | return ListTB.text(self,etype,value,elist) | |
941 |
|
976 | |||
942 | def set_mode(self,mode=None): |
|
977 | def set_mode(self,mode=None): | |
943 | """Switch to the desired mode. |
|
978 | """Switch to the desired mode. | |
944 |
|
979 | |||
945 | If mode is not specified, cycles through the available modes.""" |
|
980 | If mode is not specified, cycles through the available modes.""" | |
946 |
|
981 | |||
947 | if not mode: |
|
982 | if not mode: | |
948 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
983 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ | |
949 | len(self.valid_modes) |
|
984 | len(self.valid_modes) | |
950 | self.mode = self.valid_modes[new_idx] |
|
985 | self.mode = self.valid_modes[new_idx] | |
951 | elif mode not in self.valid_modes: |
|
986 | elif mode not in self.valid_modes: | |
952 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ |
|
987 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ | |
953 | 'Valid modes: '+str(self.valid_modes) |
|
988 | 'Valid modes: '+str(self.valid_modes) | |
954 | else: |
|
989 | else: | |
955 | self.mode = mode |
|
990 | self.mode = mode | |
956 | # include variable details only in 'Verbose' mode |
|
991 | # include variable details only in 'Verbose' mode | |
957 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
992 | self.include_vars = (self.mode == self.valid_modes[2]) | |
958 |
|
993 | |||
959 | # some convenient shorcuts |
|
994 | # some convenient shorcuts | |
960 | def plain(self): |
|
995 | def plain(self): | |
961 | self.set_mode(self.valid_modes[0]) |
|
996 | self.set_mode(self.valid_modes[0]) | |
962 |
|
997 | |||
963 | def context(self): |
|
998 | def context(self): | |
964 | self.set_mode(self.valid_modes[1]) |
|
999 | self.set_mode(self.valid_modes[1]) | |
965 |
|
1000 | |||
966 | def verbose(self): |
|
1001 | def verbose(self): | |
967 | self.set_mode(self.valid_modes[2]) |
|
1002 | self.set_mode(self.valid_modes[2]) | |
968 |
|
1003 | |||
969 | #---------------------------------------------------------------------------- |
|
1004 | #---------------------------------------------------------------------------- | |
970 | class AutoFormattedTB(FormattedTB): |
|
1005 | class AutoFormattedTB(FormattedTB): | |
971 | """A traceback printer which can be called on the fly. |
|
1006 | """A traceback printer which can be called on the fly. | |
972 |
|
1007 | |||
973 | It will find out about exceptions by itself. |
|
1008 | It will find out about exceptions by itself. | |
974 |
|
1009 | |||
975 | A brief example: |
|
1010 | A brief example: | |
976 |
|
1011 | |||
977 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1012 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | |
978 | try: |
|
1013 | try: | |
979 | ... |
|
1014 | ... | |
980 | except: |
|
1015 | except: | |
981 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1016 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | |
982 | """ |
|
1017 | """ | |
|
1018 | ||||
983 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1019 | def __call__(self,etype=None,evalue=None,etb=None, | |
984 | out=None,tb_offset=None): |
|
1020 | out=None,tb_offset=None): | |
985 | """Print out a formatted exception traceback. |
|
1021 | """Print out a formatted exception traceback. | |
986 |
|
1022 | |||
987 | Optional arguments: |
|
1023 | Optional arguments: | |
988 | - out: an open file-like object to direct output to. |
|
1024 | - out: an open file-like object to direct output to. | |
989 |
|
1025 | |||
990 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1026 | - tb_offset: the number of frames to skip over in the stack, on a | |
991 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1027 | per-call basis (this overrides temporarily the instance's tb_offset | |
992 | given at initialization time. """ |
|
1028 | given at initialization time. """ | |
993 |
|
1029 | |||
994 | if out is None: |
|
1030 | if out is None: | |
995 | out = Term.cerr |
|
1031 | out = sys.stdout if self.out_stream=='stdout' else self.out_stream | |
996 | Term.cout.flush() |
|
1032 | Term.cout.flush() | |
997 | if tb_offset is not None: |
|
1033 | if tb_offset is not None: | |
998 | tb_offset, self.tb_offset = self.tb_offset, tb_offset |
|
1034 | tb_offset, self.tb_offset = self.tb_offset, tb_offset | |
999 | print >> out, self.text(etype, evalue, etb) |
|
1035 | print >> out, self.text(etype, evalue, etb) | |
1000 | self.tb_offset = tb_offset |
|
1036 | self.tb_offset = tb_offset | |
1001 | else: |
|
1037 | else: | |
1002 | print >> out, self.text(etype, evalue, etb) |
|
1038 | print >> out, self.text(etype, evalue, etb) | |
1003 | out.flush() |
|
1039 | out.flush() | |
1004 | try: |
|
1040 | try: | |
1005 | self.debugger() |
|
1041 | self.debugger() | |
1006 | except KeyboardInterrupt: |
|
1042 | except KeyboardInterrupt: | |
1007 | print "\nKeyboardInterrupt" |
|
1043 | print "\nKeyboardInterrupt" | |
1008 |
|
1044 | |||
1009 | def text(self,etype=None,value=None,tb=None,context=5,mode=None): |
|
1045 | def text(self,etype=None,value=None,tb=None,context=5,mode=None): | |
1010 | if etype is None: |
|
1046 | if etype is None: | |
1011 | etype,value,tb = sys.exc_info() |
|
1047 | etype,value,tb = sys.exc_info() | |
1012 | self.tb = tb |
|
1048 | self.tb = tb | |
1013 | return FormattedTB.text(self,etype,value,tb,context=5,mode=mode) |
|
1049 | return FormattedTB.text(self,etype,value,tb,context=5,mode=mode) | |
1014 |
|
1050 | |||
1015 | #--------------------------------------------------------------------------- |
|
1051 | #--------------------------------------------------------------------------- | |
1016 | # A simple class to preserve Nathan's original functionality. |
|
1052 | # A simple class to preserve Nathan's original functionality. | |
1017 | class ColorTB(FormattedTB): |
|
1053 | class ColorTB(FormattedTB): | |
1018 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1054 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" | |
1019 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1055 | def __init__(self,color_scheme='Linux',call_pdb=0): | |
1020 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1056 | FormattedTB.__init__(self,color_scheme=color_scheme, | |
1021 | call_pdb=call_pdb) |
|
1057 | call_pdb=call_pdb) | |
1022 |
|
1058 | |||
1023 | #---------------------------------------------------------------------------- |
|
1059 | #---------------------------------------------------------------------------- | |
1024 | # module testing (minimal) |
|
1060 | # module testing (minimal) | |
1025 | if __name__ == "__main__": |
|
1061 | if __name__ == "__main__": | |
1026 | def spam(c, (d, e)): |
|
1062 | def spam(c, (d, e)): | |
1027 | x = c + d |
|
1063 | x = c + d | |
1028 | y = c * d |
|
1064 | y = c * d | |
1029 | foo(x, y) |
|
1065 | foo(x, y) | |
1030 |
|
1066 | |||
1031 | def foo(a, b, bar=1): |
|
1067 | def foo(a, b, bar=1): | |
1032 | eggs(a, b + bar) |
|
1068 | eggs(a, b + bar) | |
1033 |
|
1069 | |||
1034 | def eggs(f, g, z=globals()): |
|
1070 | def eggs(f, g, z=globals()): | |
1035 | h = f + g |
|
1071 | h = f + g | |
1036 | i = f - g |
|
1072 | i = f - g | |
1037 | return h / i |
|
1073 | return h / i | |
1038 |
|
1074 | |||
1039 | print '' |
|
1075 | print '' | |
1040 | print '*** Before ***' |
|
1076 | print '*** Before ***' | |
1041 | try: |
|
1077 | try: | |
1042 | print spam(1, (2, 3)) |
|
1078 | print spam(1, (2, 3)) | |
1043 | except: |
|
1079 | except: | |
1044 | traceback.print_exc() |
|
1080 | traceback.print_exc() | |
1045 | print '' |
|
1081 | print '' | |
1046 |
|
1082 | |||
1047 | handler = ColorTB() |
|
1083 | handler = ColorTB() | |
1048 | print '*** ColorTB ***' |
|
1084 | print '*** ColorTB ***' | |
1049 | try: |
|
1085 | try: | |
1050 | print spam(1, (2, 3)) |
|
1086 | print spam(1, (2, 3)) | |
1051 | except: |
|
1087 | except: | |
1052 | apply(handler, sys.exc_info() ) |
|
1088 | apply(handler, sys.exc_info() ) | |
1053 | print '' |
|
1089 | print '' | |
1054 |
|
1090 | |||
1055 | handler = VerboseTB() |
|
1091 | handler = VerboseTB() | |
1056 | print '*** VerboseTB ***' |
|
1092 | print '*** VerboseTB ***' | |
1057 | try: |
|
1093 | try: | |
1058 | print spam(1, (2, 3)) |
|
1094 | print spam(1, (2, 3)) | |
1059 | except: |
|
1095 | except: | |
1060 | apply(handler, sys.exc_info() ) |
|
1096 | apply(handler, sys.exc_info() ) | |
1061 | print '' |
|
1097 | print '' | |
1062 |
|
1098 |
@@ -1,169 +1,171 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 |
|
8 | |||
9 | from __future__ import absolute_import |
|
9 | from __future__ import absolute_import | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Module imports |
|
12 | # Module imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # From the standard library |
|
15 | # From the standard library | |
16 | import __builtin__ |
|
16 | import __builtin__ | |
17 | import commands |
|
17 | import commands | |
18 | import new |
|
18 | import new | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 |
|
21 | |||
22 | from . import tools |
|
22 | from . import tools | |
|
23 | from IPython.utils.genutils import Term | |||
23 |
|
24 | |||
24 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
25 | # Functions |
|
26 | # Functions | |
26 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
27 |
|
28 | |||
28 | # Hack to modify the %run command so we can sync the user's namespace with the |
|
29 | # Hack to modify the %run command so we can sync the user's namespace with the | |
29 | # test globals. Once we move over to a clean magic system, this will be done |
|
30 | # test globals. Once we move over to a clean magic system, this will be done | |
30 | # with much less ugliness. |
|
31 | # with much less ugliness. | |
31 |
|
32 | |||
32 | class py_file_finder(object): |
|
33 | class py_file_finder(object): | |
33 | def __init__(self,test_filename): |
|
34 | def __init__(self,test_filename): | |
34 | self.test_filename = test_filename |
|
35 | self.test_filename = test_filename | |
35 |
|
36 | |||
36 | def __call__(self,name): |
|
37 | def __call__(self,name): | |
37 | from IPython.utils.genutils import get_py_filename |
|
38 | from IPython.utils.genutils import get_py_filename | |
38 | try: |
|
39 | try: | |
39 | return get_py_filename(name) |
|
40 | return get_py_filename(name) | |
40 | except IOError: |
|
41 | except IOError: | |
41 | test_dir = os.path.dirname(self.test_filename) |
|
42 | test_dir = os.path.dirname(self.test_filename) | |
42 | new_path = os.path.join(test_dir,name) |
|
43 | new_path = os.path.join(test_dir,name) | |
43 | return get_py_filename(new_path) |
|
44 | return get_py_filename(new_path) | |
44 |
|
45 | |||
45 |
|
46 | |||
46 | def _run_ns_sync(self,arg_s,runner=None): |
|
47 | def _run_ns_sync(self,arg_s,runner=None): | |
47 | """Modified version of %run that syncs testing namespaces. |
|
48 | """Modified version of %run that syncs testing namespaces. | |
48 |
|
49 | |||
49 | This is strictly needed for running doctests that call %run. |
|
50 | This is strictly needed for running doctests that call %run. | |
50 | """ |
|
51 | """ | |
51 | #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg |
|
52 | #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg | |
52 |
|
53 | |||
53 | _ip = get_ipython() |
|
54 | _ip = get_ipython() | |
54 | finder = py_file_finder(arg_s) |
|
55 | finder = py_file_finder(arg_s) | |
55 | out = _ip.magic_run_ori(arg_s,runner,finder) |
|
56 | out = _ip.magic_run_ori(arg_s,runner,finder) | |
56 | return out |
|
57 | return out | |
57 |
|
58 | |||
58 |
|
59 | |||
59 | class ipnsdict(dict): |
|
60 | class ipnsdict(dict): | |
60 | """A special subclass of dict for use as an IPython namespace in doctests. |
|
61 | """A special subclass of dict for use as an IPython namespace in doctests. | |
61 |
|
62 | |||
62 | This subclass adds a simple checkpointing capability so that when testing |
|
63 | This subclass adds a simple checkpointing capability so that when testing | |
63 | machinery clears it (we use it as the test execution context), it doesn't |
|
64 | machinery clears it (we use it as the test execution context), it doesn't | |
64 | get completely destroyed. |
|
65 | get completely destroyed. | |
65 | """ |
|
66 | """ | |
66 |
|
67 | |||
67 | def __init__(self,*a): |
|
68 | def __init__(self,*a): | |
68 | dict.__init__(self,*a) |
|
69 | dict.__init__(self,*a) | |
69 | self._savedict = {} |
|
70 | self._savedict = {} | |
70 |
|
71 | |||
71 | def clear(self): |
|
72 | def clear(self): | |
72 | dict.clear(self) |
|
73 | dict.clear(self) | |
73 | self.update(self._savedict) |
|
74 | self.update(self._savedict) | |
74 |
|
75 | |||
75 | def _checkpoint(self): |
|
76 | def _checkpoint(self): | |
76 | self._savedict.clear() |
|
77 | self._savedict.clear() | |
77 | self._savedict.update(self) |
|
78 | self._savedict.update(self) | |
78 |
|
79 | |||
79 | def update(self,other): |
|
80 | def update(self,other): | |
80 | self._checkpoint() |
|
81 | self._checkpoint() | |
81 | dict.update(self,other) |
|
82 | dict.update(self,other) | |
82 |
|
83 | |||
83 | # If '_' is in the namespace, python won't set it when executing code, |
|
84 | # If '_' is in the namespace, python won't set it when executing code, | |
84 | # and we have examples that test it. So we ensure that the namespace |
|
85 | # and we have examples that test it. So we ensure that the namespace | |
85 | # is always 'clean' of it before it's used for test code execution. |
|
86 | # is always 'clean' of it before it's used for test code execution. | |
86 | self.pop('_',None) |
|
87 | self.pop('_',None) | |
87 |
|
88 | |||
88 | # The builtins namespace must *always* be the real __builtin__ module, |
|
89 | # The builtins namespace must *always* be the real __builtin__ module, | |
89 | # else weird stuff happens. The main ipython code does have provisions |
|
90 | # else weird stuff happens. The main ipython code does have provisions | |
90 | # to ensure this after %run, but since in this class we do some |
|
91 | # to ensure this after %run, but since in this class we do some | |
91 | # aggressive low-level cleaning of the execution namespace, we need to |
|
92 | # aggressive low-level cleaning of the execution namespace, we need to | |
92 | # correct for that ourselves, to ensure consitency with the 'real' |
|
93 | # correct for that ourselves, to ensure consitency with the 'real' | |
93 | # ipython. |
|
94 | # ipython. | |
94 | self['__builtins__'] = __builtin__ |
|
95 | self['__builtins__'] = __builtin__ | |
95 |
|
96 | |||
96 |
|
97 | |||
97 | def get_ipython(): |
|
98 | def get_ipython(): | |
98 | # This will get replaced by the real thing once we start IPython below |
|
99 | # This will get replaced by the real thing once we start IPython below | |
99 |
return |
|
100 | return start_ipython() | |
100 |
|
101 | |||
101 | def start_ipython(): |
|
102 | def start_ipython(): | |
102 | """Start a global IPython shell, which we need for IPython-specific syntax. |
|
103 | """Start a global IPython shell, which we need for IPython-specific syntax. | |
103 | """ |
|
104 | """ | |
104 | global get_ipython |
|
105 | global get_ipython | |
105 |
|
106 | |||
106 | # This function should only ever run once! |
|
107 | # This function should only ever run once! | |
107 | if hasattr(start_ipython,'already_called'): |
|
108 | if hasattr(start_ipython,'already_called'): | |
108 | return |
|
109 | return | |
109 | start_ipython.already_called = True |
|
110 | start_ipython.already_called = True | |
110 |
|
111 | |||
111 | # Ok, first time we're called, go ahead |
|
112 | # Ok, first time we're called, go ahead | |
112 | from IPython.core import ipapp, iplib |
|
113 | from IPython.core import ipapp, iplib | |
113 |
|
114 | |||
114 | def xsys(cmd): |
|
115 | def xsys(cmd): | |
115 | """Execute a command and print its output. |
|
116 | """Execute a command and print its output. | |
116 |
|
117 | |||
117 | This is just a convenience function to replace the IPython system call |
|
118 | This is just a convenience function to replace the IPython system call | |
118 | with one that is more doctest-friendly. |
|
119 | with one that is more doctest-friendly. | |
119 | """ |
|
120 | """ | |
120 | cmd = _ip.var_expand(cmd,depth=1) |
|
121 | cmd = _ip.var_expand(cmd,depth=1) | |
121 | sys.stdout.write(commands.getoutput(cmd)) |
|
122 | sys.stdout.write(commands.getoutput(cmd)) | |
122 | sys.stdout.flush() |
|
123 | sys.stdout.flush() | |
123 |
|
124 | |||
124 | # Store certain global objects that IPython modifies |
|
125 | # Store certain global objects that IPython modifies | |
125 | _displayhook = sys.displayhook |
|
126 | _displayhook = sys.displayhook | |
126 | _excepthook = sys.excepthook |
|
127 | _excepthook = sys.excepthook | |
127 | _main = sys.modules.get('__main__') |
|
128 | _main = sys.modules.get('__main__') | |
128 |
|
129 | |||
129 | argv = tools.default_argv() |
|
130 | argv = tools.default_argv() | |
130 |
|
131 | |||
131 | # Start IPython instance. We customize it to start with minimal frills. |
|
132 | # Start IPython instance. We customize it to start with minimal frills. | |
132 | user_ns,global_ns = iplib.make_user_namespaces(ipnsdict(),{}) |
|
133 | user_ns,global_ns = iplib.make_user_namespaces(ipnsdict(),{}) | |
133 | ip = ipapp.IPythonApp(argv, user_ns=user_ns, user_global_ns=global_ns) |
|
134 | ip = ipapp.IPythonApp(argv, user_ns=user_ns, user_global_ns=global_ns) | |
134 | ip.initialize() |
|
135 | ip.initialize() | |
135 | ip.shell.builtin_trap.set() |
|
136 | ip.shell.builtin_trap.set() | |
|
137 | # Set stderr to stdout so nose can doctest exceptions | |||
|
138 | ## Term.cerr = sys.stdout | |||
|
139 | ## sys.stderr = sys.stdout | |||
|
140 | ip.shell.InteractiveTB.out_stream = 'stdout' | |||
136 | # Butcher the logger |
|
141 | # Butcher the logger | |
137 | ip.shell.log = lambda *a,**k: None |
|
142 | ip.shell.log = lambda *a,**k: None | |
138 |
|
143 | |||
139 | # Deactivate the various python system hooks added by ipython for |
|
144 | # Deactivate the various python system hooks added by ipython for | |
140 | # interactive convenience so we don't confuse the doctest system |
|
145 | # interactive convenience so we don't confuse the doctest system | |
141 | sys.modules['__main__'] = _main |
|
146 | sys.modules['__main__'] = _main | |
142 | sys.displayhook = _displayhook |
|
147 | sys.displayhook = _displayhook | |
143 | sys.excepthook = _excepthook |
|
148 | sys.excepthook = _excepthook | |
144 |
|
149 | |||
145 | # So that ipython magics and aliases can be doctested (they work by making |
|
150 | # So that ipython magics and aliases can be doctested (they work by making | |
146 | # a call into a global _ip object) |
|
151 | # a call into a global _ip object). Also make the top-level get_ipython | |
147 |
|
152 | # now return this without calling here again | ||
148 | _ip = ip.shell |
|
153 | _ip = ip.shell | |
149 | get_ipython = _ip.get_ipython |
|
154 | get_ipython = _ip.get_ipython | |
150 | __builtin__._ip = _ip |
|
155 | __builtin__._ip = _ip | |
151 | __builtin__.get_ipython = get_ipython |
|
156 | __builtin__.get_ipython = get_ipython | |
152 |
|
157 | |||
153 | # Modify the IPython system call with one that uses getoutput, so that we |
|
158 | # Modify the IPython system call with one that uses getoutput, so that we | |
154 | # can capture subcommands and print them to Python's stdout, otherwise the |
|
159 | # can capture subcommands and print them to Python's stdout, otherwise the | |
155 | # doctest machinery would miss them. |
|
160 | # doctest machinery would miss them. | |
156 | ip.shell.system = xsys |
|
161 | ip.shell.system = xsys | |
157 |
|
162 | |||
158 | # Also patch our %run function in. |
|
|||
159 | ## im = new.instancemethod(_run_ns_sync,_ip, _ip.__class__) |
|
|||
160 | ## ip.shell.magic_run_ori = _ip.magic_run |
|
|||
161 | ## ip.shell.magic_run = im |
|
|||
162 |
|
||||
163 | # XXX - For some very bizarre reason, the loading of %history by default is |
|
163 | # XXX - For some very bizarre reason, the loading of %history by default is | |
164 | # failing. This needs to be fixed later, but for now at least this ensures |
|
164 | # failing. This needs to be fixed later, but for now at least this ensures | |
165 | # that tests that use %hist run to completion. |
|
165 | # that tests that use %hist run to completion. | |
166 | from IPython.core import history |
|
166 | from IPython.core import history | |
167 | history.init_ipython(ip.shell) |
|
167 | history.init_ipython(ip.shell) | |
168 | if not hasattr(ip.shell,'magic_history'): |
|
168 | if not hasattr(ip.shell,'magic_history'): | |
169 | raise RuntimeError("Can't load magics, aborting") |
|
169 | raise RuntimeError("Can't load magics, aborting") | |
|
170 | ||||
|
171 | return _ip |
General Comments 0
You need to be logged in to leave comments.
Login now